google Ads

Wednesday, October 28, 2009

index

Java Index Page


Understanding Common SQL statements
Important JDBC Concepts
This java.sql package
Driver Manager Class
UnderstandingData Source
Understanding Connection Object
JDBC Steps
Explanation of JDBC Steps:
BDK Customizers


Overview of JAVA
Java Platform
Structure of a Java program
How to compile and run a code
Development Files and Directories
Variables
Data Types
Integers
Floating-Point
Characters
Booleans
Variable names
Scope
Variable Initialization
Final Variables
Arrays
Double Dimensional Array in JAVA
Operators in JAVA
Arithmetic operators
Increase and decrease
Logical operators
Control Structures
If statements
if-else statements
Nested if-else
Switch Statement
While Loop
JAVA INDEX PAGE
Do-while
For Loop
Branching Statement
Break Statement
Continue Statement
Return Statement

DATA Source

Understanding Data Source


The JDBC API provides the DataSource interface as an alternative to the DriverManager for establishing the connection. A DataSource object is the representation of database or the data source in the Java programming language. DataSouce object is mostly preferred over the DriverManager for establishing a connection to the database.

DataSource object can be thought as a factory for making connections to the particular database that the DataSource instance represents.

DataSource has a set of properties that identify and describe the real world data source that it represents. The properties include information about the location of the database server, the network protocol use to communicate with the server the name of the database and so on.
DataSource object works with JNDI (Java Naming and Directory interface) naming service so application can use the JNDI API to access the DataSource object.
In short we can say that the DataSource interface is implemented to provide three kinds of connections:
1). Basic DataSource class
This class is provided by the driver vendor. It is used for portability and easy maintence.
2). To provide connection pooling.
It is provided by the application server vendor or driver vendor. It works with ConnectionPoolDataSource class provided by a driver vendor. Its advantage is portability, easy maintenence and increased performance.
3). To provide distributed transactions
This class works with an XADataSource class, which is provided by the driver vendor. Its advantages are easy maintenence, portability and ability to participate in distributed transactions.

Tuesday, September 29, 2009

Understanding Common SQL statements

Common SQL statements


The commonly used SQL statements are:


1): Select

2): Insert

3): Update

4): Delete


SQL Select statement:


The SELECT statement is used to select data from a table.

Syntax:

Select column_names FROM table_name;


The result from a SQL query is stored in a resultset. The SELECT statement has mainly three clauses.


1). Select

2.) From

3). Where


The Select specifies the table columns that are retrieved. The From clause tells from where the tables has been accessed. The Where clause specifies which tables are used. The Where clause is optional, if not used then all the table rows will be selected.


We can see that we have used semicolon at the end of the select statement. It is used to separate each SQL statement in database Systems which helps us to execute more than one SQL statement in the same call to the Server.


SQL INSERT Statement:


This statement allows you to insert a single or multiple records into the Database. We can specify the name of the column in which we want to insert the data.


Syntax:

Insert into table_name values (value1, value2..);


The Insert statement has mainly three clauses.


1). Insert: It specifies which table column has to be inserted in the table.

2). Into : It tells in which the data will be stored.

3). Values: In this we insert the values we have to insert. We can also specify the columns for which we want to insert data.


The UPDATE Statement:


The Update statement is used to modify the data in the table. Whenever we want to update or delete a row then we use the Update statement.


syntax :


UPDATE table_name Set colunm_name = new_value WHERE column_name = some_name;


The Update statement has mainly three clauses.


1). UPDATE: It specifies which table column has to be updated.

2). Set: It sets the column in which the data has to be updated.

3). Where: It tells which tables are used.


SQL DELETE Statement:


This delete statement is used to delete rows in a table.


Systax:


DELETE FROM table_name WHERE column_name = some_name;


The Delete statement has following clauses.


1). Delete: It specifies which table column has to be deleted.

2). From: It tells from where the Table has been accessed.

3). Where: It tells which tables are used.

Sunday, September 20, 2009

Important JDBC Concepts

JDBC Concepts


Transactions:

