Tutorial

by -

Since now you are familiar with instantiating inner classes in Java, we can talk about Polymorphism and Method Overloading. Polymorphism is the capability of an Java object to respond uniformly to achieve specific behavior to the method calls of the same name but with different implementations. In Java the concept of Polymorphism can be achieved in several ways. Let’s talk about one good way here.

What is Method Overloading

In Java it is possible to define two or more methods within the same class that share the same name, as long as their parameter declarations are different. When this is the case, the methods are said to be overloaded, and the process is referred to as method overloading. Method overloading supports polymorphism because it is one way that Java implements the “one interface, multiple methods” paradigm.

Properties

  • In a class, the concept of method overloading does not allow the external user to be aware about the internal processing of the system.
  • Overloaded methods differ in either number of parameters or type of parameters or sequence of parameters.
  • Overloaded methods are resolved in the following sequences:
    1. Number of Parameters.
    2. Type of Parameters.
    3. Sequence of Parameters.

On the basis of these methods are invoked accordingly to return the desired output.

  • Method Overloading allows the user to achieve the compile time polymorphism.
  • Overloaded methods may have the same or different return types. It doesn’t participate in resolving method overloading.

Java Program for Method Overloading

class Figure{
  /* Calculate Area of Square */
  void area(double length){
    System.out.println("Area of Square is: "+Math.pow(length,2));
  }
  /* Calculate Area of Rectangle */
  void area(double length,double breadth){
    System.out.println("Area of Rectangle is: "+(length*breadth));
  }
  /* Calculate Area of Cylinder */
  void area(double radius,int height){
    System.out.println("Area of Cylinder is: "+(2*3.14*Math.pow(radius,2)*height));
  }
  /* Calculate Area of Cube */
  void area(int arms){
    System.out.println("Area of Cube is: "+(6*arms*arms));
  }
}

class CalculateArea{
  public static void main(String args[]){
    Figure fig = new Figure();
	fig.area(5.25);
	fig.area(4.5,5.5);
    fig.area(2);
	fig.area(3.2,6);
  }
}

Output

method overloading in Java

Explanation of the Java Code & Output

Here within class Figure area() is a overloaded method, having same name with different implementations i.e. “one interface, multiple methods” paradigm. You can easily make out that the same method is used to perform different operations i.e. calculating areas of different geometric areas based on the number/ type/ sequence of parameters passed and desired output is produced.

Method invocation may be of any order. As method area() to calculate area of cube invoked before invoking method area() to calculate area of cylinder.

In the program we have also called one static method pow() of Math class which is a member of java.lang package to calculate the square of any number.

Flash on

During resolving overloaded methods Java employs its automatic type conversions only if no exact match is found. As you can see below that class Overload does not define display (int) but it already has defined display (double). Therefore, when display() is called with an integer argument inside OverloadDemo, no matching method is found. However, Java can automatically convert an integer into a double, and this conversion can be used to resolve the call. Therefore, after display (int) is not found, Java elevates i to double and then calls display (double). Of course, if display (int) had been defined, it would have been called instead.

class Overload {
  // display method with no parameters
  void display() {
    System.out.println("No parameters");
  }
  // Overload display for two integer parameters.
  void display(int a, int b) {
    System.out.println("a and b: " + a + " " + b);
  }
  // overload display for a double parameter
  void display(double a) {
    System.out.println("a: " + a);
  }
}
class OverloadDemo {
  public static void main(String args[]) {
    Overload overload = new Overload();
     int i = 88;
     ob.display();
     ob.display (10, 20);
     ob.display (i); // this will invoke display(double)
     ob.display (123.2); // this will invoke display(double)
  }
}

N.B: This conversion is true for lower datatype ( e.g int) to higher datatype (e.g double) conversion not for the reverse(double to int).

In our next tutorial we will learn about Constructor overloading in Java.

Checkout more useful tutorials and definitive guidelines on Java programming here.

by -

