Friday, July 26, 2013

Bit field in C++

Declares a class data member with explicit size, in bits. Adjacent bit field members may be packed to share and straddle the individual bytes.
A bit field declaration is a class data member declaration which uses the following declarator:
identifier(optional) attr(optional) : size(1)
The type of the bit field is introduced by the decl-specifier-seq of the declaration syntax.
attr(C++11)-optional sequence of any number of attributes
identifier-the name of the bit field that is being declared. The name is optional: nameless bitfields introduce the specified number of bits of padding
size-an integral constant expression with a value greater or equal to zero. When greater than zero, this is the number of bits that this bit field will occupy. The value zero is only allowed for nameless bitfields and has special meaning: it specifies that the next bit field in the class definition will begin at an allocation unit's boundary.

Explanation

The number of bits in a bit field sets the limit to the range of values it can hold:
#include <iostream>
struct S {
 // three-bit unsigned field,
 // allowed values are 0...7
 unsigned int b : 3;
};
int main()
{
    S s = {7};
    ++s.b; // unsigned overflow
    std::cout << s.b << '\n'; // output: 0
}
Multiple adjacent bit fields are usually (but it's implementation defined if) packed together:
#include <iostream>
struct S {
    // will usually occupy 2 bytes:
    // 3 bits: value of b1
    // 2 bits: unused
    // 6 bits: value of b2
    // 2 bits: value of b3
    // 3 bits: unused
    unsigned char b1 : 3, : 2, b2 : 6, b3 : 2;
};
int main()
{
    std::cout << sizeof(S) << '\n'; // usually prints 2
}
The special unnamed bit field of size zero can be forced to break up padding. It specifies that the next bit field begins at the beginning of its allocation unit:
#include <iostream>
struct S {
    // will usually occupy 2 bytes:
    // 3 bits: value of b1
    // 5 bits: unused
    // 6 bits: value of b2
    // 2 bits: value of b3
    unsigned char b1 : 3;
    unsigned char :0; // start a new byte
    unsigned char b2 : 6
    unsigned char b3 : 2;
};
int main()
{
    std::cout << sizeof(S) << '\n'; // usually prints 2
}
If the specified size of the bit field is greater than the size of its type, the value is limited by the type: astd::uint8_t b : 1000; would still hold values between 0 and 255. the extra bits become unused padding.
Because bit fields do not necessarily begin at the beginning of a byte, address of a bit field cannot be taken. Pointers and non-const references to bit fields are not possible. When initializing a const reference from a bit field, a temporary is created (its type is the type of the bit field), copy initialized with the value of the bit field, and the reference is bound to that temporary.
The type of a bit field can only be integral or enumeration type.
A bit field cannot be a static data member.

Notes

The following properties of bit fields are implementation-defined
  • Everything about the actual allocation details of bit fields within the class object
  • For example, on some platforms, bit fields don't straddle bytes, on others they do
  • Also, on some platforms, bit fields are packed left-to-right, on others right-to-left
  • Whether charshortintlong, and long long bit fields that aren't explicitly signed or unsigned are signed or unsigned.
  • For example, int b:3; may have the range of values 0..7 or -4..3.



Thanks : cppreference.com

Saturday, June 29, 2013

What is the difference between C# and C++?

        C# is a programming language that is derived from C programming language and C++ programming language. C# is uniquely designed to be used in .NET platform. The differences between C# and C++ are: 
C#
C++
C# is a high level language that is component oriented.
C++ is a low level and indeed platform neutral programming language.
When compiled, C# code is converted into Intermediate language code. This intermediate language code is converted into executable code through the process called Just-In-Time compilation.
When compiled, C++ code is converted into assembly language code.
In C#, memory management is automatically handled by garbage collector.
In C++, the memory that is allocated in the heap dynamically has to be explicitly deleted.
In C# Switch Statement, the test variable can be a string.
In C++ Switch Statement, the test variable cannot be a string.
In C# switch statement, when break statement is not given, the fall through will not happen to the next case statement if the current case statement has any code.
In C++ switch statement, when break statement is not given, the fall through will happen to the next case statement even if the current case statement has any code.
In addition to for, while and do..while, C# has another flow control statement called for each.
C++ does not contain for each statement.
C# struts can contain only value types. The struts is sealed and it cannot have a default no-argument constructor.
C++ struts behave like classes except that the default access is public instead of private.
In C#, delegates, events and properties can also be specified as class members.
In C++, only variables, constructors, functions, operator overloads and destructors can be class members. Delegates, events and properties cannot be specified as class members.
In C#, the end of the class definition has a closing brace alone.
In C++, the end of the class definition has a closing brace followed by a semicolon.
The access modifiers in C# are public, private, protected, internal and protected internal.
The access modifiers in C++ are public, private, protected. C++ does not have internal and protected internal access modifiers.
C# has finally block in exception handling mechanism. The code statements in the finally block will be executed once irrespective of exception occurrence.
C++ does not have finally block in exception handling mechanism.
The exception in C# can only throw a class that is derived from the System.Exception class.
The exception in C++ can throw any class.
C# does not have the concept of function pointers. C# has a similar concept called Delegates.
C++ has the concept of function pointers.

ASP.Net Web API and REST Services

            This article explains what a REST Service actually is and how the ASP.NET Web API helps with the creation of such services.

What Is a Restful Service?

Representational State Transfer (REST) is an architectural style. A service that conforms to the REST constraints is referred to as being RESTful

To be RESTful, a service has to conform to the following mandatory constraints:
  1. Client-Server constraint, which is based on the separation of concerns, is about separating user interface concerns from data storage concerns. Clients are not concerned with data storage, which is a concern of servers, and servers are not concerned with the user interface or user state, which are concerns of clients. 
  2. Stateless constraint, is about each request being an independent self-contained unit with all the necessary information for the server to service the request without looking at anything else for the context. 
  3. Cache constraint, is about the server being able to label a response as Cacheable or not, so that the client handles the response appropriately from the point of view of later use.
  4. Layered constraint, is about composing the system into layers, with each layer being able to see and interact with only its immediate neighbor. A layer cannot see through its neighbor. Between the client and the server, there could be any number of intermediaries; caches, tunnels, proxies, and so on.
  5. Uniform Interface constraint, is about providing a uniform interface for identification of resources, the manipulation of resources through representations, self-descriptive messages, and hypermedia as the engine of the application state.
Let's see how a service built with the ASP.NET Web API Framework satisfies the given constraints.

The client-server constraint is an easy one to satisfy since the ASP.NET Web API is all about responding to the client request with the data, without bothering about the client state or how data will be presented to the end user.

The stateless constraint can also be easily satisfied, unless something horrible is done such as using the ASP.NET session state from the web API.

ASP.NET MVC supports the OutputCache attribute that can be used to control output caching. The ASP.NET Web API has no built in ways to support this feature out of the box, but it's easy to roll out our own action filter attribute. The ASP.NET Web API can use a Cache-Control response header to label a response as Cacheable or not. By default, Cache-Control is set to no-cache and the response is not cached. This way it satisfies the Cache constraint.

The layered constraint is more along the infrastructure line-proxies, firewalls, and so on. There is nothing special that needs to be done from the ASP.NET Web API to satisfy this constraint.

The uniform interface constraint includes the following four constraints and is a key factor in deciding if an HTTP service is RESTful or not:
  1. Identification of resources
  2. Manipulation of resources through representations
  3. Self-descriptive messages
  4. Hypermedia as the engine of application state (HATEOAS)
Let's have a look at a unique interface constraint in detail through each of the four constraints.

1. Identification of Resources

A resource is any data that a web API sends to its clients. Examples could be an individual employee in your company, a product that your company sells etc. In the real world, a product or an employee could be uniquely identified through an identifier, such as a product ID or an employee ID.

In the case of RESTful web services, a resource is identified by a Uniform Resource Identifier (URI). An employee with an identifier of 12345 will be represented by http://myServer/employees/12345. In the case of the ASP.NET Web API, the URI can be slightly different and it includes "api" by default in the URI, so it will be more like http://myServer/api/employees/12345. If you fire up an instance of Internet Explorer, enter that URI in the address bar, and press Enter then Internet Explorer does an HTTP GET and you will get the JSON representation of the resource, which is an employee with the ID of 12345 in this case.

From the .NET code point of view (see Listing 2-1), the corresponding class will be EmployeesController, which is a subclass of ApiController and the method that executes to create the resource representation to be sent back to the client in its Get(int) method. Observe the code snippet below:

Identification-of-Resources.jpg

Picture 1 - Identification of Resources

You see here that a known resource with the URI representation http://myServer/api/employee/12345 is accessed using the GET HTTP Method. A list of employees is also a resource identified by http://myServer/api/employees pointing to the GetAllEmployees() method.

2. Manipulation of Resources through Representations

The example of a user typing http://myServer/api/employees/12345 in Internet Explorer can be described as a user requesting a resource using the GET verb and getting back the employee JSON, which is the representation of the resource. GET is guaranteed not to cause any side effect and is said to be nullipotent; nothing happens to the system's state, even when called multiple times or not called at all. In other words, the system state will be the same for all the following scenarios: (1) method was not called at all, (2) method was called once, and (3) method was called multiple times.

Other important verbs are POST, PUT, and DELETE. POST is for creating a new resource, PUT is for updating an existing resource, and DELETE is for deleting an existing resource. PUT and DELETE are idempotent; the effect to the system state will be the same as that of the first call, even when called multiple times subsequent to the first call.

To create a new employee, the client sends a POST request, with the new employee (JSON or XML representation) in the body of the request. This request gets mapped to a method with a name starting with Post, which is Post(Employee) in this case.

Updating an employee is the same as creating a new employee except that the PUT verb is used and mapping is based on the name starting with Put. One important difference compared to POST is that PUT is idempotent. If a user sends multiple requests to update an employee to the same state, no error must be sent back.

Deleting an employee is similar except that a resource representation is not needed. A DELETE request against the URI will be sufficient to delete the resource. Similar to PUT, the DELETE method is also idempotent. Even if the underlying data source sends an error back when the employee to be deleted no longer exists, because it is already deleted in response to the previous request then no error must be sent back.

Manipulation-of-Resources-through-representations.jpg

Picture 2 - Manipulation of Resources through representations

For all the preceding actions, a status code is the means through which the status of the action is communicated back. By default it is 200 – OK, indicating success. As a special case, 201 – Created gets sent for POST, when a resource was created. 401 – Not Authorized gets sent when a user requests an action on a resource that requires the user to be authenticated and that user has either not provided the credentials or provided invalid credentials. 404 – Not Found gets sent when the user has requested an action on a resource that does not exist.

3. Self-Descriptive Messages

A resource can have multiple representations, JSON and XML being just two examples. A request body having a specific representation of a resource must have a self-description of the representation so that it is parsed and handled correctly. The same holds for responses.

In the ASP.NET Web API, the Multipurpose Internet Mail Extensions (MIME) type determines how the web API serializes or deserializes the message body. There is built-in support for XML, JSON, and form-url encoded data. 

Let's take the case of a request to create a new employee, the corresponding code snippet in the picture below, to review a few scenarios.

Self-Descriptive-Messages.jpg

Picture 3- Self-Descriptive Messages

Scenario 1: JSON Representation

Here is an example of a request–response message pair with JSON being the content type for both messages. The web API determines the media-type formatter to be used based on the content type. Because it is JSON, it uses JsonMediaTypeFormatter to deserialize JSON in the CLR object of type Employee named value. Again on the way out, the CLR object to be returned, in this case an object of Employee type, is serialized into JSON. If the request content type comes in as XML then XmlMediaTypeFormatter would have been used to deserialize and this entire process is seamless to the action method code, since it always receives the Employee object. This is one of the powerful features of the ASP.NET Web API.

Request Sent

POST /api/employees HTTP/1.1
Content-Type: application/json; charset=utf-8
Content-Length: 49
{"Name":"John Q Law", "Department":"Enforcement"}

Response Received

HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
{"Department":"Enforcement","Id":"123","Name":"John Q Law"}

Scenario 2: No Content Type

What if there is no content type specified in the request header? The ASP.NET Web API will not know what to do with the message. The web API returns 500 – Internal Server Error with a message that no MediaTypeFormatter is available to read the object of the type Employee with media type undefined.

Request Sent

POST /api/employees HTTP/1.1
Content-Length: 49
{"Name":"John Q Law", "Department":"Enforcement"}

Response Received

HTTP/1.1 500 Internal Server Error
Content-Type: application/json; charset=utf-8
{"ExceptionType":"System.InvalidOperationException","Message":"No 'MediaTypeFormatter' is available to read an object of type 'Employee' with the media type ''undefined''.","StackTrace":" at System.Net.Http.ObjectContent.SelectAndValidateReadFormatter(..."}

Scenario 3: XML Representation

If the content type is specified for XML and the XML representation of the resource is sent in the request message body then it starts to work again. The web API uses XmlMediaTypeFormatter, although this time around the resource sent back in the response also becomes XML.

Request Sent

POST /api/employees HTTP/1.1
Content-Type: application/xml; charset=utf-8
Content-Length: 80
<Employee><Name>John Q Law</Name><Department>Enforcement</Department></Employee>

Response Received

HTTP/1.1 200 OK
Content-Type: application/xml; charset=utf-8
<?xml version="1.0" encoding="utf-8"?><Employee xmlns:xsi="http://www.w3.org/2001/XMLSchemainstance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"><Id>123</Id><Name>John Q Law</
Name><Department>Enforcement</Department></Employee>

Scenario 4: Mix and Match

It is possible to mix and match, that is, send the XML representation of the resource in the request body and ask for JSON to be returned or vice versa. If a web API is capable of handling the content type specified in the Accept header then it will send the resource in that representation. In the following example request, the client sends the request body as XML and indicates the same by specifying application/xml in Content-Type. However, the client prefers the response to be returned as JSON and indicates that preference by specifying application/json in the Accept header.

Request

POST /api/employees HTTP/1.1
Content-Type: application/xml; charset=utf-8
Accept: application/json
Content-Length: 80
<Employee><Name>John Q Law</Name><Department>Enforcement</Department></Employee>

Response

HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
{"Department":"Enforcement","Id":"123","Name":"John Q Law"}

The key point to note in this transaction is that the client asks and does not tell the server. If the Accept header of application/pdf, application/json is sent in the request then the ASP.NET Web API will not be able to send the response back as PDF, by default, and hence switches to the second choice, JSON. This process is therefore called Content Negotiation.

It is interesting to note that a web API switches to XML if the Accept header has just the application/pdf. It can't send a PDF for sure but there is nothing else specified as the second choice, so it switches over to the MIME type of the request, which is XML in this case.

4. Hypermedia as the Engine of Application State

The HATEOAS constraint requires a client to enter a RESTful service through a fixed URL. From that point onward, any future action a client takes will be based on what the client gets to discover within the resource representation returned by the service.

Let's take an example. A client makes a GET request to the resource with the identifier http://server/api/employees. In other words, the client is asking for a list of employees. As the next step, if the client needs to GET an employee, how will it go about doing it? One option is that the client "knows" it! Then, the client has to know quite a bit about the service. Another option is hypermedia, or hypertext. A service that satisfies the HATEOAS constraint returns not just data, but data and links.
In the previous example of the employee listing, each employee can have multiple links; one to look at employee details, or one perhaps to fire him, for example. Of course, the links available will be based on what the client is authorized to do. For a user who is not authorized to fire employees, there is no point in sending the firing link. Here is an example JSON representation of an employee resource with links.

Hypermedia-as-the-Engine-of-Application-State.jpg

Picture 4 - Hypermedia as the Engine of Application State

One obvious problem is what the client will do with the links. To get details, GET must be executed and for the next one, DELETE, probably, but how will the client know? The answer to the question is forms, which will contain all the necessary information for the client to make the next move.

HATEOAS is not supported by the ASP.NET Web by default if you expect a web API to provide links or forms intelligently without ever writing a line of code. However, it is possible to include them in the resource representation returned by writing your own custom code.
 
Thanks : c-sharpcorner



Thank you for reading this article, I hope you enjoyed it. Feedback and comments are highly appreciated. Follow for more!!

REST(Representational state transfer) Software Architecture



                         
                  The REST architectural style was developed by W3C Technical Architecture Group in parallel with HTTP/1.1, based on the existing design of HTTP/1.0. The World Wide Webrepresents the largest implementation of a system conforming to the REST architectural style. REST exemplifies how the Web's architecture emerged by characterizing and constraining the macro-interactions of the four components of the Web, namely origin serversgatewaysproxies and clients, without imposing limitations on the individual participants. As such, REST essentially governs the proper behavior of participants.
REST-style architectures consist of clients and servers. Clients initiate requests to servers; servers process requests and return appropriate responses. Requests and responses are built around the transfer of representations of resources. A resource can be essentially any coherent and meaningful concept that may be addressed. A representation of a resource is typically a document that captures the current or intended state of a resource.
The client begins sending requests when it is ready to make the transition to a new state. While one or more requests are outstanding, the client is considered in transition. The representation of each application state contains links that may be used the next time the client chooses to initiate a new state-transition.
REST facilitates the transaction between web servers by allowing loose coupling between different services. REST is less strongly typed than its counterpart, SOAP. The REST language uses nouns and verbs, and has an emphasis on readability. Unlike SOAP, REST does not require XML parsing and does not require a message header to and from a service provider. This ultimately uses less bandwidth. REST error-handling also differs from that used by SOAP.

Friday, June 28, 2013

Creating Your First Android Application (SMS App)

                  Beginning Android tutorial series covered the overview of the Android platform. If you haven't seen it yet, please take some time to read it before reading this article.

                  In this article, you will develop your first Android application. You will learn how to send SMS programmatically within an Android application.
NOTE: This tutorial assumes that you are familiar with Java programming and IDE's like Eclipse and NetBeans.



Brief Contents
  1. The Four Components of Android
  2. Creating The SMS Application
    • Obtaining The Required Tools
    • Developing SendingSMS project



The Four Components of Android

Your Android projects should contain at least one class that is derived from one of these components:
  • Activity - If your Android application has a UI, you must create one class that extends this component. You will learn how to create an Activity in this article.
  • Service - If your Android application has a long running task, you should do it in the background and not in the UI thread. This class provides the facility to make a task run in the background.
  • BroadcastReceiver - If your Android application will receive and respond to global events such as the sending and delivery of SMS, your class must be registered as a subclass of this component. You will learn how to use this component to get feedback after sending SMS.
  • ContentProvider - If your Android application has data that you wants to share with other Android applications, you should create and implement this component.
For the detailed look at the Android Build process please refer to Android documentation.

Creating The SMS Application

Android development has four phases. Below is a diagram of Android development process:

Obtaining The Required Tools

Before you can start creating Android application, you must setup your development environment first. You will need the following to develop our SMS application:
  • Android SDK
  • Eclipse (Helios or greater)
NoteYou need to install at least the Android 1.6 platform for this tutorial.
See Android Installation Instructions and System Requirements for more information and watch this video to learn how to setup your development environment for the first time on Windows. 
I use Windows 7, Java 7, Eclipse Indigo for Java Developers, ADT and Android SDK revision 17 in this screencast.

Developing The SMS Project

SMS messaging is one of the killer applications on Android or any mobile phones today. Let's create your first simple and practical Android project. I assume that you are already familiar with Java programming; I will not explain each line of code in detail.

Follow these steps:
1. Start your Eclipse IDE

2. Go to File -> New -> Project

3. Select Android Project in the New Project dialog
4. Complete the New Android Project wizard.



5. Open main.xml (located in <your project's name>/res/layout) and replace its contents with the code below:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
    <EditText
        android:id="@+id/editRecipient"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="14dp"
        android:hint="@string/recipientHint"
        android:inputType="phone" />
    <EditText
        android:id="@+id/editMessage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_marginBottom="17dp"
        android:layout_toLeftOf="@+id/sendButton"
        android:hint="@string/messageBodyHint" >
    </EditText>
    <Button
        android:id="@+id/sendButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignTop="@+id/editMessage"
        android:onClick="send"
        android:text="@string/sendButtonText" />
</RelativeLayout>
Note: I used RelativeLayout here because I need to align each common form component relative to the other components.
6. Open SMSActivity.java (located in <your project's name>/src/<your package name>) and add the following code:
public void send(android.view.View view) {
final android.widget.EditText recipient = (android.widget.EditText) findViewById(R.id.editRecipient);
final android.widget.EditText message = (android.widget.EditText) findViewById(R.id.editMessage);
final android.telephony.SmsManager smsManager = android.telephony.SmsManager.getDefault();
final String addr = recipient.getText().toString();
final String text = message.getText().toString();
smsManager.sendTextMessage(addr, null, text, null, null);
recipient.setText("");
message.setText("");
}
7. To allow our application to send SMS, add the following permission to AndroidManifest.xml (located in your project's root directory):
<uses-permission android:name="android.permission.SEND_SMS" />
8. That's it. Deploy and run the project.


How It Works

Steps 1 to 4 show you how to create a new Android application in Eclipse. Steps 5 to 7 cover the code that will enable your new application to send SMS: step 5 changes the layout of your application's UI; step 6 includes the actual code that sends an SMS, and; step 7 includes a code snippet that informs our users about the permissions the application needs to send SMS. Step 8 shows you how to run the application.

The application uses the built-in Android telephony API class `android.telephony.SmsManager` to send SMS; for more information, see: documentation of SmsManager API.







Using Sqlite database in android

To quote from the website of sqlite
"SQLite is a software library that implements a self-contained serverless zero-configuration transactional  SQL database engine."
It is small database which an android programmer can use conveniently in his/her program.

Let us learn how to use sqlite database in steps.

Opening database : openOrCreateDatabas e fuction can be used to open an existing db or create a new one if it does not exist.
SQLiteDatabase mydb;
mydb = mContext.openOrCreateDatabase("mysqdb",
SQLiteDatabase.OPEN_READWRITE, null);

 First parameter is name of database and second one is mode of opening the file. Third parameter if present will be cursorfactory which is used to allow sub classes of cursor to be returned from a query. You can even use openDatabase function. On success the db is returned. The function throws SqliteException if there is error.

Next let us try to create a table with 3 fields - id, name and salary. We need to have a string which stores the create table sql statement.
String sqlStatement = "create table if not exists  nameSal" +  
"(_id Integer PRIMARY KEY AUTOINCREMENT ,Name text, salary Integer)";
mydb.execSQL(sqlStatement);

Note that _id field is made primary key as well as auto increment which will ensure each row gets unique _id automatically.
if not exists clause ensures that if the table is already present, there will not be any error. And the function call just returns.

execSQL will execute the SQL statement and creates the table. 

Next let us see, how to add records to the table. To add records to the table, you can use contentValues and insert statement.
ContentValues v=new ContentValues();
 v.put("name", "Anil");
 v.put("salary", 24000);  
 mydb.insert("nameSal" , null, v);

You store key-value pairs in contentValues and then use insert function which takes table name as first parameter, nullColumnhack as second parameter and contentValue as third parameter.

Next let us consider how to extract data from our table. A query function can be used for this purpose. Query  will return a cursor.
mCursor = mydb.query(nameSal, null, null, null, null,
  null, null);

Here first argument is the table name to query.
Second argument is the column list to return- if null all columns are returnred
Third argument is selection like where clause in select statement excluding where
Fourth argument are the values to be filled for ? in selection 
Fifth argument is group by clause 
sixth argument is having clause which denotes which row groups to be returned
seventh argument is order by column
eighth argument is maximum number of columns to be returned

Let us look at another example using query
Cursor c = mydb.query("nameSal",new String[]{"name","salary"},
"salary > 26000",
null,
null,null,
"salary ASC ",null);
Here the query will return the columns name and salary given by second argument, where salary is greater than 26000 (the condition is given by 3rd argument). The rows returned will be arranged in ascending order of salary(7th argument).

Once we get the cursor, we can iterate through the rows using loop. Look at the example below.
c.moveToFirst();
do{ String name = c.getString(0); int salary = c.getInt(1); Toast.makeText(this, "name is "+name+" salary is "+salary, 2000).show(); }while(c.moveToNext());


c.moveToNext  method will return false when the end is reached.