Whenever a connection is created by using the JDBC, then by default it is in auto- commit mode. This means that SQL statement will be automatically committed immediately after it is executed and it is treated as a transaction. But imagine a situation where you want to execute a batch of statements, either they should commit at on go or they should get failed together. For this we need to disable the auto- commit mode by using the method:con.setAutoCommit(false).
After setting the auto- commit as false, no SQL statement will be committed until we call the con.commit() method. If there arises any problem while committing then the set of statements will be rollback, without committing. Logging: on the server--->logging--->JDBC.By this we can enable JDBC logging and specify a log file name for the JDBC log.

Attributes of Logging:

1) Enable JDBC Logging: It determines whether the server has a JDBC log file.
2) JDBC Log File Name: It is the name of the log file.

Isolation:

The isolation is needed when there are concurrent transactions. Concurrent transactions are transactions are transactions that occurs at the same time. In isolation one transaction does not interfere with another. For setting the isolation level for a JDBC transaction, use theConnection.setTransaction(int level) method By using the snapshot isolation level we can only see the snapshot of the data locked by other transactions when running from inside the transaction with snapshot isolation level.

Some of the transaction level are given below:

1). TRANSACTION_NONE
2). TRANSACTION_READ_UNCOMMITED
3. TRANSACTION_READ_COMMITTED
4. TRANSACTION_REPEATABLE_READ
5. TRANSACTION_SERIALIZABLE

By setting the isolation levels you are having an impact on the performance of the transaction. You can get the existing isolation level with:getTransactionIsolation() method. Concurrency: Database concurrency controls ensure that the transactions occur in an ordered fashion. Concurrency control deals with the issue involved with allowing multiple people simultaneous access to shared entities.

Introduction to java.sql packageThis package provides the APIs for accessing and processing data which is stored in the database especially relational database by using the java programming language. It includes a framework where we different drivers can be installed dynamically to access different databases especially relational databases.

This java.sql package

This java.sql package contains API for the following


1 Making a connection with a database with the help of DriverManager class

a) DriverManager class: It helps to make a connection with the driver.
b) SQLPermission class: It provides a permission when the code is running within a Security Manager, such as an applet. It attempts to set up a logging stream through the DriverManager class.
c) Driver interface : This interface is mainly used by the DriverManager class for registering and connecting drivers based on JDBC technology.
d). DriverPropertyInfo class : This class is generally not used by the general user.

2). Sending SQL Parameters to a database :

a). Statement interface: It is used to send basic SQL statements.
b). PreparedStatement interface: It is used to send prepared statements or derived SQL statements from the Statement object.
c). CallableStatement interface : This interface is used to call database stored procedures.
d). Connection interface : It provides methods for creating statements and managing their connections and properties.
e). Savepoint : It helps to make the savepoints in a transaction.

3). Updating and retrieving the results of a query:

a). ResultSet interface: This object maintains a cursor pointing to its current row of data. The cursor is initially positioned before the first row. The next method of the resultset interface moves the cursor to the next row and it will return false if there are no more rows in the ResultSet object. By default ResultSet object is not updatable and has a cursor that moves forward only.

4.) Providing Standard mappings for SQL types to classes and interfaces in Java Programming language.

a). Array interface: It provides the mapping for SQL Array.
b). Blob interface : It provides the mapping for SQL Blob.
c). Clob interface: It provides the mapping for SQL Clob.
d). Date class: It provides the mapping for SQL Date.
e). Ref interface: It provides the mapping for SQL Ref.
f). Struct interface: It provides the mapping for SQL Struct.
g). Time class: It provides the mapping for SQL Time.
h). Timestamp: It provides the mapping for SQL Timestamp.
i). Types: It provides the mapping for SQL types.

5). Metadata

a). DatabaseMetaData interface: It keeps the data about the data. It provides information about the database.
b). ResultSetMetaData: It gives the information about the columns of a ResultSet object.
c). ParameterMetaData: It gives the information about the parameters to the PreparedStatement commands.

6). Exceptions

a). SQLException: It is thrown by the mehods whenever there is a problem while accessing the data or any other things.
b). SQLWarning: This exception is thrown to indicate the warning.
c). BatchUpdateException: This exception is thrown to indicate that all commands in a batch update are not executed successfully.
d). DataTruncation: It is thrown to indicate that the data may have been truncated.