HTML has ruled for almost a decade as the main markup language for websites. Even though some of the old school programmers use HTML but the truth is that the next level is XHTML. HTML stands for Hyper Text Markup Language and it basically describes the structure of text information including images in a web document. XHTML stands for Extensible Hyper Text Markup Language and most of its features are similar to that of HTML and is known to be the successor to HTML.

difference between HTML and XHTML

Most Important Differences Between HTML and XHTML

There are the most important differences between HTML and XHTML and they can be classified under MIME types, Syntax and Parsing.

MIME Types

MIME stands for Multipurpose Internet Mail Extensions and in HTML you need to use text/html. In XHTML, you need to use XML MIME type like application/xhtml+xml or application/xml. Here are some HTML MIME types:

HTML mime types

Parsing and Syntax

The biggest difference between the two is that HTML uses its own parsing requirement while XHTML uses XML parsing requirement. Let’s look at each feature and the difference in each feature in HTML and XHTML.

Parsing Modes

HTML: In HTML, three different parsing modes have been defined and they are quirks mode, no quirks mode, and limited quirks mode.

XHTML: There is only one parsing mode defined, which is basically based on XML parsing rules.

Case Sensitivity

HTML: No elements are case sensitive.

XHTML: Every element is case sensitive and must be used in lower case only.

Error Handling

HTML: In HTML, there is no well-formedness constraint and hence there are no errors that are fatal

XHTML: In XHTML, well-formedness errors are all fatal

Character Encoding

HTML: In HTML, the XML declaration is treated like a bogus comment or in other words it is forbidden. Even though, you can use the charset attribute with the meta element.

XHTML: In XHTML, XML declaration is used for specifying the character encoding. The default character encoding is UTF-8 or UTF-16.

Namespaced Element

HTML: In HTML, namespaced prefixes are not allowed. Foreign elements are not treated as if they belong to another namespace and are displayed by default as inline elements.

XHTML: In XHTML, the namespace needs to be declared for HTML elements. You can use foreign elements independent of HTML elements.

Xlink attributes

HTML: In HTML, Foreign elements can use attributes like xlink:arcrole, xlink:actuate, xlink:role, xlink:href, xlink:title, xlink:show, and xlink:type. You can use only xlink as prefix.

XHTML: Based on conformance rules that have been defined by Namespaces in XML, XLink attributes can be specified on foreign elements. You can use any prefix.

difference between HTML and XHTML

Attributes

HTML: In HTML, names are not case sensitive and it allows attribute minimization.

XHTML: In XHTML, names are case sensitive and it doesn’t allow attribute minimization. All attribute values must be quoted.

The DOCTYPE

HTML: In HTML, the DOCTYPE is mandatory even though it has no value. DOCTYPE is treated case insensitively and all HTML documents should use <! DOCTYPE html >

XHTML: In XHTML, you can even use an HTML5 DOCTYPE or any custom DOCTYPE.

difference between HTML and XHTML

All tags within XHTML must be properly closed

While using XHTML you will need to close any tags which is opened and use short tags properly. Otherwise the page may render differently on different browsers as they will close those tags as per their anticipation.

CDATA Comment

HTML: <![CDATA[...]]> is not a valid CDATA comment. Anything that goes within this comment is considered as content data.

XHTML: <![CDATA[...]]> is a valid CDATA comment. If the content within this section contains any “]]>” then it can give unexpected errors.

Wrap Up

So these are some of the major differences between HTML and XHTML which every web designer should be aware of. Cross browser compatibility is one of the considerable enhancements on XHTML 1.1, a subset of which even now supports most advanced mobile browser and is known as XHTML Mobile Profile (XHTML MP).

by -

In tutorial 10, we asked you what if user enters other than the options that we have thought of. For Example, What if user enters “Blue” as jersey color instead of “Red” or “White”? Yes, you can form a hierarchy of if-else statements to accommodate this condition but there is better way. Using Select Case statements, it is possible to add more more than two conditions by keeping the code simple. Let us learn how to work with Select Case.

