1

creating Date class in c++

Creating  date class in which  member data may consist of three integers: like day, month, and year.

three member functions:
getdate( ) which allows the user to input  a date,displaydate( )/showdate() function which
displays the date the last changeformat( ) function which change the date in
mm/dd/yyyy format. */


#include<iostream.h>
class Date{
private:
int day,month,year;
public:
Date():day(0),month(0),year(0){}
void getdate(){
cout<<"Enter day:"<<endl;
cin>>day;
cout<<"Enter month:"<<endl;
cin>>month;
cout<<"Enter year:"<<endl;
cin>>year;
}
void showdate(){
cout<<day<<"-"<<month<<"-"<<year<<endl;}
void changeformat(int a, int b, int c){ day=a;
month=b;
year=c;
cout<<month<<"/"<<day<<"/"<<year<<endl;

} };

main()
{
Date b;
b.getdate();
b.showdate();
b.changeformat(12,3,2011); }

Selecting Templates For Your Website -Things To Remember

Things To Remember When Selecting a Template For Your Website
You can easily find numerous website offering predesigned templates or logos. Many websites even offers free templates or logos but it is not always suitable for you. Don’t forget that in most of the cases, you have to spend money to buy a template for your forthcoming website and for this, you have to go for an online transaction which always carries risk. By taking some easy steps, you can not only minimize the financial risk but will also be able to get the best template as to make an extremely attractive website.
Credibility of The Template Seller
Seller’s credibility always plays an important role whenever the process of buying and selling is involved anywhere. Before purchasing the template, you should check if the seller website is credible or not. The easiest method to check the credibility of the seller website is to check the payment methods which he is offering you. Risky payment methods like payments in bank accounts on the names of persons instead of company, manager’s check on personal names, etc.
Reliable Payment Methods
Nowadays, there are several payment methods which are used on the internet and are considered totally safe and secure. The most reliable payment methods include PayPal,2checkout and Escrow (usually used in the sale and purchase of goods having physical existence).
Appropriate Design
At the time of buying the template, you have several thoughts, ideas and concepts in your mind which you want to see in your website but as you are not a person who can practically do it so you go for the templates. The best approach in this is to search the template having the closest match with your thoughts and ideas and then you can personalize its contents, pictures etc to make it the ideal piece of work. What the experts suggests is to sort out 4-5 different templates and then finalize the most suitable.
Template Matching With Your Business Theme
Any type of website either designed by a developer or you have acquired its template must match with the theme of your business or the purpose for which the website is being launched e.g. use of so many bright colors and pictures of new and attractive dresses in the pictures would be an ideal scenario for a website of a clothing store. On the other hand, the same would be useless for a business consultancy firm.

Template magician as best source to buy templates for your website.

Proper Usage of The Template
Proper usage of the template also plays an important role in any website. In order to maintain the interest of the visitor of your website and to induce him to visit it again, the content and the information provided by you about your business must be brief but comprehensive. If your there is a possibility of a physical visit or you think the visitor will require any sort of assistance on phone/fax then the complete address along with the phone and fax numbers must be clearly mentioned.
 If anyone is following the above steps, he can easily make an attractive website in a short span of time and not only bolster his business activities but also promote his business in a low budget.
templates for your website,
3

How to connect Android app to MySQL database

How to connect Android app to MySQL database:

Description: In this article we will learn  how to connect android application to MySql database and apply the few of the queries (CREATE, READ ,UPDATE,DELETE) also called CRUD with proper code and explanation.

Introduction: Many android application on Google play store uses online Database to retrieve data, to be shown to the user. This is done, due to fact that we can’t store large amount of data on our android mobile. Some android application uses sqlite database for some of android application, but the data has to be of limited size.

Many  android application make use online database to have data of their users. Although we can use different web services for our application, depending on the needs of application we are to built.

Suppose if we need to make weather application, we will simply use any web service that provide us the data of the weather , which we can display on our appplication. But sometimes it becomes  mandatory to make your online database.

Lets know break down the tutorial into some steps .

  • How to Make a free database, domain name and hosting at 00webhost.com
  • Php script of CRUD sql queries.
  • Android application user interface.
  • Android application main java file.
  • Android application manifest file.
  • Conclusion

How to make free database, domain name and hosting at  00webhost.com?

First of all we need to make a free account at 00webhost website. Register a free domain .Once you register your free domain, navigate cpanel. Next step is to create a simple database at Phpmyadmin area.

Create a database with any name.

For this tutorial we would like to make an application for displaying list of products. The products will be the different types of mobiles phones .

Database should contain the following fields:

  • ID int (11) primary key auto incremented
  • mobileName varchar(255)
  • mobileModel varchar (255)
  • mobilePrice int(11)