7). Custom mapping an SQL user- defined type (UDT) to a class in the java programming language.

a). SQLData interface:
It gives the mapping of a UDT to an intance of this class.
b). SQLInput interface: It gives the methods for reading UDT attributes from a stream.
c). SQLOutput: It gives the methods for writing UDT attributes back to a stream.

Driver Manager Class


The JDBC Driver Manager


The JDBC Driver Manager is a very important class that defines objects which connect Java applications to a JDBC driver. Usually Driver Manager is the backbone of the JDBC architecture. It's very simple and small that is used to provide a means of managing the different types of JDBC database driver running on an application. The main responsibility of JDBC database driver is to load all the drivers found in the system properly as well as to select the most appropriate driver from opening a connection to a database. The Driver Manager also helps to select the most appropriate driver from the previously loaded drivers when a new open database is connected.

The DriverManager class works between the user and the drivers. The task of the DriverManager class is to keep track of the drivers that are available and handles establishing a connection between a database and the appropriate driver. It even keeps track of the driver login time limits and printing of log and tracing messages. This class is mainly useful for the simple application, the most frequently used method of this class is DriverManager.getConnetion(). We can know by the name of the method that this method establishes a connection to a database.

The DriverManager class maintains the list of the Driver classes. Each driver has to be get registered in the DriverManager class by calling the method DriverManager.registerDriver(). By calling the Class.forName() method the driver class get automatically loaded. The driver is loaded by calling the Class.forName() method. JDBC drivers are designed to tell the DriverManager about themselves automatically when their driver implementation class get loads.

This class has many methods.
Some of the commonly used methods are given below:

1. deregisterDriver(Driver driver) :
It drops the driver from the list of drivers registered in the DriverManager class.

2. registerDriver(Driver driver) :
It registers the driver with the DriverManager class.
3. getConnection(String url) :
It tries to establish the connection to a given database URL.
4. getConnection(String url, Sting user, String password) :
It tries to establish the connection to a given database URL.
5. getConnection(String url, Properties info) :
It tries to establish the connection to a given database URL.

6. getDriver(String url) :
It attempts to locate the driver by the given string.

7. getDrivers() :
It retrieves the enumeration of the drivers which has been registered with the DriverManager class.

UnderstandingData Source

Understanding Data Source


The JDBC API provides the DataSource interface as an alternative to the DriverManager for establishing the connection. A DataSource object is the representation of database or the data source in the Java programming language. DataSouce object is mostly preferred over the DriverManager for establishing a connection to the database.

DataSource object can be thought as a factory for making connections to the particular database that the DataSource instance represents.

DataSource has a set of properties that identify and describe the real world data source that it represents. The properties include information about the location of the database server, the network protocol use to communicate with the server the name of the database and so on.

DataSource object works with JNDI (Java Naming and Directory interface) naming service so application can use the JNDI API to access the DataSource object.

In short we can say that the DataSource interface is implemented to provide three kinds of connections:

1). Basic DataSource class

This class is provided by the driver vendor. It is used for portability and easy maintence.

2). To provide connection pooling.

It is provided by the application server vendor or driver vendor. It works with ConnectionPoolDataSource class provided by a driver vendor. Its advantage is portability, easy maintenence and increased performance.

3). To provide distributed transactions

This class works with an XADataSource class, which is provided by the driver vendor. Its advantages are easy maintenence, portability and ability to participate in distributed transactions.

Understanding Connection Object

Connection Object


A Connection object represents a connection with a database. When we connect to a database by using connection method, we create a Connection Object, which represents the connection to the database. An application may have one or more than one connections with a single database or many connections with the different databases also.

We can use the Connection object for the following things:

1). It creates the Statement, PreparedStatement and CallableStatement objects for executing the SQL statements.

2). It helps us to Commit or roll back a jdbc transactionn.

3). If you want to know about the database or data source to which you are connected then the Connection object gathers information about the database or data source by the use of DatabaseMetaData.

4). It helps us to close the data source. The Connection.isClosed() method returns true only if the Connection.close() has been called. This method is used to close all the connection.

