Amfas Tech | Technology, Blogging & Internet Marketing: Programming

How to Install Xamarin to Microsoft Visual Studio

The announcement of third-party mobile application development platform, Xamarin as open source is buzzing around the .NET developer forums and discussion boards now.

This mobile application development platform can be used integrating with the Visual Studio IDE of Microsoft for free now. There won’t be any trial period to expire or it won’t ask for commercial license to continue in any future. All you would need to have is the latest version of genuine licensed Visual Studio IDE software installed on your computer.

Installation of Xamarin will be executed in three phases. They are,

1. Installation of Java JDK
2. Installation of Android SDK
3. Installation of Xamarin libraries

1. Installation of Java JDK

In this phase the Xamarin installer will download and install the latest version of the Java JDK which is needed for the Android app development.

Java is platform independent and it will be installed with out any intermediator interpreters on Windows.

2. Installation of Android SDK

Installation of Android SDK is the 2nd phase of installing Xamarin to Visual Studio. Android development is all managed by this Android SDK from Google. To develop the android apps with Java, you would need to download and install complete android studio but as we are aiming to develop the android apps using .NET technologies like C# and F#, we only need the core layer, the Android SDK.


This android SDK will integrate into the Visual Studio allowing us to develop right from the VS IDE itself. This is another reason why Android SDK don’t need another IDE (android studio) for developer interface coding.

3. Installation of Xamarin libraries

Xamarin acts as intermediator interpreter for .NET technologies C#/F# and Java. The coding conventions of .NET will be translated into Java native coding using the Xamarin libraries. This is the third and last phase of installing Xamarin to Visual Studio IDE.

Let the Xamarin installer install the libraries needed for the integration with Visual Studio.

After installation, open Visual Studio > File > New Project. You would find the Android and iOS project options to continue. Go to Xamarin University and learn how to program with Xamarin on Visual Studio with .NET technologies.

That’s it! Enjoy Android and iOS app development from Visual Studio.
Continue Reading

Xamarin is Open Source Now; Available Free for Visual Studio

Xamarin, the third party .NET app development platform for Visual Studio announced as open source platform which now will be available for free for Visual Studio. The Microsoft has acquired this company recently to bring the better and flexible development options for the .NET developers.


Xamarin provides the rich mobile development offering that enables developers to build mobile apps using the C# technology to deliver the native mobile app experience on major devices like Android, iOS and Windows Phone. This development add on for Visual Studio had been released as a commercial version by the company before merging into Microsoft. After signing the acquiring contract, Microsoft announced this leading mobile development platform as open source for the commercial license holders of .NET development environment, Visual Studio.


Xamarin has 15,000 customers in 120 countries which includes 500 fortune companies and 1.3 individual developers who have taken advantage of this offering.


Microsoft has longstanding partnership with Xamarin in building the integration with Visual Studio, Microsoft Azure, Office 365 and Enterprise Mobile Suite to provide developers with an end-to-end workflow for native, secure, app cross platforms.



In this regard, Nat Friedman of Xamarin writes in their blog about making Xamarin an open source.


On March 18th, 2016, Microsoft’s acquisition of Xamarin officially closed.


We love C# and we want every developer to be able to take advantage of the power of .NET in every app, on every device. Being part of Microsoft makes it possible for us to do some incredible things, and today we are announcing several big changes to the way we ship our products.  -Nat Friedman


With this announcement, Xamarin will be included in every edition of Visual Studio including free developers edition. With this integrated, an average .NET developer can develop native apps using C# and F# technologies for Android, iOS along with Windows without any app size restrictions.


“So we are announcing today that we have contributed the Mono Project to the .NET Foundation, including some previously-proprietary mobile-specific improvements to the Mono runtime. Mono will also be re-released under the MIT License, to enable an even broader set of uses for everyone. In addition, to help clarify users’ rights to Mono under Microsoft patents, Microsoft has issued a broad patent promise for Mono. Miguel has posted more details to the Mono Project blog.


These changes to Mono remove all barriers to adopting a modern, performant .NET runtime in any software product, embedded device, or game engine, and open the door to easily integrate C# with apps and games on iOS, Android, Mac, and Windows, as well as PlayStation 4, Xbox One, and any emerging platforms developers want to target in the future


But wait, there’s more!


In addition to these important steps, we are announcing today our commitment to open source the Xamarin SDKs for Android, iOS, and Mac under the MIT license in the coming months. This includes native API bindings and the basic command-line tools necessary to develop mobile apps. It also includes our popular cross-platform native UI toolkit, Xamarin.Forms.


With these changes, .NET is now open source and native on every single device, from mobile to desktop to cloud. This is a proud moment for all of us who have invested years into making .NET the best platform, and we know that this change will make it even easier for developers to invest their own time into building great software in C#.

We look forward to building a true open source community around Xamarin, and eagerly await the first pull requests.” Nat Friedman adds in the Xamarin blog post.


The bottom line of this business activity is that the .NET developer can now develop Android and iOS apps on Visual Studio. What are you waiting for? Give your ideas a shape.

Snippet sources:

Continue Reading

Complete Guide on Using Eclipse for Android App Development

victorial 2This article is submitted by victoria Brinsley, a veteran developer who works for one of the leading Android development companies-Appsted. She’s open to provide best advices on android app development. You may contact her if you need any help regarding the same.

Android app development has always been an enticing experience for individuals with a creative bend of mind. If you too are soon going to work on a new Android app development project, it's high time for you to explore the varied components of an app that's specially been designed to run on all Android powered devices. Eclipse can serve as the perfect environment for developing Android applications. Through this blog, I'll be offering you a comprehensive guideline on the steps that are involved in using Eclipse for development of outstanding Android applications.
Step 1:  Initiating a new Android App Development Project
As one of the most powerful, open source IDE(Integrated Development Environment) Eclipse offers you the flexibility of creating applications for mobile, desktops and the web. The easy-to-adapt nature of Eclipse makes it the perfect tool for developing applications that can operate flawlessly on a range of platforms including: Android, Blackberry, Windows and many more.

For creating a new project, just go to Eclipse's main menu and choose File > New > Android Application Project. On this screen, fill out all the fields including package name, application name etc.
Once you're done with the same, click on 'Minimum Required SDK' drop-down and choose a suitable value. The value you choose here will determine the kind of features that you'll be able to program within your Android application.

Step 2: Use the Package Explorer judiciously
If you look towards the left side of Eclipse IDE, you'll notice Package Explorer feature which displays the basic structure of the Android application. While a majority of Package Explorer items are pre-generated for you, there are many others that you'll need to work as you create the Android application. Here, just double-click the src folder and its sub-folders to view the file which contains the code that's used for creating activity's functionality.