Once the database with above description is created, we are ready for the next step.

NOTE: Note down the name of the database, server, username, and password , we will require this data  make a connection to the database.

Php script for CRUD sql queries.

In your cpanel browse to filemanger , then to public-html and create an new file with name of “queries.php”.

You will need to write the php script that should respond to event that we trigger on our android application.

Note : Your specification to make connection to the database.

$hostname = “mysql8.000webhost.com”;
$username =”a522438_elift”;
$password =”Hamdard12″;
$db = “a522438_elift”;

Now lets first make a connection to the database and display that on our android device.

Listing#1 Product.php


<?php

$hostname = "mysql8.000webhost.com";

$username ="a5224389_elift";

$password ="Hamdard12";

$db = "a5224389_elift";

$conn = new mysqli($hostname,$username,$password,$db);

if($conn->connect_error){

$response[‘success’] =0;

$response[‘message’] =”could not connect to the database”;

print(json_encode($response));

die(print(json_encode($response)));

}

$response[success] =1;

$response[message] =”successfully connected to the database”;

print(json_encode($response));

?>

Explanation code:

In the first step we make a simple connection to the database. To notify the user we send the $response value to android applcation, that is for value 1 , we  will display the database is connected successfully , where as for the value 0 we will display the text saying that database could not be connected .

Now lets look at the java code and xml representation, we have used to get all this functionality .

Listing#2 MainActivity.java


package com.conndb;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.io.UnsupportedEncodingException;

import java.util.ArrayList;

import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";

TextView tv;

String textview = null;
static JSONObject jObj ;
static String json = "";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.textView1);
Button b2 = (Button) findViewById(R.id.button2);
b2.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i2 = new Intent(MainActivity.this,menuList.class);
startActivity(i2);
}

});

Button connectdb = (Button) findViewById(R.id.button1);
connectdb.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
new Connectingdb().execute();
}

});

}

class Connectingdb extends AsyncTask<String, String, JSONObject> {
/*Before starting background thread Show Progress Dialog

* */

boolean failure = false;
private ProgressDialog pDialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Attempting connect...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}

@Override
protected JSONObject doInBackground(String... args) {
InputStream is = null;
// Making HTTP request
try {
// check for request method
{
// request method is POST
// defaultHttpClient

DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost=new HttpPost("http://ieeehiit.host22.com/product.php");
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();}

}

catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
json = sb.toString();
jObj = new JSONObject(json);
is.close();
return jObj;
}
catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
return null;
}
}

/**

* After completing background task Dismiss the progress  dialog

* **/

protected void onPostExecute(JSONObject json) {
int success = 0;
try {
success = json.getInt(TAG_SUCCESS);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

if (success == 1)

try {

display(json.getString(TAG_MESSAGE));

} catch (JSONException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

pDialog.dismiss();

}

}

public void display(String m){

tv.setText(m);

}

}

Explaination to code:

Before we jump into explaining the code, lets first have some basic concepts of how do we perform long running operation in android .

Each application in android runs on its main thread. Main activity containing, most of the user interface widgets needs runs on the main thread.In case we want to perform operations that require few seconds(such as connectivity to online server, login in and other similar works ) will freeze the main activity thus user would not be able to interact with application.

To get rid of this problem android has a special class called AsynTask, that is special built form these kind of operation. As you can see in the code above we have used the AsyncTask.

AsynTask has one method that must be overridden that is

@Override

protected< String doInBackground(String… args) {}

Which take arguments that is multiple arguments, which are stored as an array of type String(you are not restricted to only strings).The above signature is used when you need to use same type of data types for your AsyncTask.

AsyncTask<String, String, String>

Note that while we are doInBackground() method, we cannot, touch the views. Inother words you cannot, assign values to textviews etc.

So how to notify the user , that something is happening in the background we make use of two methods

protected void onPreExecute()

It will be executed before the doInBackground method gets started.

protected void onPostExecute()

It will be executed after the doInBackground method. And it takes the argument, from the doInBackground method that can be stored in any view, such as textview as we have shown in the code.

You may also have noticed that we have also used the progress bar that starts onPreExecutes and gets hidden in the method named onPostExecte.

This is to make the user notified, and ask to wait for few seconds as our background task is going on.

Now let’s get back to code and explain what actually is happening!

To make a request to the user , we can either use , the HTTP request or we  can use the HTTP URL connection.

The above code uses HTTP method, where as most of the application, now a days uses URL connection method, which is continually maintained by the android developing team. The former method has not been maintain for quite some time.

We simple use Request and response objects to make a connection to the server in the above code.


DefaultHttpClient httpClient = new DefaultHttpClient();