Firstly we need to to establish the connection with the database. This is done by using the method DriverManager.getConnection().
This method takes a string containing a URL. The DriverManager class, attempts to locate a driver that can connect to the database represented by the string URL. Whenever the getConnection() method is called the DriverManager class checks the list of all registered Driver classes that can connect to the database specified in the URL.

Syntax:

String url = "jdbc: odbc: makeConnection";
Connection con = DriverManager.getConnection(url, "userID", "password");

JDBC Steps

JDBC Steps – Basic steps in writing a JDBC Application

This section gives you brief description of JDBC Steps for making connection with the database, executing the query and showing the data to the user. In this application we have connected to the MySQL database and retrieved the employee names from the database.
Here are the JDBC
Steps to be followed while writing JDBC program:

Loading Driver
• Establishing Connection
• Executing Statements
• Getting Results
• Closing Database Connection


Before explaining you the JDBC Steps for making connection to the database and retrieving the employee from the tables, we will provide you the structure of the database and sample data.
Here is the sql script to create table and populate the table with data:

Table structure for table `employee`

CREATE TABLE `employee` ( `employee_name` varchar(50) NOT NULL, PRIMARY KEY (`employee_name`) );


INSERT INTO `employee` (`employee_name`) VALUES
('Deepak Kumar'),
('Harish Joshi'),
('Rinku roy'),
('Vinod Kumar');

Data inserting in MySQL database table:

mysql> insert into employee values('Deepak Kumar');
mysql> insert into employee values('Harish Joshi');
mysql> insert into employee values('Harish Joshi');
mysql> insert into employee values('Rinku roy');
mysql> insert into employee values('Vinod Kumar');


mysql> select *from employee;

employee_name

Deepak Kumar

Harish Joshi

Rinku roy

Vinod Kumar

Here is the code of java program that retrieves all the employee data from database and displays on the console:

/*Import JDBC core packages.
Following statement imports the java.sql package, which contains the JDBC core API. */


import java.sql.*;
public class RetriveAllEmployees{
public static void main(String[] args) {
System.out.println("Getting All Rows from employee table!");
Connection con = null;
String url = "jdbc:mysql://localhost:3306/";
String db = "jdbc";
String driver = "com.mysql.jdbc.Driver";
String user = "root";
String pass = "root";
try{
Class.forName(driver);
con = DriverManager.getConnection(url+db, user, pass);
Statement st = con.createStatement();
ResultSet res = st.executeQuery("SELECT * FROM employee");
System.out.println("Employee Name: " );
while (res.next()) {
String employeeName = res.getString("employee_name");
System.out.println(employeeName );
}
con.close();
}
catch (ClassNotFoundException e){
System.err.println("Could not load JDBC driver");
System.out.println("Exception: " + e);
e.printStackTrace();
}
catch(SQLException ex){
System.err.println("SQLException information");
while(ex!=null) {
System.err.println ("Error msg: " + ex.getMessage());
System.err.println ("SQLSTATE: " + ex.getSQLState());
System.err.println ("Error code: " + ex.getErrorCode());
ex.printStackTrace();
ex = ex.getNextException(); // For drivers that support chained exceptions
}
}
}}

Friday, September 18, 2009

Explanation of JDBC Steps:

Explanation of JDBC
Steps

They are Five Steps to Explanation of JDBC

1. Loading Driver
2. Establishing Connection
3. Executing Statements
4. Getting Results
5. Closing Database Connection


Loading Driver

Loading Database driver is very first step towards making JDBC connectivity with the database. It is necessary to load the JDBC drivers before attempting to connect to the database. The JDBC drivers automatically register themselves with the JDBC system when loaded. Here is the code for loading the JDBC driver:Class.forName(driver).newInstance();


Establishing Connection

In the above step we have loaded the database driver to be used. Now its time to make the connection with the database server. In the Establishing Connection step we will logon to the database with user name and password. Following code we have used to make the connection with the database:con = DriverManager.getConnection(url+db, user, pass);

Executing Statements

In the previous step we established the connection with the database, now its time to execute query against database. You can run any type of query against database to perform database operations. In this example we will select all the rows from employee table. Here is the code that actually execute the statements against database:ResultSet res = st.executeQuery( "SELECT * FROM employee" );