Step 3: Configure the emulator
Hoping that by now you'd have gathered a detailed understanding of the Eclipse IDE, you're almost on the threshold of creating your all-new Android application. Setting up the test environment is the next step that would enable you to tell Eclipse how the respective app needs to be executed.
You can either opt for testing the Android app using the emulator that's provided by Eclipse IDE or you may choose an entirely different Android device. If you're opting for the former testing method, then make sure to test the Android application on a variety of real device prior to publishing the same on different mobile app stores. The reason for this being that real devices usually perform differently when compared to an emulator.
Hence, if you ignore testing your Android app on a real device, you'll likely have to face an unpleasant feedback from the app users. Just follow the below mentioned steps for configuring the emulator:
  1. Set up an Android Virtual Device(AVD) which serves as a software replication of multiple Android devices. For this, you may use the AVD Manager by selecting Window > Android Device Manager which will display different Virtual Devices tab. Now, simply click on 'Device Definitions' tab and scroll through the device configurations to check the number of devices your app could run on. Finally, press the Device Definitions tab and hit the 'New' button. A 'Create New Android Virtual Device(AVD)' window will be displayed. Just fill in the fields, followed by clicking on the Device drop-down. 
  2. Check the Wipe User Data box - This needs to be done for wiping out any data that has already been created in a previous app testing session. I would recommend you to leave all the entered data intact as this would prevent you from re-entering the data each time you intend to test a specific aspect of the respective Android application. 
  3. Click 'Launch' to open the Start Android Emulator window - On hitting the 'Launch' button, the Start Android Emulator window will be displayed on your screen and it will start loading the Android Virtual Device(AVD). This loading speed will be determined by the speed of your computer system. Once the AVD has been displayed, you can choose to close the Start Android Emulator and AVD(Android Virtual Device) Manager windows, with the AVD still running in the background.

Wrapping it all up

So, with that its a wrap on this blog which offered you details about the simple-to-follow steps involved in creating customer-driven Android applications using the intuitive Eclipse IDE(Integrated Development Environment). So, try these steps for yourself and see how things go for your Android app development project.
Continue Reading

Converting Temperature from Fahrenheit to Celsius and Kelvin with C# Console Application Programming

In this tutorial, we are going to see how to accept a temperature value in Fahrenheit from the keyboard and convert it into Celsius as well as Kelvin using C# programming.

Before we skip directly into the program, let’s know about the concept of conversion process at first.

Concept: Fahrenheit can be converted into Celsius using the following formula:
(No. of Fahrenheit units-32)*(5/9).

The same way, Fahrenheit units can be converted into Kelvin by using the following formula:
((No. of Fahrenheit units-32)/1.8)+273.15).

We are going to use this formulae in our following program to achieve the result.

using System.Text;

namespace TemperatureConversion
    class Program
        static void Main(string[] args)
            double temp;
            Console.Write("Enter temperature in Fahrenheit: ");
            temp = double.Parse(Console.ReadLine());
            Console.WriteLine("Temperature converted into Celsius: " + ((temp-32)*(5.0/9)));
            Console.WriteLine("Temperature converted into Kelvin: " + (((temp-32)/1.8)+273.15));
            Console.ReadLine(); /*used to make the console stop closing automatically after printing the output*/

Enter temperature in Fahrenheit: 56
Temperature converted into Celsius: 13.33
Temperature converted into Kelvin: 286.48

Points to remember:
  • As we are programming in console application, we see the result on the console only.
  • The reason why we used 5.0/9 in Celsius conversion is that it gives infinity if the values are taken in integer format.
  • The Console.ReadLine() in the last line of execution is used to make the console stop closing immediately after showing the result, else, it has nothing to do with the program logic.
Continue Reading

Drawing shapes using HTML5 <canvas> tag

Flash became insanely popular because of the flexibility it brought to the browser. With Flash the Web was free from decorating DOM elements and became a platform for real drawing and animation. HTML5 brings this same type of flexibility and power directly to the DOM with the HTML5 <canvas> tag. This hack starts us off slow by walking through the creation of basic shapes on a canvas. The <canvas> tag provides you with a blank slate to create your imagery. In order to do this you first need to create a <canvas> tag in the DOM, and then identify the context. The <canvas> tag is created as a DOM element:


<canvas id="myCanvas" width="200" height="200"></canvas>


This basic <canvas> tag will be presented as a 200 × 200-px empty block on the page. To add to it, we need to identify the context:


var myCanvas = document.getElementById('myCanvas')
var myCtx = myCanvas.getContext('2d');


Notice that we identify the '2d' context which may seem to imply that there would also be a '3d' context, but don’t be fooled: “3d” isn’t really addressed by the <canvas> tag; it has only an x- and y-axis. Now that we have the context identified, we have a host of APIs at our fingertips.


Drawing to a <canvas> tag is all about the '2d' context and finding the appropriate coordinates on the grid. Generally, one pixel on the screen correlates to one point in the canvas (this value can vary when you zoom in or out on a small screen such as on a mobile browser, or when your element is resized with CSS). The key point on our grid is (0,0) or the origin, which is the top-left-hand corner of our canvas. Our canvas is 200 × 200, which means it contains 200 points on the x-axis and 200 points on the y-axis. The following figure shows how our canvas would appear with grid lines on the x- and y axes over 10 points.


The 200 × 200 <canvas> tag with grid markers every tenth point on both the x- and y-axes


Drawing Rectangles

We’ll start with one of the simplest shapes: the rectangle. These are easy to draw into the context of our <canvas> tag. The '2d' context gives us access to the API to draw three basic types of rectangles:



Draws a rectangle with a solid color fill


Draws a rectangle that has a border but no fill


Clears a rectangle-shaped transparency that removes any imagery or fills in the defined area


Taking our sample canvas from before, let’s combine these three shapes onto our <canvas> tag:

var myCanvas = document.getElementById('myCanvas')
var myCtx = myCanvas.getContext('2d');
myCtx.strokeRect(10,10, 180, 180);
myCtx.clearRect(50,50, 100, 100);


The preceding code laid on top of our <canvas> tag looks like as follows:


The 200 × 200 canvas demonstrating the different rectangle APIs in the <canvas> tag

Each of the three APIs follows the same pattern. They are passed four parameters: the x and y coordinates, along with the width and height of the rectangle.


Drawing Paths

Rectangles are just the tip of the iceberg when it comes to drawing on a canvas. Most imagery is produced by combining a series of lines. Like all methods in the <canvas> tag, these drawing APIs are available on the '2d' context. Paths require a few steps to start and complete a drawing. To start a drawing (a single path or series of paths), we use this method:




This method takes no arguments; it simply initiates a drawing. Once the path has begun, we need to determine where we are going to start and end the path. To start the path, we will use the moveTo method. This is similar to determining where you would move your pencil on a piece of drawing paper. Think of it as picking up a pencil and putting it down directly on your starting point. From there, we will use the line To method to determine where our line will end. Here is the first line of our grid:




At this point our canvas will still be blank, as we have not yet closed our path. To close the path we use the following method:




Now we have one line on our canvas. To create our grid, we want to draw multiple lines within our path. To accomplish this, we will begin the path, and then create a series of moveTo and lineTo methods. Once we have all our grid lines, we will write them to the canvas with our stroke method. Our code will look something like this:


