Thursday, January 31, 2013

C Language Example # 14 For Loop Example : Display Sum of 1 to N Terms.


C Language Example # 14 For Loop Example : Display Sum of 1 to N Terms.


Lets now starts with Looping Structure of C Programming Language.

C Language Code:

//Written by Latest Technology Guide    
//Title : Example  14 For Loop Example : Display Sum of 1 to N Terms.
  
#include <stdio.h>
#include <conio.h>



void main()
{
clrscr();

int n,i,sum=0;

printf("Enter Number : ");
scanf("%d",&n);

for(i=1;i<=n;i++)
sum=sum+i;

printf("Sum of Up To %d Number is : %d",n,sum);

getch();
}



Output:
We think there is no need of Output for this program.

--------------------------------------------------------------------------------
Explanation of C Language Example  # 14 For Loop Example : Display Sum of 1 to N Terms..

* Enter value for Number of Terms as N.
* This C Program will display sum of 1 to N Terms.

Still having doubts you can post comment, will explain in details.

Note: All programs are developed and tested using Turbo C++ 3.0 under Windows XP. We just want to provide guidelines to the users. If you are using any other Compiler or other operating system they you need to modify this program as per your requirements. 

Wednesday, January 30, 2013

C Language Example # 13 For Loop Example : Display Numbers Up to N Terms in Reverse Order


C Language Example # 13 For Loop Example : Display Numbers Up to N Terms in Reverse Order.

Lets now starts with Looping Structure of C Programming Language.


C Language Code:

//Written by Latest Technology Guide    
//Title : Example 13 For Loop Example : Display Numbers Up to N Terms in Reverse Order.
  
#include <stdio.h>
#include <conio.h>



void main()
{
clrscr();

int n,i;

printf("Enter Number of Terms : ");
scanf("%d",&n);

for(i=n;i>=1;i--)
printf("%d ",i);

getch();
}



Output:

We think there is no need of Output for this program.


--------------------------------------------------------------------------------
Explanation of C Language Example  # 13 For Loop Example : Display Numbers Up to N Terms in Reverse Order.

* Enter value for Number of Terms as N.
* This C Program will will display numbers from N to 1. (Means it will reverse the output from our previous program)

Still having doubts you can post comment, will explain in details.

Note: All programs are developed and tested using Turbo C++ 3.0 under Windows XP. We just want to provide guidelines to the users. If you are using any other Compiler or other operating system they you need to modify this program as per your requirements. 

Tuesday, January 29, 2013

Microsoft Visual Studio Lesson # 01


What is Microsoft Visual Studio ?
Number of books are available to explain this but lets discuss in short, Its Development Environment developed for programming using Visual Language is developed by Microsoft Company.

How to start learning of Microsoft Visual Studio?
Best way to learn Microsoft Visual Studio is to start development of program with definition. Here we will demonstrate demo of different application with coding to understand the world of Microsoft Visual Studio.

Which Version of Microsoft Visual Studio we are going to discuss here ?
Here we will start demo of Visual Studio 2008 onward.


Lets start Microsoft Visual Studio First Hello world Application !

There are two ways to start Microsoft Visual Studio 

1) Goto Start -> Run   Type : devenv and press Enter (Shortcut way to run Microsoft Visual Studio)

2) Goto Start -> Program Files -> Microsoft Visual Studio 2008 -> Visual Studio 2008


Lets Develop Hello World Application Using Microsoft Visual Studio.

* Hope you have already open Visual Studio.
* Now Goto File -> New -> Project.
























* Select Project Type : Visual Basic -> Windows
* Select Templates : Windows Forms Application.
* Select Framework : .Net Framework 3.5
* Write Name of Application
* Write Path (You can skip this it will consider default path)
* Write Solution Name (You can skip this it will consider as per Application Name)



















* Press Ok
* Your Project is Ready with Basic Code.
* Now add Button from Toolbox to Scree as shown in the figure. (If toolbox is not visible goto View menu and Click on ToolBox or Press Ctrl + Alt + X )
* First Click on Common Controls or All Windows Forms
* Double Click on Button Control to add Button into our forms.
* Move Button1 to Center of the screen.





* Now double click on Button1 to write code for this button.