Getting Results

In this step we receives the result of execute statement. In this case we will fetch the employees records from the recordset object and show on the console.
Here is the code:

while (res.next())
{
String employeeName = res.getInt( " employee_name " );

System.out.println( employeeName );

}

Closing Database Connection

Finally it is necessary to disconnect from the database and release resources being used. If you don’t close the connection then in the production environment your application will fail due to hanging database connections. Here is the code for disconnecting the application from database:


con.close();

In this section you learnt about the JDBC Steps necessary for performing database operations.

Output

C:\vinod>javac Employee.java
C:\vinod>java Employee

Getting All Rows from employee table!

Employee Name:

Deepak Kumar

Harish

JoshiRinku roy

Vinod Kumar

Friday, September 11, 2009

BDK Customizers

BDK Customizers

The OurButtonCustomizer serves as an example that demonstrates the mechanics of building a customizer.

OurButtonCustomizer:

Extends java.awt.Panel (a Component subclass).
Implements the Customizer interface, and uses a PropertyChangeSupport object to manage PropertyChangeListener registration and notification.

See the bound property section for a PropertyChangeSupport description.
Implements a default constructor:
public OurButtonCustomizer()
{
setLayout(null);
}

Is associated with its target class, ExplicitButton, by the following ExplicitButtonBeanInfo code: public BeanDescriptor getBeanDescriptor()
{
return new BeanDescriptor(beanClass, customizerClass);
}
private final static Class customizerClass = OurButtonCustomizer.class;

Monday, July 20, 2009

Overview of JAVA

Java is a two things:


One is Programming language

and another one is platform


Java Programming language



Java is a high-level programming language that is all of the following:


Simple

Object-oriented

Distributed

Interpreted

Robust

Secure

Architecture-neutral

Portable

High-performance

Multithreaded

Dynamic


Java is also unusual in that each Java program is both compiled and interpreted. With a compiler, you translate a Java program into an intermediate language called java bytecodes – the platform-independent codes interpreted by the Java interpreter. With an interpreter, each java bytecode instruction is parsed and run on the computer.


Compilation happens just once; interpretation occurs each time the program is executed.


The following figure illustrates how this works


How a Java Program works





You can think of Java bytecodes as the machine code instructions for the java Virtual Machine (JVM). Every Java interpreter, whether it’s a Java development tool or a Web browser that can run java applets, is an implementation of the Java VM. The Java VM can also be implemented in hardware.


Java bytecodes help make “write once, run anywhere” possible. You can compile your Java program into bytecodes on any platform that has a Java compiler. The bytecodes can then be run on any implementation of the Java VM. For example, the same Java program can run on Windows NT, Solaris, and Macintosh.


Java Platform

The Java Platform


A platform is the hardware or software environment in which a program runs. The Java platform differs from most other platforms in that it’s a software-only platform that runs on top of other, hardware-based platforms. Most other platforms are described as a combination of hardware and operating system.

The Java platform has two components:

The Java Virtual Machine (Java VM)
The Java Application Programming Interface (Java API)

The JVM. It’s the base for the Java platform and is ported onto various hardware-based platforms.

The Java API is a large collection of ready-made software components that provide many useful capabilities, such as graphical user interface (GUI) widgets. The Java API is grouped into libraries (PACKAGES) of related components.

As a platform-independent environment, Java can be a bit slower than native code. However, smart compilers, well-tuned interpreters, and just-in-time bytecode compilers can bring Java’s performance close to that of native code without threatening portability.

Sunday, July 19, 2009

Structure of a Java program

Structure of a Java program


The structure of a java program is very different from traditional programming languages like C or C++. In java we have to declare a class however simple the objective of our program be. This is because java is pure object oriented language. Through difficult to start with, it is clearly one of the best programming paradigms.


Syntax of Java program

public class

{

public static void main (String [] arguments)

{


statemenst;


}

}





Example


Public class myprogClass ------------- Step1

{

Public static void main (String[] arguments) ------------- Step2

{

System.out.println(“Good Morning”); ------------- Step 3

}

}