var myCanvas = document.getElementById('myCanvas')
var myContext = myCanvas.getContext('2d');
var ctx = myContext;
for(i=0; i<201; i++){
for(i=0; i<201; i++){
myContext.lineTo(i, 200);


Paths have a number of different JavaScript APIs that create different line effects. In many cases we may have a few lines that we want to connect and consequently fill the area. To accomplish this we can simply call the following method:




Drawing Arcs

We can get pretty far with straight lines in our drawings, but we can use the canvas to draw arcs as well. Remember, the <canvas> tag will always be a square, but we can draw any shape inside the square. To draw an arc on the canvas, call the following method off the canvas context:


arc(x, y, radius, startAngle, endAngle, anticlockwise);


As illustrated in the preceding code, a number of arguments are passed into the arc method. The first two are the coordinates for the arc’s center, followed by the arc radius. The startAngle and endAngle parameters declare the start and end points of the arc in radians, which are measured from the x-axis. The final optional anti clockwise parameter, when set to true, draws the arc in a counterclockwise direction. The default is false, which would draw the arc in a clockwise direction.


Looking back at the radius argument, we want to make a special note. In CSS, we are comfortable with declaring values in degrees, but in this case the arc radius is measured in radians. It’s quite common to see an inline conversion from radians to degrees using the JavaScript math equation for pi:


myRadians = (Math.PI/180)*degrees


Let’s put this to good use by creating something recognizable on the <canvas> tag. When I think of circles I think of two things: smiley faces and bombs. To keep the violence level down, we’ll work on the smiley face in this article. Using a similar 200 × 200 <canvas> tag let’s center our outer circle directly in the middle of our tag, and then draw our head:




We now have a canvas with a circle on it, as shown in following screenshot:


The <canvas> tag with a circle centered on the element


This isn’t very exciting. So next we will add the mouth. For this we will use the move To method, and then draw a half circle (notice that the radius will be PI instead of PI*2 as it was for the full circle):


smileCtx.arc(100,100,70,0,Math.PI); // Mouth


The last two components are the eyes. Since we want our eyes to be solid fills, we need to make separate strokes for each of them so that we can apply the fill. The first step to accomplish this is to close the current stroke. We will then start a new stroke, move to a new start point, draw a new circle, and call our fill parameter for each eye:


smileCtx.moveTo(60, 65);
smileCtx.arc(60,65,12,0,Math.PI*2); // Left eye


Let’s put all this code together, and see our masterpiece:


var mySmile = document.getElementById('mySmile')
var smileCtx = mySmile.getContext('2d');
smileCtx.arc(100,100,99,0,Math.PI*2); // head
smileCtx.arc(100,100,70,0,Math.PI); // Mouth
smileCtx.moveTo(60, 65);
smileCtx.arc(60,65,12,0,Math.PI*2); // Left eye
smileCtx.arc(140,65,12,0,Math.PI*2); // Right eye


Our canvas now holds all three strokes to form the face, as shown in the following screenshot:


The 200 × 200 <canvas> tag with the smiley face


Advanced Drawing

We’ve plowed right through lines and arcs, but many illustrations call for lines that can’t be accomplished by either of these shapes. The Canvas specification includes two additional tools for creating custom shapes:


quadraticCurveTo(cp1x, cp1y, x, y);
bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y);


Each of these methods has control points and an ending x,y point. The control points determine the curvature of the path. The bezierCurveTo method has a second control point for an uneven curvature. Additional information about the implementation of each method is available in the W3C spec.

Continue Reading

Validating HTML5 forms without using JavaScript

Form validation is a process where you write code for forms and validate them using another piece of custom code. It is to make sure all inputs are filled with content they are supposed to be filled with. Validation is done in two ways: on the server side and the client side. The server side validation code runs on server to check all the fields and if the requirements are not met, the page will be reloaded with errors. The client side validation works the pretty same way. But the only difference is server side validation runs after the form submission where as client side validation runs before the form is submitted. The best kind of validation is when you do both. The client side validation gives the user an immediate response and the server side validation makes sure response wasn’t being hacked.

Generally, JavaScript is preferred technology for form validations on client side. Writing form in HTML and validating forms using JavaScript really sucks. We’ll have to check two piece of codes when any run-time errors are found. Swapping between the codes would kill your patience. HTML5 doesn’t need JavaScript for validations on client side as the new input types are introduced for validations with it.

In HTML5 the <input> tag has the ability to validate the information in the form. If it validates, proceeds to the submission and if it doesn’t, shows errors.

Let’s see the form validation in both conventional(HTML+JavaScript) and new(HTML5) ways.

Validating forms with HTML+JavaScript:

HTML Form:
<!DOCTYPE html>
<form name="myForm">Quantity (between 1 and 5):
<input max="5" min="1" value="11" name="quantity">
<input type="submit" value="Submit Query"></form>
if(document.myForm.quantity.checkValidity() === false){ alert('fail'); } </script>

The above script will check the ‘quantity’ field and validates the input given in it. When the value is greater than 5, the trigger will be fired. This type of validation is a good practice if only some fields are to be validated in a form. Let us suppose we have 30 fields to be validated. Writing 30 validation lines of code isn’t necessary and it is a worst practice of coding.

You can simply write the following script that does validation of all form fields:
if(document.myForm.checkValidity() === false){ alert('fail'); }

‘myForm’ is the name of the form and it is enough to validate the fields.

Validating forms in HTML5:

Validation criteria in HTML5 is quite different and simpler than before. There is no need to use JavaScript for every small validation of the input fields. Some new ‘input’ tag attributes were introduced with HTML5. They take care of input field validations very well.

The required attribute:

The required attribute can be simply added to the input tag at the end. When the form filler misses out the field, a pop up notifies about that mandatory field to be filled.

For e.g.,
<input type="number" name="quantity" min="1" max="5" required/>

The ‘min’ and ‘max’ attributes see if the value entered is with in the range. If the out of range value is entered, it shows validation error.

The pattern attribute:

The pattern attribute is pretty slick, and is for people who write regular expressions. If you write a regular expression to the pattern attribute, your input will validate against the pattern in order to have the return value true.

For e.g.,
<input type="text" name="quantity" pattern="[0-5]{1}" />

Notice that the type was changed to text in order for the pattern to make the input invalid; we need to remove the number type, as that will supersede the validation criteria. If the type and pattern conflict (by requiring results that exclude each other), the validation criteria will never be met, and the form will never validate.

The measurable attributes:

Some input types have comparative criteria such as email, which require a strict input pattern. Other input types have attributes such as min and max that must be satisfied before the input can be considered valid. Let’s look at our first input example again:
<form name="myForm">
Quantity (between 1 and 5): <input type="number" name="quantity" min="1"
max="5" />
<input type="submit" />

In this case the number that is input must meet the min and max criteria in order to be considered valid. For example, the number 11 would not validate but the number 4 would validate. In a similar manner we have the email type:
<form name="myForm">
Enter Your Email: <input type="email" name="myEmail" />
<input type="submit" />

The email type looks for a value that meets traditional email criteria that would match a regular expression such as this:

var emailTest = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;

If the value of the input doesn’t have a username, an at sign (@), and a domain, it’s considered invalid.

That's all for now! till next time! keep visiting
Continue Reading

How better can you do with the new <input> tag in HTML5

HTML5 was introduced with a lot of new features and modifications to its previous version. It is compatible with the different technologies and used in mobile application development effectively.

HTML5 was introduced with new types for <input> tag. These new types allow better input control & eases the code validation without writing regular expressions every time.

Let's peek into the new <input> types along with the quick demo codes that show how better can you do with them.

Input Type: color

The ‘color’ type is used for input fields that should contain color.
For e.g.,
<!DOCTYPE html>
  Select your favourite color: <input type="color" name="favcolor"><br>
  <input type="submit">

Executing the above code would result the following:

Select your favorite color:

Input Type: date

The ‘date’ type allows user to select a date. You can select the date from the scroll down calendar that pops up when clicked on the field.

For e.g.,
<!DOCTYPE html>
Select your Birthday: <input type="date" name="bday">
  <input type="submit">

Executing the above code with date type will result the following:


Input Type: datetime

The ‘datetime’ type allows you to select a date and time along with the time zone.

For e.g.,
<!DOCTYPE html>
When is the party? (date and time): <input type="datetime" name="partytime">
  <input type="submit">

The above code after execution shows as follows:

When is the party? (date and time):

Input Type: datetime-local

This input type allows you to choose date and time but no time zone. If no time zone is to be displayed, it is better to use ‘datetime-local’ type in the input form.

For e.g.,
<!DOCTYPE html>
  Birthday (date and time): <input type="datetime-local" name="bdaytime">
  <input type="submit">

Google Chrome can differentiate the both ‘datetime’ and ‘datetime-local’ types but Firefox and IE 11 cannot render the difference between these two input types.

Executing the above code results:

Birthday (date and time):

Input Type: email

The ‘email’ input type accepts email format of text into the field. The format other than will not pass the validation.

It is easy to validate an email format with this type rather than writing regular expression.

For e.g.,
<!DOCTYPE html>
  E-mail: <input type="email" name="email">
  <input type="submit">
<p><b>Note:</b> type="email" is not supported in Internet Explorer 9 and earlier versions.</p>

This input type is not compatible with the IE.

The above code looks like as follows when executed:

Note: type="email" is not supported in Internet Explorer 9 and earlier versions.

Input Type: month

The ‘month’ type allows users to select month and year from the drop down calendar.

For e.g.,
<!DOCTYPE html>
  When is your birthday? (month and year): <input type="month" name="bdaymonth">
  <input type="submit">

The above give the following result:

When is your birthday? (month and year):

Input Type: number

The ‘number’ input type is used where the fields should contain numbers. The range of numbers between which the user should opt one can be defined by using ‘min’ and ‘max’ attributes.

The following are the attributes that can be used to specify restrictions:
min – To specify a minimum value in the range.
max – To specify a maximum value in the range.
step – To specify the jump interval of numbers.
value – To specify a default value.

For e.g.,
<!DOCTYPE html>
  Work experience (between 1 and 5): <input type="number" name="quantity" min="1" max="5">
  <input type="submit">
<p><b>Note:</b> type="number" is not supported in Internet Explorer 9 and earlier versions.</p>
This type is not compatible with IE 9 or later versions.

When executed, it shows the result as follows:

Work experience (between 1 and 5):
Note: type="number" is not supported in Internet Explorer 9 and earlier versions.

Input Type: range

The ‘range’ input type allows to choose the range of numbers between the specified end points.

The difference between setting a range with ‘number’ type and ‘range’ type is that you are allowed to choose the range with a slider when using ‘range’ type where as you are allowed to choose a number from the dropdown list of range when using ‘number’ type.

For e.g.,
<!DOCTYPE html>
Rate amfastech: 0<input type="range" name="points" min="1" max="10">10
<input type="submit">
<p><b>Note:</b> type="range" is not supported in Internet Explorer 9 and earlier versions.</p>

Result for above code:

Rate amfastech: 010
Note: type="range" is not supported in Internet Explorer 9 and earlier versions.

Input Type: search

The ‘search’ field can be used to create custom search engines for your website.

For e.g.,
<!DOCTYPE html>
<form action="">
  Search amfastech: <input type="search" name="googlesearch"><br>
  <input type="submit">


Search amfastech:

Input Type: tel

The ‘tel’ type accepts telephone number format into its field. This input type is not supported with most of the browsers including Google Chrome. We may expect it working in the future versions of web browsers.

For e.g.,
<!DOCTYPE html>
  Telephone: <input type="tel" name="usrtel"><br>
  <input type="submit">



Input Type: url

The ‘url’ type allows input in URL format.

For e.g.,
<!DOCTYPE html>
  Add your blog's URL here: <input type="url" name="blog"><br>
  <input type="submit">


Add your blog's URL here:

Input Type: week

You can select the number of the week from the dropdown calendar menu by using ‘week’ input type. The week number along with the year is displayed when selected a date.

For e.g.,
<!DOCTYPE html>
  Week number(week number with year): <input type="week" name="year_week">
  <input type="submit">


Week number(week number with year):

Most of the major browser are upgrading to newer versions to avail full benefits of HTML5. Google Chrome, Mozilla Firefox, Safari and Opera are doing better when compared to Internet Explorer. Internet Explorer 11, so claimed better browser than ever, even can’t render HTML5 properly.

Besides all of these, HTML5 is fluid that supports rich content without any further usage of external plugins. That’s the beauty of it! What do you say? Is HTML5 really good? Comment your thoughts and opinions below!
Continue Reading

Send Email to Gmail and Yahoo Accounts Using JavaMail

So far you know sending email with Gmail, Yahoo, Outlook accounts. Have you ever used JavaMail to send emails to your family & friends?

Compile and execute the following code to use JavaMail:

import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
public class GoogleTest {
private static final String SMTP_HOST_NAME = "";
private static final String SMTP_PORT = "465";
private static final String emailMsgTxt = "Test Message Contents";
private static final String emailSubjectTxt = "A test from gmail";
private static final String emailFromAddress = "";
private static final String SSL_FACTORY =
private static final String[] sendTo = {"",""};
private static final String fileAttachment="D:\hai.txt";
public static void main(String args[]) throws Exception {
new GoogleTest().sendSSLMessage(sendTo, emailSubjectTxt,
emailMsgTxt, emailFromAddress);
System.out.println("Sucessfully Sent mail to All Users");
public void sendSSLMessage(String recipients[], String subject,
String message, String from) throws MessagingException {
boolean debug = true;
Properties props = new Properties();
props.put("", SMTP_HOST_NAME);
props.put("mail.smtp.auth", "true");
props.put("mail.debug", "true");
props.put("mail.smtp.port", SMTP_PORT);
props.put("mail.smtp.socketFactory.port", SMTP_PORT);
props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
props.put("mail.smtp.socketFactory.fallback", "false");
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("", "give password of

MimeMessage message1 =
new MimeMessage(session);
new InternetAddress(from));
new InternetAddress(recipients[0]));
new InternetAddress(recipients[1]));
"Hello JavaMail Attachment");
// create the message part
MimeBodyPart messageBodyPart =
new MimeBodyPart();
//fill message
Multipart multipart = new MimeMultipart();
// Part two is attachment
messageBodyPart = new MimeBodyPart();
DataSource source =
new FileDataSource(fileAttachment);
new DataHandler(source));
// Put parts in message
// Send the message
Transport.send( message1 );