* Now Press F5 to Run Your First Project !!!!
* Click on Button1 it will display message as follow :























Still Having Doubts, Post Comment We will try to resolve it.


C Language Example # 12 For Loop Example : Display Numbers Up to N Terms

C Language Example # 12 For Loop Example : Display Numbers Up to N Terms.

Lets now starts with Looping Structure of C Programming Language.


C Language Code:

//Written by Latest Technology Guide    
//Title : Example 12 : For Loop Example : Display Numbers Up to N Terms.
  
#include <stdio.h>
#include <conio.h>


void main()
{
clrscr();

int n,i;

printf("Enter Number of Terms : ");
scanf("%d",&n);

for(i=1;i<=n;i++)
printf("%d ",i);

getch();
}


Output:

We think there is no need of Output for this program.


--------------------------------------------------------------------------------
Explanation of C Language Example  # 12 For Loop Example : Display Numbers Up to N Terms..

* Enter value for Number of Terms as N.
* This C Program will will display numbers from 1 to upto N Terms.

Still having doubts you can post comment, will explain in details.

Note: All programs are developed and tested using Turbo C++ 3.0 under Windows XP. We just want to provide guidelines to the users. If you are using any other Compiler or other operating system they you need to modify this program as per your requirements. 

Monday, January 28, 2013

What is Java Servlets?


What is Java Servlets?

A Servlet is a Java-based server-side web technology. Technically speaking, a Servlet is a Java class in Java EE that conforms to the Java Servlet API, a protocol by which a Java class may respond to requests. Servlets could in principle communicate over any client–server protocol, but they are most often used with the HTTP protocol. Thus "Servlet" is often used as shorthand for "HTTP Servlet". Thus, a software developer may use a servlet to add dynamic content to a web server using the Java platform. The generated content is commonly HTML, but may be other data such as XML. Servlets can maintain state in session variables across many server transactions by using HTTP cookies, or URL rewriting.


To deploy and run a Servlet, a web container must be used. A web container (also known as a Servlet container) is essentially the component of a web server that interacts with the Servlets. The web container is responsible for managing the lifecycle of Servlets, mapping an URL to a particular Servlet and ensuring that the URL requester has the correct access rights.
The Servlet API, contained in the Java package hierarchy javax.servlet, defines the expected interactions of the web container and a servlet.


A servlet is an object that receives a request and generates a response based on that request. The basic Servlet package defines Java objects to represent Servlet requests and responses, as well as objects to reflect the Servlet's configuration parameters and execution environment. The package javax.servlet.http defines HTTP-specific subclasses of the generic servlet elements, including session management objects that track multiple requests and responses between the web server and a client. Servlets may be packaged in a WAR file as a web application.


Servlets can be generated automatically from JavaServer Pages (JSP) by the JavaServer Pages compiler. The difference between Servlets and JSP is that Servlets typically embed HTML inside Java code, while JSPs embed Java code in HTML. While the direct usage of Servlets to generate HTML (as shown in the example below) has become rare, the higher level MVC web framework in Java EE (JSF) still explicitly uses the Servlet technology for the low level request/response handling via the FacesServlet. A somewhat older usage is to use Servlets in conjunction with JSPs in a pattern called "Model 2", which is a flavor of the model–view–controller pattern.


Methods of  Servlet
A Generic servlet contains the following five methods:

init()

public void init(ServletConfig config) throws ServletException
The init() method is called only once by the servlet container throughout the life of a servlet. By this init() method the servlet get to know that it has been placed into service. 

Parameters - The init() method takes a ServletConfig object that contains the initialization parameters and servlet's configuration and throws a ServletException if an exception has occurred.

service()

public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException

Once the servlet starts getting the requests, the service() method is called by the servlet container to respond. The servlet services the client's request with the help of two objects. These two objects javax.servlet.ServletRequest and  javax.servlet.ServletResponse are passed by the servlet container.  

The status code of the response always should be set for a servlet that throws or sends an error.

Parameters -  The service() method takes the ServletRequest object that contains the client's request and the object ServletResponse contains the servlet's response. The service() method throws ServletException and IOExceptions exception.
 

getServletConfig()