The above program is inside a file called myprogClass.java

The above program prints Good Morning in the standard output screen

The above code has to be stored in a file, which has same name as the public class. So the source file should have a name myprogClass.java

Let us analyze this code step by step

In Step1 we declare a class called myprogClass (We have to declare this)

In Step 2 we make declare a method called main, which takes in an array of String objects. This is starting point of any program. We are not allowed to change the signature of this method.

In Step 3 we call System.out.println() method which is inside an object called out, which is in turn inside an object called System. We will learn more about these Objects and classes later, as of now remember this statement, as we will be using this quite often.

How to compile and run a code

How to compile and run a code

Once the file myprogClass.java has been saved, we have to compile it and convert it into byte code.


The Java compilation does not create direct executable format. (.exe in MsDOS or MS Windows). Instead byte code for the source is generated which is run by Java Virtual Machine or JVM.


To compile a .java file we have to type

Syntax:


Prompt > javac

Example:

C:\javac myprogClass.java


To generates a file called myprogClass.class


To run a byte code (for a class), it must contain a static main() method as described above. In our case we have to type

C:\ java myprogClass


This runs the main method in that class. If no main method is found an error message saying ‘No main method found’ is displayed.

Note: Its better if you set the path to the directory in which the jdk is installed. Doing so will allow you to execute the above commands from any directory.


To do this add following line to your autoexec.bat file which is in the C:


Set path=”C:\jdk1.5\bin”


Here c:\jdk1.5\bin is the directory where java and javac are stored


Before we go ahead with programming in java it is good to know the directory structure of the JDK. It may not make much sense when looking for the first time, but it is very important from viewpoint of platform independence implementation in java.

Development Files and Directories

Development Files and Directories

This section describes the files and directories that are required to develop apps for the Java platform. ( The directories that are not required include demos, source code, and C header files. They are discussed in the following section, Additional Files and Directories ). The following diagram shows the most important directories.

C:\jdk1.5

The root directory of the SDK software installation. Contains copyright, license, and README files. Also contains src.jar, the archive of source code for the Java 2 platform.

C:\jdk1.5\bin


The executable files for the development tools contained in the Java Development Kit. The PATH environment variables should contain an entry for this directory. For more information on the tools, see the SDK Tools.




Variables

Variables


A variable is an entity that can change values during the program execution. Variables are the nouns of any programming language. They are the entities (values and data ) that act or are acted upon.



All variables in Java must be clearly declared and initialized before using it. This may sound a little uncomfortable at first, at it is one way to ensure safe programming.

Data Types

Data Types



Java defines eight simple types of data:

byte
short
int
long
char
float
double
boolean

These can be put in four groups:

Integers This group includes byte, short, int, and long, which are for whole valued
signed numbers.

Floating-point numbers This group includes float and double, which represent
numbers with fractional precision.

Characters This group includes char, which represents symbols in a character
set, like letters and numbers.

Boolean This group includes boolean, which is a special type for representing
true/false values.


JAVA LANGUAGE

The simple types represent single values—not complex objects. Although Java is
otherwise completely object-oriented, the simple types are not. They are analogous to
the simple types found in most other non–object-oriented languages. The reason for
this is efficiency. Making the simple types into objects would have degraded performance too much.

The simple types are defined to have an explicit range and mathematical behavior.
Languages such as C and C++ allow the size of an integer to vary based upon the
dictates of the execution environment. However, Java is different. Because of Java’s
portability requirement, all data types have a strictly defined range. For example, an
int is always 32 bits, regardless of the particular platform. This allows programs to be
written that are guaranteed to run without porting on any machine architecture. While
strictly specifying the size of an integer may cause a small loss of performance in some environments, it is necessary in order to achieve portability.

Integers

Integers

Java defines four integer types: byte, short, int, and long. All of these are signed, positive and negative values. Java does not support unsigned, positive-only integers. Many other computer languages, including C/C++, support both signed and unsigned integers. However, Java’s designers felt that unsigned integers were unnecessary. Specifically, they felt that the concept of unsigned was used mostly to specify the behavior of the high-order bit, which defined the sign of an int when expressed as a number. Java manages the meaning of the high-order bit differently, by adding