How to Execute?

  1. Copy the code above > Paste the code in Notepad > Save it with extention ‘.java’
  2. Download the JavaMail jars from and put them in classpath.
  3. Run the program.
Continue Reading

3 different techniques for redirecting old websites to new URL

Whenever you wanted move your domain to a new one and you don’t want to loose the traffic that is coming for old website, you should opt for redirection. Redirecting old websites to new URL is not that hard to implement. It can also be done in client side by using simple JavaScript in the website code.

Note: Implement either of the following codes inside <head>…</head> section. Don’t forget to remove the comment tags( ‘<!—’ ,‘–>’ ,’//’and ‘/*…*/’) before you save the changes after implementation.

Method 1: Simple redirection

This method has simple code of redirecting to new website’s URL. Copy the code below and paste it in the <head>…</head> section. Replace with your new website’s URL.
<script type="text/javascript"> <!-- window.location=""; //--> </script>

Method 2: Show message before redirection

This method of redirecting features a popup message in old webpage. You can customize the message in the code below before implementing it in your website/blog. To do so, replace you will be redirected to main page in 10 sec with the text of your wish.
<script type="text/javascript"> <!-- function Redirect() { window.location=""; } document.write("You will be redirected to main page in 10 sec."); setTimeout('Redirect()', 10000); //--> </script>

Did you figure out why it takes 10 seconds to your page to redirect to the new URL? The part of the code setTimeout(‘Redirect()’,10000) is responsible for that delay. It actually means that the function Redirect() would be redirected after ten seconds of timeout. You can change this timeout delay also to the time you wanted.

Remember, 1 second here represented as 1000 and so it was specified as 10000 for 10 seconds of timeout. Keep that in mind before setting the timeout.

Method 3: Redirecting based on their browsers

This method of redirection allows the old website to be redirected to particular URL based on the web browser it is opened in. See the code below,
<script type="text/javascript"> <!-- var browsername=navigator.appName; if( browsername == "Netscape" ) { window.location=""; } else if ( browsername =="Microsoft Internet Explorer") { window.location=""; } else { window.location=""; } //--> </script>

You can customize the URL’s based on the compatibility of the browsers it is opened in. The URLs in window.location are supposed to be customizable.

Don’t forget to remove the comment tags before saving the changes after implementation of the codes above.
Continue Reading

A Simple Java Program to find the Real Roots

The following java program finds out the real roots.

import java.util.Scanner;
class solutions
    public static void main(String args[])
        int a,b,c;
        double x,y;
        Scanner s=new Scanner(;
            System.out.println("Enter the values of a,b,c");
        int k=(b*b)-(4*a*c);
            System.out.println("There are no real roots");
            double l=Math.sqrt(k);
            System.out.println("Real roots are"+x+" "+y);


Result for real roots

Continue Reading

Master List of 100 Java interview Questions

Guys I bring you this time the mostly asked interview questions on Java along with the perfect answers. Go a ride through them and do your best in your next interview.

1. What is the difference between procedural and object-oriented programs?- a) In procedural program, programming logic follows certain procedures and the instructions are executed one after another. In OOP program, unit of program is object, which is nothing but combination of data and code. b) In procedural program, data is exposed to the whole program whereas in OOPs program, it is accessible with in the object and which in turn assures the security of the code.