public ServletConfig getServletConfig() 
This method contains parameters for initialization and startup of the servlet and returns a ServletConfig object. This object is then passed to the init method. When this interface is implemented then it stores the ServletConfig object in order to return it. It is done by the generic class which implements this inetrface.
Returns -  the ServletConfig object
destroy()

public void destroy() 
This method is called when we need to close the servlet. That is before removing a servlet instance from service, the servlet container calls the destroy() method. Once the servlet container calls the destroy() method, no service methods will be then called . That is after the exit of all the threads running in the servlet, the destroy() method is called. Hence, the servlet gets a chance to clean up all the resources like memory, threads etc which are being held. 

  
Life Cycle of Servlet

The life cycle of a servlet can be categorized into four parts:
  1. Loading and Inatantiation: The servlet container loads the servlet during startup or when the first request is made. The loading of the servlet depends on the attribute <load-on-startup> of web.xml file. If the attribute <load-on-startup> has a positive value then the servlet is load with loading of the container otherwise it load when the first request comes for service. After loading of the servlet, the container creates the instances of the servlet.
  2. Initialization: After creating the instances, the servlet container calls the init() method and passes the servlet initialization parameters to the init() method. The init() must be called by the servlet container before the servlet can service any request. The initialization parameters persist untill the servlet is destroyed. The init() method is called only once throughout the life cycle of the servlet.

    The servlet will be available for service if it is loaded successfully otherwise the servlet container unloads the servlet.
  3. Servicing the Request: After successfully completing the initialization process, the servlet will be available for service. Servlet creates seperate threads for each request. The sevlet container calls the service() method for servicing any request. The service() method determines the kind of request and calls the appropriate method (doGet() or doPost()) for handling the request and sends response to the client using the methods of the response object.
  4. Destroying the Servlet: If the servlet is no longer needed for servicing any request, the servlet container calls the destroy() method . Like the init() method this method is also called only once throughout the life cycle of the servlet. Calling the destroy() method indicates to the servlet container not to sent the any request for service and the servlet  releases all the resources associated with it. Java Virtual Machine claims for the memory associated with the resources for garbage collection.




Advantages of Servlet

1.  Portability
As we know that the servlets are written in java and follow well known standardized APIs so they are highly portable across operating systems and server implementations.  We can develop a servlet on Windows machine running the tomcat server or any other server and later we can deploy that servlet effortlessly on any other operating system like Unix server. So servlets are write once, run anywhere (WORA) program.

2.  Powerful
We can do several things with the servlets which were difficult or even impossible to do with CGI, for example the servlets can talk directly to the web server while the CGI programs can't do. Servlets can share data among each other, they even make the database connection pools easy to implement. They can maintain the session by using the session tracking mechanism which helps them to maintain information from request to  request. It can do many other things which are difficult to implement in the CGI programs.

3.  Efficiency
As compared to CGI the servlets invocation is highly efficient. When the servlet get loaded in the server, it remains in the server's memory as a single object instance. However with servlets there are N threads but only a single copy of the servlet class. Multiple concurrent requests are handled by separate threads so we can say that the servlets are highly scalable. 

4.  Safety
As servlets are written in java, servlets inherit the strong type safety of java language. Java's automatic garbage collection and a lack of pointers means that servlets are generally safe from memory management problems. In servlets we can easily handle the errors due to  Java's exception handling mechanism. If any exception occurs then it will throw an exception.

5.  Extensibility
The servlet API is designed in such a way that it can be easily extensible. As it stands today, the servlet API support Http Servlets, but in later date it can be extended for another type of servlets.

6.  Inexpensive
There are number of  free web servers available for personal use or for commercial purpose. Web servers are relatively expensive. So by using the free available web servers you can add servlet support to it.





Friday, January 25, 2013

What is JSP ? or What is Java Server Pages ? or Define JSP.


Architecturally, JSP may be viewed as a high-level abstraction of Java servlets. JSPs are translated into servlets at runtime; each JSP's servlet is cached and re-used until the original JSP is modified.

JSP can be used independently or as the view component of a server-side model–view–controller design, normally with JavaBeans as the model and Java servlets (or a framework such as Apache Struts) as the controller. This is a type of Model 2 architecture.