First, create a form as shown below:

Now double click on the button and put the following code between “Private Sub” and “End Sub”

Dim Color As String
 Dim Club As String
Color = txt_SelectCase.Text
Select Case Color
Case "Red"
     Club = "Manchester United"
Case "White"
     Club = "England"
 Case Else
     Club = "Wrong Entry"
End Select
MsgBox(Club)

In the above program, the part we are not aware of is from “Select Case Color” to “End Select”. It is a Select Case box where we have defined a case or condition and have instructed VB what to display if certain condition is being satisfied. For Example, when user will enter something other than “Red” or “White”, it will be categorized under Case “Else”, which holds true for any value other than specified values. That is, when user enters “Red”, we ask VB to check what Case it is satisfying and what is action to be taken after the check. Now run your program and put “Blue” or “Green” as input to see what happens:

Now that we have applied Select Case for a single condition evaluation, let us see how to use it when condition is a group of entities that satisfy similar condition. Like if user’s age lies between 21 to 30, he is in his thirties. Let us see the code so that things will get clear up in your mind. For that, add one more button in your form and name it as btn_to. Put the following code for new button:

Dim Age As Integer
Select Case Age
 Case 11 To 19
    MsgBox("Teenage")
 Case 20 To 29
    MsgBox("Thirties")
 Case 30 To 39
    MsgBox("Fourties")
 Case Else
    MsgBox("You are Old.")
 End Select

Here everything else is same as former code the only difference is word “To”. We can use word “To” to specify the range for condition within Select Case statement. Now run the program and enter any number to see the output. In next tutorial we will see how to provide  options to user through drop down list and use Select Case statements to work on those options. Till then, Keep Coding!

by -

In Java programming language, when a class is defined within another class then such a class is called a nested class or inner class. Nested classes is a very unique feature of Java that has been included since jdk1.1. Always remember, this nesting functionality is a relationship between classes only, not between Java objects. Previously we have talked about how to instantiate instance variable in Java, and now we will take a look at how to instantiate an inner class in Java.

Types of Nested Classes in Java

Non-static Nested Class

Non-static nested classes are called inner classes. It has access to all of its enclosing class’s instance data,

including private fields and methods.

Syntax

[modifiers] class OuterClassName {
  code...
  [modifiers] class InnerClassName {
    code....
  }
}

Creation

<OuterClassName> outerObj = new <OuterClassName>(arguments);
<OuterClassName>.<InnerClassName> innerObj = outerObj.new <InnerClassName> (arguments);

Properties

  1. The outer class (the class containing the inner class) can instantiate as many number of inner class objects as it wishes, inside it’s code.
  2.  If the inner class is public & the containing class as well, then code in some other unrelated class can as well create an instance of the inner class.
  3. No inner class objects are automatically instantiated with an outer class object.
  4. Inner class code has free access to all elements of the outer class object that contains it, by name (no matter what the access level of the elements is), if the inner class has a variable with same name then the outer class’s variable can be accesse like this:
    <OuterClassName>.this.<variableName>
  5. The outer class can call even the private methods of the inner class.
  6. The inner class object must be associated with an instance of the outer class.

Static Nested Class

Nested classes that are declared static are simply called static nested classes. A static class has no access to instance-specific data.

Syntax 

<access-specifier> class OuterClassName {
  public static class <StaticInnerClassName> {
      code. . .
  }
  code . . .
}

Creation

<OuterClassName>.<InnerClassName> innerObj = new <OuterClassName>.<InnerClassName>(arguments);

Properties

  1. For static inner class, then static inner class can be instantiated without an outer class instance.
  2. Static members of the outer class are visible to the static inner class, what ever their access level is.
  3. Non-static members of the outer class are not available, because there is no instance of the outer class.
  4.  An inner class may not have static members unless the inner class is itself marked as static.
  5. Sometimes static nested classes are not referred to as inner class at all, as they don’t require outer class’s instance.
  6. A static inner class is just like any other inner class, but it dose not have the reference to its outer class object that generated it.