2. What are Encapsulation, Inheritance and Polymorphism?- Encapsulation is the mechanism that binds together code and data it manipulates and keeps both safe from outside interference and misuse. Inheritance is the process by which one object acquires the properties of another object. Polymorphism is the feature that allows one interface to be used for general class actions.


3. What is the difference between Assignment and Initialization?- Assignment can be done as many times as desired whereas initialization can be done only once.

4. What is OOPs?- Object oriented programming organizes a program around its data, i. e. , objects and a set of well defined interfaces to that data. An object-oriented program can be characterized as data controlling access to code.


5. What are Class, Constructor and Primitive data types?- Class is a template for multiple objects with similar features and it is a blue print for objects. It defines a type of object according to the data the object can hold and the operations the object can perform. Constructor is a special kind of method that determines how an object is initialized when created. Primitive data types are 8 types and they are: byte, short, int, long, float, double, boolean, char.


6. What is an Object and how do you allocate memory to it?- Object is an instance of a class and it is a software unit that combines a structured set of data with a set of operations for inspecting and manipulating that data. When an object is created using new operator, memory is allocated to it.


7. What is the difference between constructor and method?- Constructor will be automatically invoked when an object is created whereas method has to be called explicitly.


8. What are methods and how are they defined?- Methods are functions that operate on instances of classes in which they are defined. Objects can communicate with each other using methods and can call methods in other classes. Method definition has four parts. They are name of the method, type of object or primitive type the method returns, a list of parameters and the body of the method. A method’s signature is a combination of the first three parts mentioned above.


9. What is the use of bin and lib in JDK?- Bin contains all tools such as javac, appletviewer, awt tool, etc., whereas lib contains API and all packages.


10. What is casting?- Casting is used to convert the value of one type to another.


11. How many ways can an argument be passed to a subroutine and explain them?- An argument can be passed in two ways. They are passing by value and passing by reference. Passing by value: This method copies the value of an argument into the formal parameter of the subroutine. Passing by reference: In this method, a reference to an argument (not the value of the argument) is passed to the parameter.


12. What is the difference between an argument and a parameter?- While defining method, variables passed in the method are called parameters. While using those methods, values passed to those variables are called arguments.


13. What are different types of access modifiers?- public: Any thing declared as public can be accessed from anywhere. private: Any thing declared as private can’t be seen outside of its class. protected: Any thing declared as protected can be accessed by classes in the same package and subclasses in the other packages. default modifier : Can be accessed only to classes in the same package.


14. What is final, finalize() and finally?- final : final keyword can be used for class, method and variables. A final class cannot be subclassed and it prevents other programmers from subclassing a secure class to invoke insecure methods. A final method can’t be overridden. A final variable can’t change from its initialized value. finalize() : finalize() method is used just before an object is destroyed and can be called just prior to garbage collection. finally : finally, a key word used in exception handling, creates a block of code that will be executed after a try/catch block has completed and before the code following the try/catch block. The finally block will execute whether or not an exception is thrown. For example, if a method opens a file upon exit, then you will not want the code that closes the file to be bypassed by the exception-handling mechanism. This finally keyword is designed to address this contingency.


15. What is UNICODE?- Unicode is used for internal representation of characters and strings and it uses 16 bits to represent each other.


16. What is Garbage Collection and how to call it explicitly?- When an object is no longer referred to by any variable, java automatically reclaims memory used by that object. This is known as garbage collection. System. gc() method may be used to call it explicitly.


17. What is finalize() method?- finalize () method is used just before an object is destroyed and can be called just prior to garbage collection.


18. What are Transient and Volatile Modifiers?- Transient: The transient modifier applies to variables only and it is not stored as part of its object’s Persistent state. Transient variables are not serialized. Volatile: Volatile modifier applies to variables only and it tells the compiler that the variable modified by volatile can be changed unexpectedly by other parts of the program.


19. What is method overloading and method overriding?- Method overloading: When a method in a class having the same method name with different arguments is said to be method overloading. Method overriding : When a method in a class having the same method name with same arguments is said to be method overriding.