JSP allows Java code and certain pre-defined actions to be interleaved with static web markup content, with the resulting page being compiled and executed on the server to deliver a document. The compiled pages, as well as any dependent Java libraries, use Java bytecode rather than a native software format. Like any other Java program, they must be executed within a Java virtual machine (JVM) that integrates with the server's host operating system to provide an abstract platform-neutral environment.

JSP pages are usually used to deliver HTML and XML documents, but through the use of OutputStream, they can deliver other types of data as well.


Lifecycle of JSP (Java Server Pages)

JSP’s life cycle can be grouped into following phases.

1. JSP Page Translation:
A java servlet file is generated from the JSP source file. This is the first step in its tedious multiple phase life cycle. In the translation phase, the container validates the syntactic correctness of the JSP pages and tag files. The container interprets the standard directives and actions, and the custom actions referencing tag libraries used in the page.

2. JSP Page Compilation:

The generated java servlet file is compiled into a java servlet class.
Note: The translation of a JSP source page into its implementation class can happen at any time between initial deployment of the JSP page into the JSP container and the receipt and processing of a client request for the target JSP page.

3. Class Loading:

The java servlet class that was compiled from the JSP source is loaded into the container.

4. Execution phase:


In the execution phase the container manages one or more instances of this class in response to requests and other events.
The interface JspPage contains jspInit() and jspDestroy(). The JSP specification has provided a special interface HttpJspPage for JSP pages serving HTTP requests and this interface contains _jspService().

5. Initialization:

jspInit() method is called immediately after the instance was created. It is called only once during JSP life cycle.

6. _jspService() execution:

This method is called for every request of this JSP during its life cycle. This is where it serves the purpose of creation. Oops! it has to pass through all the above steps to reach this phase. It passes the request and the response objects. _jspService() cannot be overridden.

7. jspDestroy() execution:

This method is called when this JSP is destroyed. With this call the servlet serves its purpose and submits itself to heaven (garbage collection). This is the end of jsp life cycle.
jspInit(), _jspService() and jspDestroy() are called the life cycle methods of the JSP.


JSP basic Syntax

This part will give basic idea on simple syntax (ie. elements) involved with JSP development:

The Scriptlet

A scriptlet can contain any number of JAVA language statements , variable or method declarations, or expressions that are valid in the page scripting language. i.e. Scriplet contains java business logic

Following is the syntax of Scriptlet:

<% Business Login in Java %>

Any text, HTML tags, or JSP elements you write must be outside the scriptlet. Following is the simple and first example for JSP:

<html>
<head><title>Hello World</title></head>
<body>
Hello World!<br/>
<%
out.println("Your IP address is " + request.getRemoteAddr());
%>
</body>
</html>
This would generate following result:
Hello World!
Your IP address is 127.0.0.1

NOTE: Assuming that Apache Tomcat is installed in C:\apache-tomcat-7.0.2 and your environment is setup as per environment setup tutorial.

JSP Declarations:

A declaration declares one or more variables or methods that you can use in Java code later in the JSP file. You must declare the variable or method before you use it in the JSP file.

Following is the syntax of JSP Declarations:

<%! declaration; [ declaration; ]+ ... %>
Following is the simple example for JSP Comments:
<%! int i = 0; %> 
<%! int a, b, c; %> 
<%! Circle a = new Circle(2.0); %>

JSP Expression:

A JSP expression element contains a scripting language expression that is evaluated, converted to a String, and inserted where the expression appears in the JSP file.

Because the value of an expression is converted to a String, you can use an expression within a line of text, whether or not it is tagged with HTML, in a JSP file.

The expression element can contain any expression that is valid according to the Java Language Specification but you cannot use a semicolon to end an expression.


Following is the syntax of JSP Expression:

<%= expression %>


Following is the simple example for JSP Expression:

<html> 
<head><title>A Comment Test</title></head> 
<body>
<p>
   Today's date: <%= (new java.util.Date()).toLocaleString()%>
</p>
</body> 
</html> 


This would generate following result:

Today's date: 01-Jan-2013 00:00:00 


Introduction to Java Programming : Simple Java Program


Simple Java Program