HttpPost httpPost = new  HttpPost("http://ieeehiit.host22.com/product.php");

HttpResponse httpResponse = httpClient.execute(httpPost);

HttpEntity httpEntity = httpResponse.getEntity();

is = httpEntity.getContent();

httpPost object behaves as a request with a http methode of type post, URL as an argument.

Response is then stored in InputStrem object “is” using httpEnity.getContent().

We simply then read line by line, the input stream, and deal with it, they way we want to deal, with it.

In our case we simply have either 1 or 0 as a response from the server, and once we know the response value we notify the user on the basis of that value.

In this version of our application we simply have a button view and text view. When clicked on button, we are shown with result weather connected or not! Besides this we have used RelativeLayout for our xml representation, which positions  the items in a respective manner

Listing#3 activity_main.xml


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:paddingBottom="@dimen/activity_vertical_margin"

android:paddingLeft="@dimen/activity_horizontal_margin"

android:paddingRight="@dimen/activity_horizontal_margin"

android:paddingTop="@dimen/activity_vertical_margin"

tools:context=".MainActivity" >

 

<Button

android:id="@+id/button1"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_alignParentLeft="true"

android:layout_alignParentTop="true"

android:layout_marginLeft="64dp"

android:layout_marginTop="100dp"

android:text="check conection" />

 

<TextView

android:id = "@+id/textView1"

android:layout_width = "match_parent"

android:layout_height = "wrap_content"

android:layout_alignParentTop = "true"

android:layout_centerHorizontal = "true"

android:layout_marginTop ="53dp"

android:text="TextView" />

</RelativeLayout>

OUTPUT:

android tutorial to connect to database online

Fig : 1 Displaying the output for database connection .

Now we will modify both our php Script and UI interface so that we apply the read sql query to fetch data from the database and display it on the android application.

 

Implementing Read query on Mysql database using android:

Lets first look at the modification that  we have to make in order to implement read query.

 

Listing #4 Php Script Version2:


<?php

$hostname = "mysql8.000webhost.com";

$username ="a5224389_elift";

$password ="Hamdard123";

$db = "a5224389_elift";

$conn = new mysqli($hostname,$username,$password,$db);

if($conn->connect_error){

$response ="could not connect to the database";

die(print(json_encode($response)));}

$q ="Select * from product";

$result = $conn->query($q);

while($row = $result->fetch_assoc()){

$output= $row;

}

print(json_encode($output));

$conn->close();

 

?>

Explanation to the code:

The data displayed on the screen of android application is fetched as json(which is a data format same like XML but is light weight ). Json data can of two types , Json Objects and json Arrays .

To display the json on android screen you will first need to parse the data, for which you will need to first analyse whether your data is coming as json objects or json Arrays .

[ ] brackets are signs of json objects where as {} brackets are the signs of objects.

 

Coming back to the code of Php script, we have simply used the select query, and then printed the data as json.

 

$q =”Select * from product”;

$result = $conn->query($q);

while($row = $result->fetch_assoc()){

$output= $row;}

print(json_encode($output));

 

 

 

Now lets look at the changes that we have made in our mainActivity.java file in order to display this data.

Listing #5 mainActivity java version 2


public class MainActivity extends Activity {
TextView tv;
String textview = null;
static JSONObject jObj ;
static String json = "";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.textView1);
Button b2 = (Button) findViewById(R.id.button1);

b2.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {

// TODO Auto-generated method stub

Intent i2 = new Intent(MainActivity.this,menuList.class);
startActivity(i2);

}

});
Button connectdb = (Button) findViewById(R.id.button1);
connectdb.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
new Connectingdb().execute();
}

});
}

class Connectingdb extends AsyncTask<String, String, JSONObject> {
/**

* Before starting background thread Show Progress Dialog

* */

boolean failure = false;
private ProgressDialog pDialog;

@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Attempting connect...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();

}
@Override
protected JSONObject doInBackground(String... args) {
InputStream is = null;

// Making HTTP request

try {
// check for request method

{

// request method is POST

// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://ieeehiit.host22.com/product.php");
HttpResponse httpResponse =             httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();

}
} catch (UnsupportedEncodingException e) {

e.printStackTrace();

} catch (ClientProtocolException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

try {

BufferedReader reader = new BufferedReader(new InputStreamReader(

is, "iso-8859-1"), 8);

StringBuilder sb = new StringBuilder();

String line = null;

while ((line = reader.readLine()) != null) {

sb.append(line + "\n");

}

json = sb.toString();
jObj = new JSONObject(json);
is.close();
return jObj;
} catch (Exception e) {

Log.e("Buffer Error", "Error converting result " + e.toString());
return null;

}
}

/**

* After completing background task Dismiss the progress dialog

* **/

protected void onPostExecute(JSONObject json) {

try {
int mobid = json.getInt("ID");
String mobilename = json.getString("mobileName");
String mobileModel = json.getString("mobileModel");
int mobilePrice = json.getInt("mobileprice");

display("mobile Id= "+mobid+"\nmobileName = "+mobilename +"\n mobile model = "+mobileModel +"\n mobile price = "+mobilePrice+"\n>>>>>>>>>>>>>>>\n");

} catch (JSONException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}
pDialog.dismiss();
}
}
public void display(String m){
tv.setText(m);
}
}