Access Modifiers for Nested or Inner Classes

  • public
  • protected
  • private
  • default

Features of Nested Class

An object of an inner class has an implicit reference to the outer class object that instantiated it. Through this pointer, it gains access to any variable of the outer object. Only static inner classes don’t have this pointer but can access all the static members only using outer class name. It is actually invisible when we write the code, but compiler takes care of it. Inner classes are actually a phenomenon of the compiler and not the JVM. This feature makes Java inner classes richer and more useful.

Advantages

  • It is a way of logically grouping classes that are only used in one place.
  • It increases encapsulation.
  • Nested classes can lead to more readable and maintainable code.
  • Logical grouping of classes – If a class is useful to only one other class, then it is logical to embed it in that class and keep the two together. Nesting such “helper classes” makes their package more streamlined.
  • Increased encapsulation – Consider two top-level classes, A and B, where B needs access to members of A that would otherwise be declared private. By hiding class B within class A, A’s members can be declared private and B can access them. In addition, B itself can be hidden from the outside world.

Program 1

/* within the scope of outer class */
class Outer{
  int var1 = 2;
  int var2 = 3;

  /* Inner Class */
  class Inner{
    void add(){
      System.out.println("Addition is:"+(var1+var2));
    }
  }

  void show(){
    Inner in = new Inner();
    in.add();
  }
}

class NestedClassDemo{
  public static void main(String args[]){
    Outer out = new Outer();
    out.show();
  }
}

Output 1

code for nested class in java

Program 2

/* Outside the scope of outer class */
class Outer{
  int var1 = 2;
  int var2 = 3;

  /* Inner Class */
  class Inner{
    void add(){
      System.out.println("Addition is:"+(var1+var2));
    }
  }
}

class NestedClassDemo1{
  public static void main(String args[]){
    Outer.Inner in = new Outer().new Inner();
    in.add();
  }
}

Output 2

code for nested class in java

Explanation of Code & Output

In the first program we have instantiated the nested class Inner in a method declared within the Outer class i.e.

within the scope of outer class. We will specially instantiate inner classes within the scope of outer class when it the inner class is Private as we know private members can’t be accessed outside the scope of that class containing private members.

In the second program we have instantiated the nested class Inner outside the scope of Outer class. Syntax seems to be difficult but its not like that. It’s too easy:

We will break this statement into two:

Outer out =  new Outer();
Outer.Inner in = out.new Inner();

First we have to create an object for outer class. Then we will create object for Inner class as Inner class is the member of Outer class so we have to uniquely recognize the Inner class, can be done with Outer.Inner then we have to create the object which is done by new operator followed by the constructor of that particular class. Same thing is done here.

Flash on

After compiling nested class, two .class files will be generated with Outer.class and Outer$Inner.class (here class Inner is inside class Outer).

Checkout more useful tutorials and definitive guidelines on Java programming here.

by -

We have gone through VB.net tutorials so far, where our logic for coding was quite simple. Either we wanted to do mathematical operations or want to show some result in textbox. But what about the situations, where one query can have more than one possible answers. Like, If famous English footballer Wayne Rooney is in Red Jersey, it means he belongs to Manchester United FC but When he is in White Jersey, he belongs to England’s National Football team. Here, we have put some condition to get the exact answer to our query. To work out similar situation in VB.Net, we use conditional statements like If-Then, If-Else, Select and so on. In this tutorial, we will study how to implement If statements.

Now, we will formulate above given example into proper syntax as follows:

If Red Jersey Then Manchester United

Thus, when user will input word “Red”, our program must answer it with “Manchester United”. Let us try coding for it. Open a new project, name it “If Statements” and design a form as shown below:

Now double click on “Click” button and put the following code:

If TextBox1.Text = "Red" Then
MsgBox("Manchester United")
End If

Now it is time to check our code. So Run the program and put “Red” as input in textbox and click the button. You must get following output

But what when player is wearing white jersey? Do we have to insert another button and put same code there again? No. For that purpose, we can use Else statement which is a part of If-Else statements. We just have to make little modifications to the previously written button code:

If TextBox1.Text = "Red" Then
            MsgBox("Manchester United")
        ElseIf TextBox1.Text = "White" Then
            MsgBox("England")
        End If

Run the code and put “White” in textbox. Click on button and see the result. It must be something like this:

Now you must have understood how and where If-Else statement works. Here is one task for you. Suppose user gives anything other than “Red” or “white” as input, VB must display “Wrong Input. Please Re-enter” as output. Let us know how you code it and if there are any difficulties.

by -

In tutorial 8, we were facing a difficulty about entering two digit number in a textbox. So here is a solution; put following line of code in programming box for button 9. We have already put code for button 9 which you have to modify as shown below.

Textbox1.text = Textbox1.text & btn_Nine.text

Modify code for all the buttons in similar fashion and run the program. Make sure you put button name properly while modifying code for that respective button. Now you must be able to put two digit number in calculator as shown below:

Next part is to perform mathematical functions like addition. For that purpose, we have to define to integer variables to make VB store values put into textbox. If we define those variables inside “Private_Sub” section of button, it will be accessible only for that particular button. Hence we will define them as public, but how to do it? Go into coding section of your project and define two variables as integers. Let two variables be sum1 and sum2. Here is how to code if you have forgotten how to define variables:

Public Class Form1
Dim Sum1 As Integer
Dim Sum2 As Integer

Now that we have defined public variables,let us code for Add button. Double click on the addition button to open code window and put the following code in the section:

Sum1 = Sum1 + Val(TextBox1.Text)
TextBox1.Clear()

In this code, we are using a new function Val() and passing attribute as “TextBox1.Text” to it. This val function will now convert whatever is in Text property of textbox into an integer. It is important as addition operation can only be performed with the numbers and content in textbox is in String format. Thus, Val() function is used to convert datatype from String to Integer.

Now that we have added two variables, we must show them to user in textbox. It can be done with the help of equal button. Here is the code for equal button:

Sum2 = Sum1 + Val(TextBox1.Text)
TextBox1.Text = Sum2
Sum1 = 0

Here, we have utilized Sum2 variable to store value of addition of whatever is there in Sum1 plus whatever user enters in textbox as second variable to be added. This addition is transferred to textbox via Sum2 variable in second line of code. And in third line we clear up Sum1 variable so that new values can be stored in it in case of iterative addition.

To see if our code is working properly run the program and try to add two numbers. If your project is giving any error, try to check if there are any mistakes in the code. Similarly we can code for other mathematical buttons in our calculator. For any queries you can comment below. Happy Coding!

by -

Mobile phone application market is growing at a tremendous rate. Android and iOS have millions of applications in their mobile application market place. And with the success of Windows Phone platform, the mobile phone application market is expected to continue growing with applications suiting each and every need of yours. So if you are pondering on developing an application for mobiles then here are a few tips that we think you should go through.

1. Do not hog Memory and CPU

Most of the smart phones available in the market today come with around 512MB or 1GB RAM and around 1 GHz processors. Some of the new smart phones also encompass dual core processors. These handsets perform like a pro. However excessive usage of CPU drains the battery quickly thereby requiring frequent recharging. Apart from high CPU usage make sure your application does not hog memory as this can

2. Prevent Unnecessary Network usage

Sending the right amount of information at the right time is key in applications that are constantly connected to some remote backend server. If your mobile phone application needs to constantly retrieve and/or update a server make sure you send just the necessary information at the right time. This leads to precise network usage avoiding unnecessary network traffic. Being aware of network restrictions helps a lot.

3.Develop for Multiple Platforms

Developing your application for multiple platforms helps you reach out to a large customer base. It also helps in lowering your applications’ selling price thereby increasing the chances of a customer purchasing your application. Do note that developing an application for multiple platforms is a time-consuming task and you might miss on some of the features available in a particular device or platform.

4. Consistency Is The Key To a Uniform User Experience

Try as far as possible to keep the look and feel of your mobile phone application the same on different platforms. Indeed this is a difficult task but if succeeded then it gives a good user experience.

5.Get Registered and Certified

Getting yourself registered to the application developer community as this has many benefits. Firstly the publisher ensures that you get paid for you application. Secondly you get access to their Software Development Kits. Also ensure that you get your application certified from the publisher. Certified applications are more likely to be downloaded by users as they give the feel of authenticity.

Do let me know if you have any questions.

by -

Java, like most other powerful programming languages, supports multi-dimensional arrays, like 2 dimensional and 3 dimensional arrays. Previously we have discussed about working with one dimensional arrays in Java. In this tutorial let’s discuss about 2 dimensional and 3 dimensional arrays. The same principles are applied to higher dimension arrays as well.

2 Dimensional Array in Java

There are two ways to implement 2-dimensional arrays. Many languages reserve a block of memory large enough to hold all elements of the full, rectangular, array (number of rows times number of columns times the element size). Java doesn’t do this. Instead Java builds multi-dimensional arrays from many one-dimensional arrays, the so-called “arrays of arrays” approach.

Two-dimensional arrays are defined as “an array of arrays”. Since an array type is a first-class Java type, we can have an array of ints, an array of Strings, or an array of Objects. For example, an array of ints will have the type int[]. Similarly we can have int[][], which represents an “array of arrays of  ints”. Such an array is said to be a two-dimensional array.

The following command:

int[][] twodimArray = new int[3][4];

declares a variable, twodimArray, of type int[][], and it initializes that variable to refer to a newly created object. That object is an array of arrays of ints. Here, the notation int[3][4] indicates that there are 3 arrays of ints in the array twodimArray, and that there are 4 ints in each of those arrays.

There are a couple of interesting consequences of this: Rows may be different sizes. Also, each row is an object (an array) that can be used independently.

Declaration

int[][] a1; // Declares, but doesn't allocate, 2-dim array.

Allocation

As with all arrays, the new keyword must be used to allocate memory for an array. For example,

int[][] a1 = new int[3][4];

Or:

int[][] a1;
a1 = new int[3][4];

Or:

double[][] ID3 = {  {1.0, 0.0, 0.0},  {0.0, 1.0, 0.0}, {0.0, 0.0, 1.0}};

This allocates an int array with 3 rows and 4 columns. As with all objects, the values are initialized to zero (unlike local variables which are uninitialized).

This actually allocates 5 objects: a one-dimensional array of 4 elements for each of the rows, and a one-dimensional array of 3 elements, with each element pointing to the appropriate row array.

Processing

Often 2-dimensional arrays are processed with nested for loops. Notice in the following example how the rows are handled as separate objects.

Java Program

public class TwoDimArrayDemo{
  public static void main(String[] args) {
    int[][] twoDimArray = new int[3][4];
    for (int i=0; i<twoDimArray.length; i++) {
      for (int j=0; j<twoDimArray[i].length; j++) {
        twoDimArray[i][j] = i;
        System.out.print(" " + twoDimArray[i][j]);
      }
      System.out.println("");
    }
  }
}

Output

code for 2 dimensional Array in Java

3 Dimensional Array in Java

Java Program

class Array3D{
  public static void main(String args[]){
    int[][][] a2 = new int[2][2][4];
    for (int i = 0; i < a2.length; i++)
    for (int j = 0; j < a2[i].length; j++)
    for (int k = 0; k < a2[i][j].length; k++)
    System.out.println("a2[" + i + "][" + j + "][" + k + "] = "+ a2[i][j][k]);
  }
}

Output

code for 3 dimensional Array in Java

Explanation of Code & Output

Multi-dimensional array is processed through nested loops. For n-dimensional array you need n number of nested loops. As I said default value for each position of an array is ‘0’. It’s proved from the output of 3-dimensional array.