In this section, our plan is to lead you into the world of Java programming by taking you through the three basic steps required to get a simple program running. The Java system is a collection of applications not unlike any of the other applications that you are in touch to using (such as your word processor, e-mail program, or Internet browser). As with any application, you need to be sure that Java is properly installed on your computer. You also need an editor and a terminal application. Here are three steps to make basic application.

  1. Create the program by typing it into a text editor and saving it to a file named, say, MyProgram.java.
  2. Compile it by typing "javac MyProgram.java" in the Command Prompt(cmd).
  3. Run (or execute) it by typing "java MyProgram" in the Command Prompt(cmd).
Creating a Java program. A program is nothing more than a sequence of characters, like a sentence, a paragraph, or a poem. To create one, we need to write sequence of characters systematicall just like we write in e-mail. HelloWorld.java is an example program. Type these character into your text editor and save it into a file named HelloWorld.java

public class HelloWorld {
   public static void main(String[] args) {
      System.out.println("Hello World !!!");
   }
}

Note. It is compulsory to give program name and class name which contain the public static void main method same.

Compiling a Java program. At first, it might seem to you as though the Java programming language is designed to be best understood by the computer. Actually, the language is designed to be best understood by the programmer (that's you). A compiler is an application that translates programs from the Java language to a language more suitable for executing on the computer. It takes a text file with the .java extension as input (your program) and produces a file with a .class extension (the computer-language version). To compile go to the path of the file and type boldfaces text bold boldfaced text below at the cmd.
 
javac HelloWorld.java

If you typed in the program correctly, you should see no error messages. Otherwise, go back and make sure you typed in the program exactly as it appears above.

Executing a Java program. Once you compile your program, you can run it. This is the exciting part, where the computer follows your instructions. To run the HelloWorld program, type the following at the cmd:

java HelloWorld

If all goes well, you should see the following response
Hello World !!!
  • Understanding a Java program. The key line with System.out.println() send the text "Hello World !!!". When we begin to write more complicated programs, we will discuss the meaning of public, class, main, String[], args, System.out, and so on.
  • Creating your own Java program. For the time being, all of our programs will be just like HelloWorld.java, except with a different sequence of statements in main(). The easiest way to write such a program is to:
    • Copy HelloWorld.java into a new file whose name is the program name followed by .java.
    • Replace HelloWorld with the program name everywhere.
    • Replace the print statement by a sequence of statements.
Errors.
Most errors are easily fixed by carefully examining the program as we create it, in just the same way as we fix spelling and grammatical errors when we type an e-mail message.
  • Compile-time errors. These errors are caught by the system when we compile the program, because they prevent the compiler from doing the translation (so it issues an error message that tries to explain why).
  • Run-time errors. These errors are caught by the system when we execute the program, because the program tries to perform an invalid operation (e.g., division by zero).
  • Logical errors. These errors are (hopefully) caught by the programmer when we execute the program and it produces the wrong answer. Bugs are the bane of a programmer's existence. They can be subtle and very hard to find.
One of the very first skills that you will learn is to identify errors; one of the next will be to be sufficiently careful when coding to avoid many of them.

Some Idea regarding Java Program:
Hey guys, Here I have provided some more basic examples, kindly follow it and check output,

Swap Two Number Example using Core Java:

  public class SwapElementsExample {
   
          public static void main(String[] args) {
                 
                  int num1 = 10;
                  int num2 = 20;
                
                  System.out.println("Before Swapping");
                  System.out.println("Value of num1 is :" + num1);
                  System.out.println("Value of num2 is :" +num2);
                 
                  //swap the value
                  swap(num1, num2);
          }
   
          private static void swap(int num1, int num2) {
                 
                  int temp = num1;
                  num1 = num2;
                  num2 = temp;
                 
                  System.out.println("After Swapping");
                  System.out.println("Value of num1 is :" + num1);
                  System.out.println("Value of num2 is :" +num2);
                 
          }
  }

Reverse No. Example Using Core Java

  public class ReverseNumber {
   
          public static void main(String[] args) {
                 
                  //original number
                  int number = 1234;
                  int reversedNumber = 0;
                  int temp = 0;
                 
                  while(number > 0){
                         
                          //use modulus operator to strip off the last digit
                          temp = number%10;
                         
                          //create the reversed number
                          reversedNumber = reversedNumber * 10 + temp;
                          number = number/10;
                           
                  }
                 
                  //output the reversed number
                  System.out.println("Reversed Number is: " + reversedNumber);
          }
  }