Explanation to the code:

Most the code above is similar to our previous code, whe just made some changes.
To get the exact data , we are looking for

static JSONObject jObj ;
is being used.

Remeber that, since we have used , our own php script, the data is in json, objects we are only showing one recode right now on our android application. This is just to make you familiar with usage. Most often while dealing with web-services you will be having your data as jsonArray , That is more efficient , you can play around with data as you want. I could have use some libraries to show all of the recodes on screen.


int mobid = json.getInt("ID");
String mobilename = json.getString("mobileName");
String mobileModel = json.getString("mobileModel");
int mobilePrice = json.getInt("mobileprice");
display("mobile Id= "+mobid+"\nmobileName = "+mobilename +"\n mobile model = "+mobileModel +"\n mobile price = "+mobilePrice+"\n&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;\n");


After Passing the JSONObject from the doInBackground method, the data is stored in relative string, using get methods of the jsonclass.which is then passed to display method to be appended to the textView.

We do have made some of the changes in the XML file also.
<h2>Listing #6 activity_main.xml</h2>


&lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" &gt;

&lt;ScrollView
android:id="@+id/scrollView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="37dp" &gt;

&lt;LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" &gt;

&lt;/LinearLayout&gt;

&lt;/ScrollView&gt;

&lt;TextView

android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignLeft="@+id/button1"
android:layout_alignRight="@+id/button2"
android:layout_below="@+id/button1"
android:layout_marginTop="24dp"
android:text="TextView" /&gt;

&lt;Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="Read cammad" /&gt;

&lt;Button

android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/button1"
android:layout_alignBottom="@+id/button1"
android:layout_toRightOf="@+id/button1"
android:text="Next activity " /&gt;

&lt;/RelativeLayout&gt;

OUTPUT:

android tutorial  how to connect to databse

Figure #2 Displaying data fetched from the database .

Conclusion:

We dicussed how to connect with database, and get notified on our andorid application.
AysnTask class was discussed in detail.
We have also used Select query to fetch data from the mysql data base. We learned how to display data using json objects.
Hope you have got some of the idea , on how to deal with data bases , using php, mysql and android. Besides this I would recommend you to have a look, different  web-services . There are various web service which can be used to make android application, to bring ease to the human life. All of the web service almost have the same concept, as we have discussed, in fact it would be more easy for you to deal with that. You only need to follow their documentation, for applying different queries, fetching data etc.

All of the web services now a days provide their data as json, and xml which you can easily use for your android application.

2

Create free app with app creator

Create free app with app creator:

createmyfreeapp: In today’s world of information technology , humans have brought almost every thing into a tiny small but smart device. Android , IOS being the most popular OS running on these devices. Today every organization , business need their own custom application, so that data is kept to the finger tips of managers.This helps to analyse data.Building application can cost you very money. But today i will be bringing you one of the web application called CreatYourFreeApp  which will let you make different sort of applications for different categories.

create free app

 

These includes

  • Business applications,
  • Entertainment applications
  • Event applications
  • Education and much more.

Create free app with our app maker through through easy steps , Login , Desing, and Publish. Your application will be placed on google paly store thus letting you download, distribute your application with all your employees and the people you need to use your application.

Secondly the you can design you application according your wishes, you can add headers, splash screens and other important data to your application such as about us, social channels they way you wish. you donot need any sort of coding your free app creator will make you an amazing application with in few minutes .

Beside free version, we have different sort of premium features for your application that you can buy and enhance your capabilities of application that you have created through free app maker application , with your designed instruction.

I highly recommend you if you have any of business organization, these free app creator will surly help you boost-up your business and take your business to next level of which you have every time dreamed of.

So now create your application without codding , with costing any sort of money providing you only designed app according your own design. you can get you application both for android and IOS.

Android drop down List:Example

Android drop down List:In this tutorial we will make Android drop down List without using xml. Basically all the work is done using the java programming. We can make Android drop down List simply by using xml, But you can also create using a Java implementation to have full control .