20. What is difference between overloading and overriding?- a) In overloading, there is a relationship between methods available in the same class whereas in overriding, there is relationship between a superclass method and subclass method. b) Overloading does not block inheritance from the superclass whereas overriding blocks inheritance from the superclass. c) In overloading, separate methods share the same name whereas in overriding, subclass method replaces the superclass. d) Overloading must have different method signatures whereas overriding must have same signature.


21. What is meant by Inheritance and what are its advantages?- Inheritance is the process of inheriting all the features from a class. The advantages of inheritance are reusability of code and accessibility of variables and methods of the super class by subclasses.


22. What is the difference between this() and super()?- this() can be used to invoke a constructor of the same class whereas super() can be used to invoke a super class constructor.


23. What is the difference between superclass and subclass?- A super class is a class that is inherited whereas sub class is a class that does the inheriting.


24. What modifiers may be used with top-level class?- public, abstract and final can be used for top-level class.


25. What are inner class and anonymous class?- Inner class : classes defined in other classes, including those defined in methods are called inner classes. An inner class can have any accessibility including private. Anonymous class : Anonymous class is a class defined inside a method without a name and is instantiated and declared in the same place and cannot have explicit constructors.


26. What is a package?- A package is a collection of classes and interfaces that provides a high-level layer of access protection and name space management.


27. What is a reflection package?- java. lang. reflect package has the ability to analyze itself in runtime.


28. What is interface and its use?- Interface is similar to a class which may contain method’s signature only but not bodies and it is a formal set of method and constant declarations that must be defined by the class that implements it. Interfaces are useful for: a)Declaring methods that one or more classes are expected to implement b)Capturing similarities between unrelated classes without forcing a class relationship. c)Determining an object’s programming interface without revealing the actual body of the class.


29. What is an abstract class?- An abstract class is a class designed with implementation gaps for subclasses to fill in and is deliberately incomplete.


30. What is the difference between Integer and int?- a) Integer is a class defined in the java. lang package, whereas int is a primitive data type defined in the Java language itself. Java does not automatically convert from one to the other. b) Integer can be used as an argument for a method that requires an object, whereas int can be used for calculations.


31. What is a cloneable interface and how many methods does it contain?- It is not having any method because it is a TAGGED or MARKER interface.


32. What is the difference between abstract class and interface?- a) All the methods declared inside an interface are abstract whereas abstract class must have at least one abstract method and others may be concrete or abstract. b) In abstract class, key word abstract must be used for the methods whereas interface we need not use that keyword for the methods. c) Abstract class must have subclasses whereas interface can’t have subclasses.


33. Can you have an inner class inside a method and what variables can you access?- Yes, we can have an inner class inside a method and final variables can be accessed.


34. What is the difference between String and String Buffer?- a) String objects are constants and immutable whereas StringBuffer objects are not. b) String class supports constant strings whereas StringBuffer class supports growable and modifiable strings.


35. What is the difference between Array and vector?- Array is a set of related data type and static whereas vector is a growable array of objects and dynamic.


36. What is the difference between exception and error?- The exception class defines mild error conditions that your program encounters. Exceptions can occur when trying to open the file, which does not exist, the network connection is disrupted, operands being manipulated are out of prescribed ranges, the class file you are interested in loading is missing. The error class defines serious error conditions that you should not attempt to recover from. In most cases it is advisable to let the program terminate when such an error is encountered.


37. What is the difference between process and thread?- Process is a program in execution whereas thread is a separate path of execution in a program.


38. What is multithreading and what are the methods for inter-thread communication and what is the class in which these methods are defined?- Multithreading is the mechanism in which more than one thread run independent of each other within the process. wait (), notify () and notifyAll() methods can be used for inter-thread communication and these methods are in Object class. wait() : When a thread executes a call to wait() method, it surrenders the object lock and enters into a waiting state. notify() or notifyAll() : To remove a thread from the waiting state, some other thread must make a call to notify() or notifyAll() method on the same object.


39. What is the class and interface in java to create thread and which is the most advantageous method?- Thread class and Runnable interface can be used to create threads and using Runnable interface is the most advantageous method to create threads because we need not extend thread class here.


40. What are the states associated in the thread?- Thread contains ready, running, waiting and dead states.


41. What is synchronization?- Synchronization is the mechanism that ensures that only one thread is accessed the resources at a time.


42. When you will synchronize a piece of your code?- When you expect your code will be accessed by different threads and these threads may change a particular data causing data corruption.


43. What is deadlock?- When two threads are waiting each other and can’t precede the program is said to be deadlock.


44. What is daemon thread and which method is used to create the daemon thread?- Daemon thread is a low priority thread which runs intermittently in the back ground doing the garbage collection operation for the java runtime system. setDaemon method is used to create a daemon thread.


45. Are there any global variables in Java, which can be accessed by other part of your program?- No, it is not the main method in which you define variables. Global variables is not possible because concept of encapsulation is eliminated here.


46. What is an applet?- Applet is a dynamic and interactive program that runs inside a web page displayed by a java capable browser.


47. What is the difference between applications and applets?- a)Application must be run on local machine whereas applet needs no explicit installation on local machine. b)Application must be run explicitly within a java-compatible virtual machine whereas applet loads and runs itself automatically in a java-enabled browser. d)Application starts execution with its main method whereas applet starts execution with its init method. e)Application can run with or without graphical user interface whereas applet must run within a graphical user interface.


48. How does applet recognize the height and width?- Using getParameters() method.


49. When do you use codebase in applet?- When the applet class file is not in the same directory, codebase is used.


50. What is the lifecycle of an applet?- init() method - Can be called when an applet is first loaded start() method - Can be called each time an applet is started. paint() method - Can be called when the applet is minimized or maximized. stop() method - Can be used when the browser moves off the applet’s page. destroy() method - Can be called when the browser is finished with the applet.


51. How do you set security in applets?- using setSecurityManager() method


52. What is an event and what are the models available for event handling?- An event is an event object that describes a state of change in a source. In other words, event occurs when an action is generated, like pressing button, clicking mouse, selecting a list, etc. There are two types of models for handling events and they are: a) event-inheritance model and b) event-delegation model


53. What are the advantages of the model over the event-inheritance model?- The event-delegation model has two advantages over the event-inheritance model. They are: a)It enables event handling by objects other than the ones that generate the events. This allows a clean separation between a component’s design and its use. b)It performs much better in applications where many events are generated. This performance improvement is due to the fact that the event-delegation model does not have to be repeatedly process unhandled events as is the case of the event-inheritance.


54. What is source and listener?- source : A source is an object that generates an event. This occurs when the internal state of that object changes in some way. listener : A listener is an object that is notified when an event occurs. It has two major requirements. First, it must have been registered with one or more sources to receive notifications about specific types of events. Second, it must implement methods to receive and process these notifications.


55. What is adapter class?- An adapter class provides an empty implementation of all methods in an event listener interface. Adapter classes are useful when you want to receive and process only some of the events that are handled by a particular event listener interface. You can define a new class to act listener by extending one of the adapter classes and implementing only those events in which you are interested. For example, the MouseMotionAdapter class has two methods, mouseDragged()and mouseMoved(). The signatures of these empty are exactly as defined in the MouseMotionListener interface. If you are interested in only mouse drag events, then you could simply extend MouseMotionAdapter and implement mouseDragged() .