Checkout more useful tutorials and definitive guidelines on Java programming here.

by -

Now let’s study the structure of Arrays in Java. Array is the most widely used data structure in Java. It can contain multiple values of the same type. Moreover, arrays are always of fixed length i.e. the length of an array cannot be increased or decreased.

Let’s have a close look over the structure of Array. Array contains the values which are implicitly referenced through the index values. So to access the stored values in an array we use indexes. Suppose an array contains “n” integers. The first element of this array will be indexed with the “0” value and the last integer will be referenced by “n-1″ indexed value.

Presume an array that contains 6 elements as shown in the figure. Each element is holding a distinct value. Here the first element is referenced by a[0] i.e. the first  index value.

We have filled the 6 distinct values in the array each referenced as:

a[0] = 1

a[1] = 2

a[2] = 3

a[3] = 4

a[4] = 5

a[5] = 6

…here n = 6, therefore n-1 is 5 where we have stored 6 which is the value of n.

Diagrammatically

a[0]

a[1]

a[2]

a[3]

a[4]

a[5]

1

2

3

4

5

6

One Dimensional Array

Array variable has a type and a valid Java identifier i.e. the array’s type and the array’s name. By type we mean the type of elements contained in an array. To represent the variable as an Array, we use [] notation. These two brackets are used to hold the array of a variable.

How to Declare an Array in Java

By array’s name, we mean that we can give any name to the array, however it should follow the predefined conventions. Below are the examples which show how to declare an array –

int days[];      //declares an array of integers

int[] years;    //declares an array of integers

String months[];   //declares an array of Strings

double salaries[];  //declares an array of doubles

It is essential to assign memory to an array when we declare it. Memory is assigned to set the size of the declared array. The “new” operator is used for the allocation of memory to the array object. Here, the new operator is followed by the type of variable and the number of elements to be allocated. In this example [ ] operator has been used to place the number of elements to be allocated.

For example:

1.

int days[] = new int[31];  //single step

this can be done in two steps also:

int days[];

days = new int[31];

2.

String []months = new String[12];        //single step

This can be done in two steps also:

String []months;

months = new String[12];

Java Program

class ArrayDemo{
  public static void main(String args[]){
    int count = 0;
    int days[] = new int[31];
    while(count<days.length){
      days[count] = ++count;
    }
    for(int index = 0;index<days.length;index++){
      System.out.println("days["+index+"] = "+days[index]);
    }
  }
}

Output

program for one dimensional array in Java

Explanation of Code & Output

In this example, a variable ‘days’ is declared which has a type array of int, that is, int[]. The variable days is initialized to reference a newly created array object. The expression ‘int[] = new int[50]‘ specifies that the array should have 50 components. To know the length of the Array, we use field length, as shown.

In our next tutorial, we will discuss about how to use multi dimensional arrays in Java.

Checkout more useful tutorials and definitive guidelines on Java programming here.

by -

Recursion is the process of defining something in terms of itself. As it relates to Java programming, recursion is the attribute that allows a method to call itself. A method that calls itself is said to be recursive and Java supports recursion.

At first this may seem like a never ending loop, and it seems our method will never finish. This might be true is some cases, but in practice we can check to see if a certain condition is true and in that case exit (return from) our method. The case in which we end our recursion is called a base case. Additionally, just as in a loop, we must change some value and incrementally advance closer to our base case.

Every recursion should have the following characteristics:

  1. A simple base case which we have a solution for and a return value.
  2. A way of getting our problem closer to the base case. i.e. a way to chop out part of the problem to get somewhat simpler problem.
  3. A recursive call which passes the simpler problem back into the method.

Advantages

The main to recursive methods is that they can be used to create clearer and simpler versions of several algorithms than can their iterative relatives. For example, the QuickSort sorting algorithm is quite difficult to implement in an iterative way.

Disadvantages

Recursive versions of many routines may execute a bit more slowly than the iterative equivalent because of the added overhead of the additional function calls. Many recursive calls to a method could cause a stack overrun. Because storage for parameters and local variables, it is possible that the stack could be exhausted. If this occurs, the java run-time system will cause an exception. However, you probably will not have to worry about this unless a recursive routine runs wild.

For example:

int myFactorial(int integer) {
  if( integer == 1) {
    return 1;
  }
  else  {
    return(integer*(myFactorial(integer-1);
  }
}

Tail recursion is defined as occurring when the recursive call is at the end of the recursive instruction. This is not the case with my factorial solution above. It is useful to notice when ones algorithm uses tail recursion because in such a case, the algorithm can usually be rewritten to use iteration instead. In fact, the compiler will (or at least should) convert the recursive program into an iterative one. This eliminates the potential problem of stack overflow.

This is not the case with head recursion, or when the function calls itself recursively in different places like in the Towers of Hanoi solution. Of course, even in these cases we could also remove recursion by using our own stack and essentially simulating how recursion would work.

In my example of factorial above the compiler will have to call the recursive function before doing the multiplication because it has to resolve the (return) value of the function before it can complete the multiplication. So the order of execution will be “head” recursion, i.e. recursion occurs before other operations.

To convert this to tail recursion we need to get all the multiplication finished and resolved before recursively calling the function. We need to force the order of operation so that we are not waiting on multiplication before returning. If we do this the stack frame can be freed up.

Previously you have seen our Java program to calculate factorial of an integer.

The proper way to do a tail-recursive factorial is this:

int factorial(int number) {
    if(number == 0) {
    return 1;
  }
  factorial_i(number, 1);
}

int factorial_i(int currentNumber, int sum) {
  if(currentNumber == 1) {
    return sum;
  } else {
    return factorial_i(currentNumber - 1, sum*currentNumber);
  }
}

Notice that in the call return factorial_i(currentNumber – 1, sum*currentNumber); both parameters are immediately resolvable. We can compute what each parameter is without waiting for a recursive function call to return. This is not the case with the previous version of factorial. This streamlining enables the compiler to minimize stack use as explained above.

You can also take the number from the user as a command line argument.

Java Recursion Program

class Factorial{
  int fact(int n){
    int result;
    if ( n ==1)
      return 1;
    result = fact (n-1) * n;
    return result;
  }
}

class Recursion{
  public static void main (String args[]){
    Factorial f =new Factorial();
    System.out.println("Factorial of 3 is " + f.fact(3));
    System.out.println("Factorial of 4 is " + f.fact(4));
    System.out.println("Factorial of 5 is " + f.fact(5));
  }
}

Output

recursion

Explanation of the Java Code & Output

If you are unfamiliar with recursive methods, then the operation of fact() may seem a bit confusing. Here is how it works. When fact()  is called with an argument of 1, the function returns 1; otherwise it returns the product of fact(n-1)*n. to evaluate this expression, fact() is called with n-1. This process repeats until n equals 1 and the calls to the method begin returning.

To better understand how the fact() method works, let’s go through a short example. When you compute the factorial of 3, the first call to fact() will cause a second call to be made with an argument of 2. This invocation will cause fact() to be called a third time with an argument of 2. This call will return 1, which is then be called a third time with an argument of 1. This call will return 1, which is then multiplied by 2 (the value of n in the second invocation). This result (which is 2) is then returned to the original invocation of fact() and multiply by 3 ( the original value of n). This yields the answer, 6. You might find it interesting to insert println() statements into fact() which will show at what level each call is and what the intermediate answers are.

When a method calls itself, new local variables and parameters are allocated storage on the stack, and the method code is executed with these new variables from the start. A recursive call does not make a new copy of the method. Only the arguments are new. As each recursive call returns, the old local variables and parameters are removed from the stack, and execution resumes at the point of the call inside the method.

Next we will learn how to deal with Array in Java.

Checkout more useful tutorials and definitive guidelines on Java programming here.