So first of you will need to create a new application with any name you like , and then you simply need have a look at the coding below .

Android drop down List:Example


class menuList extends ListActivity {

//remember to extend your class extends ListActivity

String listvalues[] ={ "item1", "item2","item3"};

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setListAdapter(new ArrayAdapter(menuList.this, android.R.layout.simple_dropdown_item_1line, listvalues));

// we use a methode setListAdapter() methode that takes an arrayAdapter that //takes context and , dropdwonlist constant , and listvalues

}

@Override

protected void onListItemClick(ListView l, View v, int position, long id) {

super.onListItemClick(l, v, position, id);

// you can perform opertion on each item clicked here!

}

}

OutPutAndroid drop down List

 

 

When to Drop down list:

It can be used to list down different item, or activities of  your android application.Besides this you can use drop down list while parsing the data and displaying images with some description on a list.Basically it can be used at so many places depending on your application fuctionality .

Once you learn this you can simply use the same features at different application, most of the application now adays contains drop down list menus , and the cool thing is android.R.Layout provides you different styles of menu which you can use according to your needs.

 

Conclusion:

In this short tutorial you just learned how to create  a simple drop down list menu, soon we will be updated the second portion we we can perform different action when each of the item is clicked.

 

1

ArrayList example in java

What is ArrayList in java?

ArrayList is a class of java collection framework (a collection framework gives the architecture for manipulation and storage of group of object).Arraylist is basically a dynamic array. We  are not required to define it size, it can increase its size dynamically. It has the capability of direct access, i.e is with index we can access its elements, same as we deal with arrays. Arraylist are not efficient for add/removing elements as much of shifting is required. you may look for other type of data structure if you data is frequently changing, LinkedList may be helpfull in that case.

Arraylist example in java

ArrayList example in java

Lets have a look , on how to create and add items to the Arraylist data structure.

How to iterate the elements of collection in java?

we can iterate either using the Iterator inter face or by simply using for loop.

 


package arraylistapplication;

import java.util.ArrayList;
import java.util.Iterator;

public class CollectionAL {

public static void main(String [] args){

ArrayList<String> al = new ArrayList<>();
al.add("orange");
al.add("apple");
al.add("bannana");

Iterator it = al.iterator();
while(it.hasNext()){

System.out.println(it.next());

}
} }

 

Not only can ArrayList contain only primitive data types, or objects , it can also contain user defined objects . Now lets create our own class and then add that to the array list and display each object on the screen. This is the most useful usage of the array list that you will be using in more advance programming.

Creating student class


package arraylistapplication;

public class Students {

int stdId;
String name;

Students(int id, String stdName) {
this.stdId = id;
this.name = stdName;

}
}

Creating Array list for the students class.


package arraylistapplication;

import java.util.ArrayList;
import java.util.Iterator;

public class ArraylistStd {

public static void main(String[] args) {

Students std1 = new Students(001, "Khan");
Students std2 = new Students(002, "dada");

ArrayList<Students> al = new ArrayList<>();
al.add(std1);
al.add(std2);

Iterator it = al.iterator();

while(it.hasNext()){

Students stds = (Students)it.next();
System.out.println("Student Id :"+stds.stdId+" Student Name : "+stds.name);

}

}

}

 

2

How to Make String Palindrome in PHP

How to Make String Palindrome: A string is said to be Palindrome, if its reverse string is the same as it is!.

Let suppose we have a string = “TAT ” now if we reverse it !

it will still be TAT. so we simply say that the string is palindrome.Lets look at the simple example to understand all this.


<?php

$str = "tat";
$reverse_str= strrev($str);
if( $reverse_str == $str){

echo"the string ".$str."is Palindrome";
}
else
{
echo"the string ".$str."is not Palindrome";
}
?>

 

Now lets try the same Palindrome without using strrev() function.

Palindrome without using strrev() function in php

<?php

$str = “level”;
$str_array = str_split($str);
$str_reverse =””;
$size = count($str_array);
echo”the size of string is “.$size;

for($i=$size-1; $i>=0;$i–){

$str_reverse.=$str_array[$i];

}
if($str_reverse == $str){

echo “this is Palindrome”;}

else{
echo “this is not Palindrome”;
}

?>

Please do post your comments .

 

2

interview questions in c ++

Interview questions in C ++

1) Is C++ is case sensitive?

YES, C++ is case sensitive. You cannot write MAIN instead of main.


2) Write simple C++ program.


#include<iostream.h>

using namespace std;

//main() is portion where program executions begins.

main()

{

cout<<"RAFI ULLAH AFRIDI"<<endl;

// cout is used to print something on screen

}


3)


4) What is compiler?

Compiler is a translator which translate our high level language in to low level language (also called machine language) and low level language to high level language.