a special “unsigned right shift” operator. Thus, the need for an unsigned integer type

was eliminated.

The width of an integer type should not be thought of as the amount of storage it

consumes, but rather as the behavior it defines for variables and expressions of that

type. The Java run-time environment is free to use whatever size it wants, as long as

the types behave as you declared them. In fact, at least one implementation stores bytes and shorts as 32-bit (rather than 8- and 16-bit) values to improve performance, because that is the word size of most computers currently in use.


The width and ranges of these integer types vary widely, as shown in this table:


Name Width Range

long 64 9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

int 32 2,147,483,648 to 2,147,483,647

short 16 32,768 to 32,767

byte 8 128 to 127

THE

JAVA

LANGUAGE

long


long is a signed 64-bit type and is useful for those occasions where an int type is not

large enough to hold the desired value. The range of a long is quite large. This makes

it useful when big, whole numbers are needed. For example, here is a program that

computes the number of miles that light will travel in a specified number of days.

// Compute distance light travels using long variables.

class Light

{

public static void main(String args[])

{

int lightspeed;

long days;

long seconds;

long distance;

// approximate speed of light in miles per second

lightspeed = 186000;

days = 1000; // specify number of days here

seconds = days * 24 * 60 * 60; // convert to seconds

distance = lightspeed * seconds; // compute distance

System.out.print("In " + days);

System.out.print(" days light will travel about ");

System.out.println(distance + " miles.");

}

}

This program generates the following output:

In 1000 days light will travel about 16070400000000 miles.

Clearly, the result could not have been held in an int variable.

Int

The most commonly used integer type is int. It is a signed 32-bit type that has a range

from –2,147,483,648 to 2,147,483,647. In addition to other uses, variables of type int are commonly employed to control loops and to index arrays. Any time you have an integer expression involving bytes, shorts, ints, and literal numbers, the entire expression is promoted to int before the calculation is done.

The int type is the most versatile and efficient type, and it should be used most of

the time when you want to create a number for counting or indexing arrays or doing

integer math. It may seem that using short or byte will save space, but there is no

guarantee that Java won’t promote those types to int internally anyway. Remember,

type determines behavior, not size. (The only exception is arrays, where byte is

guaranteed to use only one byte per array element, short will use two bytes, and int

will use four.)

short

short is a signed 16-bit type. It has a range from –32,768 to 32,767. It is probably the

least-used Java type, since it is defined as having its high byte first (called big-endian

format). This type is mostly applicable to 16-bit computers, which are becoming

increasingly scarce.

Here are some examples of short variable declarations:

short s;

short t;

byte

The smallest integer type is byte. This is a signed 8-bit type that has a range from –128 to 127. Variables of type byte are especially useful when you’re working with a stream of data from a network or file. They are also useful when you’re working with raw binary data that may not be directly compatible with Java’s other built-in types.

Byte variables are declared by use of the byte keyword. For example, the following

declares two byte variables called b and c: byte b, c;

Floating-Point

Floating-Point Types


Floating-point numbers, also known as real numbers, are used when evaluating
expressions that require fractional precision. For example, calculations such as square
root, or transcendentals such as sine and cosine, result in a value whose precision
requires a floating-point type. Java implements the standard set of



floating-point types and operators. There are two kinds of floating-point types,

float
double
which represent single- and double-precision numbers, respectively. Their
width and ranges are shown here:
Name Width in Bits Approximate Range
double 64 4.9e–324 to 1.8e+308
float 32 1.4e045 to 3.4e+038
Each of these floating-point types is examined next.


Float

The type float specifies a single-precision value that uses 32 bits of storage. Single
precision is faster on some processors and takes half as much space as double precision, but will become imprecise when the values are either very large or very small. Variables of type float are useful when you need a fractional component, but don’t require a large degree of precision. For example, float can be useful when representing dollars and cents.
Here are some example float variable declarations:
float hightemp, lowtemp;


double