56. What is meant by controls and what are different types of controls in AWT?- Controls are components that allow a user to interact with your application and the AWT supports the following types of controls: Labels, Push Buttons, Check Boxes, Choice Lists, Lists, Scrollbars, Text Components. These controls are subclasses of Component.


57. What is the difference between choice and list?- A Choice is displayed in a compact form that requires you to pull it down to see the list of available choices and only one item may be selected from a choice. A List may be displayed in such a way that several list items are visible and it supports the selection of one or more list items.

58. What is the difference between scrollbar and scrollpane?- A Scrollbar is a Component, but not a Container whereas Scrollpane is a Conatiner and handles its own events and perform its own scrolling.


59. What is a layout manager and what are different types of layout managers available in java AWT?- A layout manager is an object that is used to organize components in a container. The different layouts are available are FlowLayout, BorderLayout, CardLayout, GridLayout and GridBagLayout.


60. How are the elements of different layouts organized?- FlowLayout: The elements of a FlowLayout are organized in a top to bottom, left to right fashion. BorderLayout: The elements of a BorderLayout are organized at the borders (North, South, East and West) and the center of a container. CardLayout: The elements of a CardLayout are stacked, on top of the other, like a deck of cards. GridLayout: The elements of a GridLayout are of equal size and are laid out using the square of a grid. GridBagLayout: The elements of a GridBagLayout are organized according to a grid. However, the elements are of different size and may occupy more than one row or column of the grid. In addition, the rows and columns may have different sizes.


61. Which containers use a Border layout as their default layout?- Window, Frame and Dialog classes use a BorderLayout as their layout.


62. Which containers use a Flow layout as their default layout?- Panel and Applet classes use the FlowLayout as their default layout.


63. What are wrapper classes?- Wrapper classes are classes that allow primitive types to be accessed as objects.


64. What are Vector, Hashtable, LinkedList and Enumeration?- Vector : The Vector class provides the capability to implement a growable array of objects. Hashtable : The Hashtable class implements a Hashtable data structure. A Hashtable indexes and stores objects in a dictionary using hash codes as the object’s keys. Hash codes are integer values that identify objects. LinkedList: Removing or inserting elements in the middle of an array can be done using LinkedList. A LinkedList stores each object in a separate link whereas an array stores object references in consecutive locations. Enumeration: An object that implements the Enumeration interface generates a series of elements, one at a time. It has two methods, namely hasMoreElements() and nextElement(). HasMoreElemnts() tests if this enumeration has more elements and nextElement method returns successive elements of the series.


65. What is the difference between set and list?- Set stores elements in an unordered way but does not contain duplicate elements, whereas list stores elements in an ordered way but may contain duplicate elements.


66. What is a stream and what are the types of Streams and classes of the Streams?- A Stream is an abstraction that either produces or consumes information. There are two types of Streams and they are: Byte Streams: Provide a convenient means for handling input and output of bytes. Character Streams: Provide a convenient means for handling input & output of characters. Byte Streams classes: Are defined by using two abstract classes, namely InputStream and OutputStream. Character Streams classes: Are defined by using two abstract classes, namely Reader and Writer.


67. What is the difference between Reader/Writer and InputStream/Output Stream?- The Reader/Writer class is character-oriented and the InputStream/OutputStream class is byte-oriented.


68. What is an I/O filter?- An I/O filter is an object that reads from one stream and writes to another, usually altering the data in some way as it is passed from one stream to another.


69. What is serialization and deserialization?- Serialization is the process of writing the state of an object to a byte stream. Deserialization is the process of restoring these objects.


70. What is JDBC?- JDBC is a set of Java API for executing SQL statements. This API consists of a set of classes and interfaces to enable programs to write pure Java Database applications.


71. What are drivers available?- a) JDBC-ODBC Bridge driver b) Native API Partly-Java driver c) JDBC-Net Pure Java driver d) Native-Protocol Pure Java driver


72. What is the difference between JDBC and ODBC?- a) OBDC is for Microsoft and JDBC is for Java applications. b) ODBC can’t be directly used with Java because it uses a C interface. c) ODBC makes use of pointers which have been removed totally from Java. d) ODBC mixes simple and advanced features together and has complex options for simple queries. But JDBC is designed to keep things simple while allowing advanced capabilities when required. e) ODBC requires manual installation of the ODBC driver manager and driver on all client machines. JDBC drivers are written in Java and JDBC code is automatically installable, secure, and portable on all platforms. f) JDBC API is a natural Java interface and is built on ODBC. JDBC retains some of the basic features of ODBC.


73. What are the types of JDBC Driver Models and explain them?- There are two types of JDBC Driver Models and they are: a) Two tier model and b) Three tier model Two tier model: In this model, Java applications interact directly with the database. A JDBC driver is required to communicate with the particular database management system that is being accessed. SQL statements are sent to the database and the results are given to user. This model is referred to as client/server configuration where user is the client and the machine that has the database is called as the server. Three tier model: A middle tier is introduced in this model. The functions of this model are: a) Collection of SQL statements from the client and handing it over to the database, b) Receiving results from database to the client and c) Maintaining control over accessing and updating of the above.


74. What are the steps involved for making a connection with a database or how do you connect to a database?a) Loading the driver : To load the driver, Class. forName() method is used. Class. forName(”sun. jdbc. odbc. JdbcOdbcDriver”); When the driver is loaded, it registers itself with the java. sql. DriverManager class as an available database driver. b) Making a connection with database: To open a connection to a given database, DriverManager. getConnection() method is used. Connection con = DriverManager. getConnection (”jdbc:odbc:somedb”, “user”, “password”); c) Executing SQL statements : To execute a SQL query, java. sql. statements class is used. createStatement() method of Connection to obtain a new Statement object. Statement stmt = con. createStatement(); A query that returns data can be executed using the executeQuery() method of Statement. This method executes the statement and returns a java. sql. ResultSet that encapsulates the retrieved data: ResultSet rs = stmt. executeQuery(”SELECT * FROM some table”); d) Process the results : ResultSet returns one row at a time. Next() method of ResultSet object can be called to move to the next row. The getString() and getObject() methods are used for retrieving column values: while(rs. next()) { String event = rs. getString(”event”); Object count = (Integer) rs. getObject(”count”);


75. What type of driver did you use in project?- JDBC-ODBC Bridge driver (is a driver that uses native(C language) libraries and makes calls to an existing ODBC driver to access a database engine).


76. What are the types of statements in JDBC?- Statement: to be used createStatement() method for executing single SQL statement PreparedStatement — To be used preparedStatement() method for executing same SQL statement over and over. CallableStatement — To be used prepareCall() method for multiple SQL statements over and over.


77. What is stored procedure?- Stored procedure is a group of SQL statements that forms a logical unit and performs a particular task. Stored Procedures are used to encapsulate a set of operations or queries to execute on database. Stored procedures can be compiled and executed with different parameters and results and may have any combination of input/output parameters.


78. How to create and call stored procedures?- To create stored procedures: Create procedure procedurename (specify in, out and in out parameters) BEGIN Any multiple SQL statement; END; To call stored procedures: CallableStatement csmt = con. prepareCall(”{call procedure name(?,?)}”); csmt. registerOutParameter(column no. , data type); csmt. setInt(column no. , column name) csmt. execute();

79. What is servlet?- Servlets are modules that extend request/response-oriented servers, such as java-enabled web servers. For example, a servlet might be responsible for taking data in an HTML order-entry form and applying the business logic used to update a company’s order database.


80.  What is a Java Bean?- A Java Bean is a software component that has been designed to be reusable in a variety of different environments.


81. What is the difference between an applet and a servlet?- a) Servlets are to servers what applets are to browsers. b) Applets must have graphical user interfaces whereas servlets have no graphical user interfaces.


82. What is the difference between doPost and doGet methods?- a) doGet() method is used to get information, while doPost() method is used for posting information. b) doGet() requests can’t send large amount of information and is limited to 240-255 characters. However, doPost()requests passes all of its data, of unlimited length. c) A doGet() request is appended to the request URL in a query string and this allows the exchange is visible to the client, whereas a doPost() request passes directly over the socket connection as part of its HTTP request body and the exchange are invisible to the client.


83. What is the life cycle of a servlet?- Each Servlet has the same life cycle: a) A server loads and initializes the servlet by init () method. b) The servlet handles zero or more client’s requests through service() method. c) The server removes the servlet through destroy() method.


84. Who is loading the init() method of servlet?- Web server


85. What are the different servers available for developing and deploying Servlets?- a) Java Web Server b) JRun g) Apache Server h) Netscape Information Server i) Web Logic


86. How many ways can we track client and what are they?- The servlet API provides two ways to track client state and they are: a) Using Session tracking and b) Using Cookies.


87. What is session tracking and how do you track a user session in servlets?- Session tracking is a mechanism that servlets use to maintain state about a series requests from the same user across some period of time. The methods used for session tracking are: a) User Authentication - occurs when a web server restricts access to some of its resources to only those clients that log in using a recognized username and password. b) Hidden form fields - fields are added to an HTML form that are not displayed in the client’s browser. When the form containing the fields is submitted, the fields are sent back to the server. c) URL rewriting - every URL that the user clicks on is dynamically modified or rewritten to include extra information. The extra information can be in the form of extra path information, added parameters or some custom, server-specific URL change. d) Cookies - a bit of information that is sent by a web server to a browser and which can later be read back from that browser. e) HttpSession- places a limit on the number of sessions that can exist in memory. This limit is set in the session. maxresidents property.


88. What is Server-Side Includes (SSI)?- Server-Side Includes allows embedding servlets within HTML pages using a special servlet tag. In many servlets that support servlets, a page can be processed by the server to include output from servlets at certain points inside the HTML page. This is accomplished using a special internal SSINCLUDE, which processes the servlet tags. SSINCLUDE servlet will be invoked whenever a file with an. shtml extension is requested. So HTML files that include server-side includes must be stored with an . shtml extension.


89. What are cookies and how will you use them?- Cookies are a mechanism that a servlet uses to have a client hold a small amount of state-information associated with the user. a) Create a cookie with the Cookie constructor: public Cookie(String name, String value) b) A servlet can send a cookie to the client by passing a Cookie object to the addCookie() method of HttpServletResponse: public void HttpServletResponse. addCookie(Cookie cookie) c) A servlet retrieves cookies by calling the getCookies() method of HttpServletRequest: public Cookie[ ] HttpServletRequest. getCookie().


90. Is it possible to communicate from an applet to servlet and how many ways and how?- Yes, there are three ways to communicate from an applet to servlet and they are: a) HTTP Communication(Text-based and object-based) b) Socket Communication c) RMI Communication


91. What is connection pooling?- With servlets, opening a database connection is a major bottleneck because we are creating and tearing down a new connection for every page request and the time taken to create connection will be more. Creating a connection pool is an ideal approach for a complicated servlet. With a connection pool, we can duplicate only the resources we need to duplicate rather than the entire servlet. A connection pool can also intelligently manage the size of the pool and make sure each connection remains valid. A number of connection pool packages are currently available. Some like DbConnectionBroker are freely available from Java Exchange Works by creating an object that dispenses connections and connection Ids on request. The ConnectionPool class maintains a Hastable, using Connection objects as keys and Boolean values as stored values. The Boolean value indicates whether a connection is in use or not. A program calls getConnection() method of the ConnectionPool for getting Connection object it can use; it calls returnConnection() to give the connection back to the pool.


92. Why should we go for interservlet communication?- Servlets running together in the same server communicate with each other in several ways. The three major reasons to use interservlet communication are: a) Direct servlet manipulation - allows to gain access to the other currently loaded servlets and perform certain tasks (through the ServletContext object) b) Servlet reuse - allows the servlet to reuse the public methods of another servlet. c) Servlet collaboration - requires to communicate with each other by sharing specific information (through method invocation)


93. Is it possible to call servlet with parameters in the URL?- Yes. You can call a servlet with parameters in the syntax as (?Param1 = xxx || m2 = yyy).


94. What is Servlet chaining?- Servlet chaining is a technique in which two or more servlets can cooperate in servicing a single request. In servlet chaining, one servlet’s output is piped to the next servlet’s input. This process continues until the last servlet is reached. Its output is then sent back to the client.


95. How do servlets handle multiple simultaneous requests?- The server has multiple threads that are available to handle requests. When a request comes in, it is assigned to a thread, which calls a service method (for example: doGet(), doPost() and service()) of the servlet. For this reason, a single servlet object can have its service methods called by many threads at once.


96. What is the difference between TCP/IP and UDP?- TCP/IP is a two-way communication between the client and the server and it is a reliable and there is a confirmation regarding reaching the message to the destination. It is like a phone call. UDP is a one-way communication only between the client and the server and it is not a reliable and there is no confirmation regarding reaching the message to the destination. It is like a postal mail.


97. What is Inet address?- Every computer connected to a network has an IP address. An IP address is a number that uniquely identifies each computer on the Net. An IP address is a 32-bit number.


98. What is Domain Naming Service(DNS)?- It is very difficult to remember a set of numbers(IP address) to connect to the Internet. The Domain Naming Service(DNS) is used to overcome this problem. It maps one particular IP address to a string of characters. For example, www. mascom. com implies com is the domain name reserved for US commercial sites, moscom is the name of the company and www is the name of the specific computer, which is mascom’s server.


99. What is URL?- URL stands for Uniform Resource Locator and it points to resource files on the Internet. URL has four components: http://www. address. com:80/index.html, where http - protocol name, address - IP address or host name, 80 - port number and index.html - file path.


100. What is RMI and steps involved in developing an RMI object?- Remote Method Invocation (RMI) allows java object that executes on one machine and to invoke the method of a Java object to execute on another machine. The steps involved in developing an RMI object are: a) Define the interfaces b) Implementing these interfaces c) Compile the interfaces and their implementations with the java compiler d) Compile the server implementation with RMI compiler e) Run the RMI registry f) Run the application

Continue Reading