Because machine don’t understand our high level language such as

int a;

cin>>a;

cout<<a<<endl;

compiler will convert this into machine language like

0010010101011100

something like that. And then process it and result is converted again into high level language.


5) What are comments in C++ program and why it is used?

Comments are that lines in C++ program which we don’t want to compile but we want to write it down in C++ program. Those lines which are commented in C++ program will be simply ignored by compiler.

And it is used for users to understand each and every step in C++ program code.


6) how many types of comments are there?

There are two types

Single line comment:- “//” symbol is used if we want to comment a single line.

Multiple line comments:- if we want to comment whole paragraph. It is recommended to use this.

/* Program comments are explanatory statements that you can include in the C++ code that you write and helps anyone reading it’s source code. All programming languages allow for some form of comments.  */

Lines or statement between /* and */ will be simply ignored by compiler.


7) what is function of endl?

endl is used for new line. “\n” is also used for new line.


8) What is variable?

variable is named part of memory where we store our data.

int a;

above statement means the part of memory named “a” where we can store integer value.


8) What kind of name we should use for variables?

Every words can be used for variable name except keywords.

the variable name should start with lower case alphabet. Like

int value;                            // valid name

int age of boy;                   // invalid name

int gpa_of_student;        // valid name


9) what are keywords?

Keywords are specail words used by C++ language. We cannot use it for naming purposes.

for example

int float;              // invalid name because its keyword.

int include;        // invalid name because its keyword.


10) What are keywords used in C++?

Following keywords(also called reserve words) are use in C++.

int, float, main, iostream, iomanip, include, bool, double, long, unsigned etc.


11) Types of data

Following are some of the datatypes

int:- used for integer values

char:- used for character values

float:-  a single precision floating point value

double:- double precision floating point value

void:-  this represents the absence of datatype

bool:-  used for true and false values only


12) What are kinds of variables?

There are two types

Local variable:-  variable defined by some specific function. And only accessible in that function.

Global variables:- variables defined above main function and accessible by whole program.


#include<iostream.h>

using namespace std;

int age;      // global variable

main()

{

int age;      // local variable

cout<<"RAFI ULLAH AFRIDI"<<endl;

}


13) What is main difference between local and global variables?

  • Local variables are not initialized automatically by system.
  • Default values are garbage values.
  • Visible only in function which defined it.

=====+=======+=======+=======+=======+=======+========+=========+========+

  • Global variables initialized automatically by system.
  • Defaults values for int, float, double is O and for pointer is NULL and for char is ‘\o’.
  • visible in whole program.

14) In how many ways we can define constant in C++?

There are two ways to define constant in C++

(1) #define PI 3         // this means that PI has value 3

(2) const int PI = 3;   // this means that PI has value 3


15) What operators are used in C++?

Arithmetic Operators (+, -, *, /, %)

Relational Operators (==, <=, >=, <, >!=)

Logical Operators (!, &&, ||)

Bitwise Operators (|, &, ^)

Assignment Operators (=, +=, -=, *=, /=)

Misc Operators (?:, *, sizeof)


16) What is meant by infinite for loop?

infinite for loop means the loop that will run forever. i-e not ending


#include<iostream.h>

using namespace std;

main()

{

for(; ; 😉

{

cout<<"This is infinite loop, it will never stop"<<endl;

}

}


 

 

JAVA INTERVIEW QUESTIONS

JAVA INTERVIEW QUESTIONS

1) What is OOP?

OOP stands for object oriented programming. It is programming paradigm in which programming is performed through objects.


2) What is platform?

Any software or hardware in which program run or executed is called platform.


3) What is JRE?

Java Runtime Environment (JRE) is the platform for JAVA.


4) What are features of JAVA?

Java is Object Oriented Programming, Simple, Secure, Platform independent, Multithreaded, Portable, Robust etc.


****************Very important java interview questions****************


5) How JAVA is secure?

Java has no explicit pointers like most of the Object Oriented programming languages. This feature make it secure.


6) How JAVA is Multithreaded?

Java supports Multi threads programming.


7) How JAVA is platform independent?

Java program can be run on many platforms such as windows , Linux, sun Solaris, MAC OS etc. This is because of bytecode. Every Java program converted in to bytecode and This bytecode can execute on multiple platforms.


8) What is bytecode?

Java program is converted by compiler into bytecode. This bytecode is platform independent which can run on multiple plarforms.


9) What is JVM?

JVM stands for Java Virtual Machine. It is JVM who runs / executes bytecode.


10) What are basic functions of JVM?

  • Loads code
  • Verifies code
  • Executes code
  • Provides runtime environment

11) What is JDK?

JDK stands for Java Development Kit.  It is JRE and development tools used for Java.


****************Very important java interview questions****************


12) What are the basic concepts of OOP?

The basic concept of OOP are

  1. Classes
  2. Objects
  3. Encapsulation
  4. Inheritance
  5. Polymorphism
  6. Abstraction

JAVA INTERVIEW QUESTIONS

13) How Java program is executed form Command Line?

Two steps are required to do this.

  • Compile program: javac Program_name.java
  • Execute program: java Program_name

****************Very important java interview questions****************


14) What is mean by visibility of class or method or variable?

Visibility means who can access that class , method or variable. Visibility is achieved by access modifier in Java. There are three types of access modifiers.

  • private
  • public
  • protected

15) What are Valid main method signatures.

  • public static void main(String[] args)
  • public static void main(String []args)
  • public static void main(String args[])
  • public static void main(String… args)
  • static public void main(String[] args)
  • public static final void main(String[] args)
  • final public static void main(String[] args)
  • final strictfp public static void main(String[] args)

16) What is compile time?

When Java program  is compiled into Bytecode by compiler. Prgram.class file created.


17) What is run time?

When Bytecode executes.


18) Can you save Java program by different file name?

Yes you can. But this you should compiler program by file name. But execute by Java class name.

  • javac file_name.java
  • java class_name

19) What is JIT?

JIT stands for just in time compiler. JIT compiles that parts bytecode which have similar functionalities. It reduces compilation time.


20) What is variable?

Variable is name of reserved area in memory.


21) What are types of variables in Java?

  • Instance variable :- also called class variable. Variable inside class.
  • Local variable :- variable inside method.
  • Static variable :- variable declared as a static. this make it history sensitive.

22) What are Datatypes in JAVA?

There are two types

  • Primitive datatypes: – int, char, double etc.
  • Non-primitive datatypes: – Array, objects, String etc.

23) What is object?

Any entity having state and behavior is object. For example human, pen, book etc. It may be physical or may be logical. Pen is having state and its behavior is writing.


24) What is class?

Class is collection of data and methods or collection of objects.


25) What is inheritance?

When object acquire properties and behavior of other objects, it is called inheritance. It provides code re-usability facility.


26) What is Polymorphism?

When single task performed by different ways. In java method overloading and overriding gives us polymorphism facility.


****************Very important java interview questions****************


27) What is Abstraction?

Abstraction is technique in which we hide the internal details of something and only showing the functionality.

In java abstract class and methods are used to achieve Abstraction.


****************Very important java interview questions****************


28) What is Encapsulation?

Encapsulation is the wrapping of data and code together. It is also called data hiding.


29) What is a Java naming convention?

It is the suggestions provided by Java for naming classes, interface, method or variables.

  • Class and Interface name should start with upper case letter i-e Button.
  • Method name should be camel case notation i-e yourMthod().
  • Variable name should consist of small letter i-e cgpa, current etc.
  • Constant name should be all upper case letters i-e PI, AGE etc.

30) What is new keyword in Java?

New keyword is used to allocate memory at runtime.


****************Very important java interview questions****************


31) What are the characteristics of Objects?

Objects have three characteristics.

  • State
  • Behavior
  • Identity

32) How object is created?

Class_name object_name = new Class_name();


****************Very important java interview questions****************


33) What is nameless or anonymous object in java?

new Class_name();    // this object has no name(identity).


34) In how many ways objects in java can be created?

In JAVA objects can be created by four methods.

  • By “new” keyword
  • By clone method
  • By factory method
  • By newInstance method

35) In how many ways a method in java can be overloaded?

There are two ways to overload method in JAVA.

  • By changing number of arguments
  • By changing datatype

36) Why method overloading is used in JAVA?

It increase readability of code.


37) What is constructor?

Constructor is methods having no explicit return type, name same as class name and automatically called whenever object is created.


38) What is default constructor?

A no argument constructor is called default constructor.


****************Very important java interview questions****************


39) Why default constructor is used?

Default constructor is used to initialized default values for objects. For example 0 and null etc.


40) Why static keyword is used in JAVA.

Static keyword in java is used for memory management.


****************Very important java interview questions****************


41) Where static keyword can be used in java?

Static keyword can be used with following

  • Variables :- static variable is shared between all objects of the class. Static fields get memory only once
  • Nested class
  • Methods :- can be called using class name. Creating objects for static method is not important. Static method is used to change values of static data
  • Block :- it executed before main method and used to initialized static data

42) Why main method in JAVA is static?

Because main method execute automatically without creating any instance or object for it to call. If it were not static JVM must used some instance to call main method.


 

43) What is usage of “this” keyword in JAVA?

There are several usage of “this” keyword in JAVA.

“this” keyword is a reference variable used to refers current objects.

“this” is used to call current class method and constructor.

For example:  this.methodName();

“this” can be used as argument as well as return type in methods.

For example:   this methodName(this);

“this” can be used to access current class instance variable.

For example:   this.variable_name = 90;


44) What is use of “extend” keyword in JAVA?

“extend” keyword is used for inheritance in JAVA.

class child_class extend parent_class {    //coding here }

inheritance in JAVA is “is a relation”. Means used when something is a type of some other thing.

For example teacher is an employee

It will code in JAVA like this.

class Teacher extends Employee  { }


45) Why multiple inheritance is not supported in classes?

To remove ambiguity problem or diamond problem, multiple inheritance is not supported in case of classes, But multiple inheritance is allowed in interfaces (will discuss later).

Class C is inherits from class A and B and both of its parent class having method by the name show(). So when we called show method through object of class C. What show() will be called by object. Whether A method or B method. So there is ambiguity. It has been removed in JAVA.

JAVA INTERVIEW QUESTIONS46) How we can call method with nameless/anonymous object?

new class_name().methodName();


47) What is aggregation in JAVA?

In JAVA when a class contains the object of some other class as member of class. Such property is called aggregation. Aggregation is “has a relation”.


48) When something is part of another thing, we have to use aggregation.

class Processor

{

}

class Computer

{

int no;

Processor  pro;

}


49) When we have to used inheritance and when aggregation?

If relation is only maintained throughout the life time of object use inheritance, otherwise aggregation is best choice to use.


50) Can we override static methods and why?

No, it is not possible to override static methods in JAVA, because static method is bound with class not with objects.


51) Can main method be overridden?

No, because main method is static. And static cannot be overridden.


******************JAVA INTERVIEW QUESTIONS*******************


52) What is scope of Java access modifiers?

Access Modifier Within class By child class Within package Outside package
Private Yes No No No
Protected Yes Yes Yes No
Public Yes Yes Yes Yes
1

Template in C ++ examples

Template in C++

templates are the basis of generic programming. Which means write code independent of data types.

Template in C ++ is actually a formula or blueprint or map for creating generic programs.

Template in C ++ can be used with functions as well as classes.

 Function template in C ++

A generic function which is coded and independent of specific datatype is called template function.

Real world example

Template in C ++ is like a structure or map of a single room in building and then all rooms can be constructed using same structure or map. Analogous to that example a function template in  C++ can be used for each of that datatype in C++.

c template

We must write separate functions for processing different datatypes.

Example


#include<iostream.h>

void sum(int a, int b)

{

cout<<"Sum is "<<a+b<<endl;

}

main()

{

sum(2,3);

}

Output

template in C

 

Now pass two float values as argument to function. See result

template in C

Now pass two float values as argument to function. See result

template in C

The above all results are not actually we expecting. So we must write separate functions for these. But template in C ++ allow us to write function only once and used as generic function for all the data types.

Syntax of function template


template <class T>

T function_name(T varible1, T variable2,...)

T in above syntax of template in C ++ is actually datatype which may be anyone of datatypes in C++. T may integer, char or float etc.

Example of function template


#include<iostream.h>

template <class T>

void sum(T a, T b)

{

cout<<"Sum is "<<a+b<<endl;

}

main()

{

sum(2,3);

sum('R','S');

sum(3.4,4.5);

}

Output

template in c

 

Class template in C ++

Same as function template in C ++, class template in C ++ is used in generic programming and class template in C ++ is used as blueprint.

Syntax of class template in C++


template <class T>

class class_name{};

Example of class template in C ++


#include<iostream.h>

template <class T>

class Student

{

private:

T var[10];

public:

void show(T vari[10])

{

for(int i=0; i<10; i++)

{ cout<<vari[i]<<" , "; }

cout<<endl;

}

 

};

main()

{

int i[10]={1,2,3,4,5,6,7,8,9,10};

Student<int> obj;

obj.show(i);

 

char c[10]={'R','A','F','I','U','L','L','A','H','!'};

Student<char> obj1;

obj1.show(c);

 

float f[10]={1.1,2.2,3.3,4.4,5.5,6.6,7.7,8.8,9.9,10.10};

Student<float> obj2;

obj2.show(f);

}

Output

template in C

In above template in C ++ example it has been cleared that we have a class used to process different datatype. But at the time of creating objects of that class objects must be declared that it is of which type. To do that we used the following syntax.


Student<int> obj;


This shows that it is arrays of integers.


Student<char> obj1;


This shows that it is arrays of characters.


Student<float> obj2;


This shows that it is arrays of float.