Double precision, as denoted by the double keyword, uses 64 bits to store a value. Double precision is actually faster than single precision on some modern processors that have been optimized for high-speed mathematical calculations. All transcendental math functions, such as sin( ), cos( ), and sqrt( ), return double values. When you need to maintain accuracy over many iterative calculations, or are manipulating large-valued numbers, double is the best choice.
Here is a short program that uses double variables to compute the area of a circle:
// Compute the area of a circle.
class Area

{

public static void main( String args[] )

{

double pi, r, a;

r = 10.8; // radius of circle

pi = 3.1416; // pi, approximately

a = pi * r * r; // compute area

System.out.println("Area of circle is " + a);

}
}

Friday, July 17, 2009

Characters

Characters


In Java, the data type used to store characters is char. However, C/C++ programmers

beware: char in Java is not the same as char in C or C++. In C/C++, char is an integer type that is 8 bits wide. This is not the case in Java. Instead, Java uses Unicode to represent characters. Unicode defines a fully international character set that can represent all of the characters found in all human languages. It is a unification of dozens of character sets, such as Latin, Greek, Arabic, Cyrillic, Hebrew, Katakana, Hangul, and many more. For this purpose, it requires 16 bits. Thus, in Java char is a 16-bit type. The range of a char is 0 to 65,536. There are no negative chars. The standard set of characters known as ASCII still ranges from 0 to 127 as always, and the extended 8-bit character set, ISO-Latin-1, ranges from 0 to 255. Since Java is designed to allow applets to be written for worldwide use, it makes sense that it would use Unicode to represent characters. Of course, the use of Unicode is somewhat inefficient for languages such as English, German, Spanish, or French, whose characters can easily be contained within 8 bits. But such is the price that must be paid for global portability.

Here is a program that demonstrates char variables:

// Demonstrate char data type.

class CharDemo {

public static void main(String args[]) {

char ch1, ch2;

ch1 = 88; // code for X

ch2 = 'Y';

System.out.print("ch1 and ch2: ");

System.out.println(ch1 + " " + ch2);

}

}

This program displays the following output:

ch1 and ch2: X Y

Notice that ch1 is assigned the value 88, which is the ASCII (and Unicode) value that

corresponds to the letter X. As mentioned, the ASCII character set occupies the first

127 values in the Unicode character set. For this reason, all the “old tricks” that you

have used with characters in the past will work in Java, too. Even though chars are not integers, in many cases you can operate on them as if they were integers. This allows you to add two characters together, or to increment the value of a character variable.

For example, consider the following program:

// char variables behave like integers.

class CharDemo2

{

public static void main(String args[])

{

char ch1;

ch1 = 'X';

System.out.println("ch1 contains " + ch1);

ch1++; // increment ch1

System.out.println("ch1 is now " + ch1);

}

}

The output generated by this program is shown here:

ch1 contains X

ch1 is now Y

In the program, ch1 is first given the value X. Next, ch1 is incremented. This results in ch1 containing Y, the next character in the ASCII (and Unicode) sequence.

if(b == true) ...

Third, the outcome of a relational operator, such as <, is a boolean value. This is why

the expression 10 > 9 displays the value “true.” Further, the extra set of parentheses

around 10 > 9 is necessary because the + operator has a higher precedence than the >.

Booleans

Booleans


Java has a simple type, called boolean, for logical values. It can have only one of two

possible values, true or false. This is the type returned by all relational operators, such

as a < >. boolean is also the type required by the conditional expressions that govern the

control statements such as if and for.

Here is a example program for the boolean type:

THEJAVA

LANGUAGE

// Demonstrate boolean values.

class BoolTest

{

public static void main(String args[])

{

boolean b;

b = false;

System.out.println("b is " + b);

b = true;

System.out.println("b is " + b);

// a boolean value can control the if statement

if(b) System.out.println("This is executed.");

b = false;

if(b) System.out.println("This is not executed.");

// outcome of a relational operator is a boolean value

System.out.println("10 > 9 is " + (10 > 9));

}

}

The Output will be:

b is false

b is true

This is executed.

10 > 9 is true

There are three interesting things to notice about this program. First, as you can see,

when a boolean value is output by println( ), “true” or “false” is displayed. Second,

the value of a boolean variable is sufficient, by itself, to control the if statement. There is no need to write an if statement like this: