• Skip to main content
  • Skip to primary sidebar
  • Skip to secondary sidebar
  • Skip to footer

Computer Notes

Library
    • Computer Fundamental
    • Computer Memory
    • DBMS Tutorial
    • Operating System
    • Computer Networking
    • C Programming
    • C++ Programming
    • Java Programming
    • C# Programming
    • SQL Tutorial
    • Management Tutorial
    • Computer Graphics
    • Compiler Design
    • Style Sheet
    • JavaScript Tutorial
    • Html Tutorial
    • Wordpress Tutorial
    • Python Tutorial
    • PHP Tutorial
    • JSP Tutorial
    • AngularJS Tutorial
    • Data Structures
    • E Commerce Tutorial
    • Visual Basic
    • Structs2 Tutorial
    • Digital Electronics
    • Internet Terms
    • Servlet Tutorial
    • Software Engineering
    • Interviews Questions
    • Basic Terms
    • Troubleshooting
Menu

Header Right

Home » Java » Java

String toLowerCase() in Java Example

By Dinesh Thakur

String toLowercase (): This method converts all of the characters in the string to lowercase.

For example,

str1.toLowercase(); //returns hello dinesh thakur

public class StringtoLowerCase 
{
     public static void main(String[] args)
     {
            String strl = "HELLO DINESH THAKUR";
             System.out.println("str1.toLowerCase() = " + strl.toLowerCase());
      }
}

String toLowerCase() in Java Example

String toUpperCase() in Java Example

By Dinesh Thakur

String toUppercase ():This method converts all of the characters in the invoking string to uppercase. For example,

str1.toUppercase(); //returns HELLO JAVA

public class StringtoUpperCase 
{
     public static void main(String[] args)
     {
            String strl = "hello java";
             System.out.println("strl.toUpperCase() = " + strl. toUpperCase());
      }
}

String toUpperCase() in Java Example

String Compare Methods in Java

By Dinesh Thakur

The String class also provides a number of methods for comparing strings. While discussing these, we assume string sl contains ‘Welcome’ in it.

boolean equals (String str): This method checks whether the contents of the String object referenced by str is equal to the contents of String object through which this methodis invoked. It returns true if the strings are equal and false otherwise. For example:

sl.equals(“Welcome”) // returns true

sl.equals(s2) // returns false

 

boolean equalslgnoreCase (String str) : It is same as above except it ignores the case of the characters in the string (i.e treats uppercase and lowercase characters to be equivalent). For example,

sl.equalslgnoreCase(“welcome”) // returns true

sl.equalslgnoreCase(s2) // returns true

int compareTo (String str) : This method compares the contents of String object referenced by str with the contents of invoking string by comparing the successive corresponding characters, starting with the first character in each string. The process continues until either the corresponding characters are found to be different or the last character in one or both strings is reached. Characters are compared lexicographically (i.e. according to their unicode representation). This method returns

if the two strings are equal i.e. they contain the same number of characters and corresponding characters are identical.

a value greater than 0 if the invoking string has a character greater than the corresponding character in the String object referenced by str.

a value less than 0 if the invoking string has a character less than the corresponding character in the String object referenced by str. For example:

sl.compareTo(“Welcome”) // returns 0

sl.compareTo(s2) // returns -32

s2.compareTo{sl) // returns 32

NOTE: A syntax error will occur if you compare strings using comparison operators >, >=, <=, < .

• int compareTolgnoreCase (String str) : This method is same as compareTo () method except that it ignores the case of string characters. For example: sl. compareTolgnoreCase (s2) returns 0.

• boolean startsWi th (Sting str) : This method determines whether the invoking string starts with the specified string str. If so, the method returns true otherwise returns false. For example,

sl.startsWith(“We”) //returns true

sl.startsWith(“Well”) //returns false

• boolean startsWith(string str, int startlndex): It is similar to the previous method but it tests whether the invoking string starts with the specified string str beginning at a specified index, startlndex. For example,

sl.startsWith(“We”,2) // returns false

boolean endsWith (String str) : This method determines whether the invoking string ends with the specified string str or not. If so the method returns true otherwise returns false. For example:

s3.endswith(“Java”) // returns true

s1. endswith (“come”) // returns false

boolean regionMatches(int startlndex, String str, int strStartlndex, int len) : This method checks whether a region (portion) of the invoking string matches the specified region of the specified String object referenced by str. The parameter startIndex specifies the starting index in the string that invokes the method. The parameter str is the comparison string and the parameter strStartlndex specifies the starting index in the string str. The last parameter len specifies the number of characters to compare between two strings. It returns true if the specified number of characters are lexicographically equivalent. For example,

sl.regionMatches(2,”come”,1,3) // returns true

boolean regionMatches(boolean ignoreCase, int startlndex, String str, int strStartlndex, int len) :It is similar to the above method except that it will ignorecase if the value in the first parameter ignoreCal3e is true. For example,

sl.regionMatches(true,2,”COME”,1,3) // returns true.

Now let us consider a example to shows how these work.

public class StringCompareMethods 
{
           public static void main(String[] args)
      {
            String str = "welcome" ;
            System.out.println("str.equals(\"welcome\") ="+str.equals("Welcome"));
            System.out.println("str.equalsIgnoreCase(\"welcome\") = "+ str.equalsIgnoreCase("welcome"));
            System.out.println("str.compareTo(\"welcome\") = "+ str.compareTo("welcome"));
            System.out.println("str.compareToIgnoreCase(\"welcome\") = "+ str.compareToIgnoreCase("welcome"));
            System.out.println("str.startsWith(\"we\") = "+ str.startsWith("We"));
            System.out.println("str,startsWith(\"We\",2) = "+ str.startsWith("We",2));
            System.out.println(" str.endsWith(\"me\") = "+ str.endsWith("me"));
            System.out.println("str.regionMatches(4,\"COME\",1,3) = " + str.regionMatches(4, "COME",1,3));
            System.out.println("str.regionMatches(true,4,\"come\",1,3) = " + str.regionMatches(true,4,"come",1,3));
      }
}

String Compare Methods in Java

Searching Strings in Java Examples

By Dinesh Thakur

Searching a string for finding the location of either a character or group of characters (substring) is a common task. For example: In some situations, usernames and passwords are stored in a single string in which they are separated from each other by a special character such as colon (Example: username : password). In order to get the username and password separately from such a string, there must be some method such that we can search the string and return the location of the colon character. The String class provides the following methods for performing these tasks,

indexOf();

lastIndexOf ();

int indexOf (int ch) : This method returns the index position of the first occurrence of the character ch in the string. If the specified character ch is not found within the string then -1 is returned. For example:

The statement, sl. indexOf ( ‘e’) will return 1as index starts from 0.

Another version of this method is int indexOf (String str)

It is same as above except that it accepts a string argument. For example,

s3.indexOf(“there”)

will return 6 i.e. the index position of the first occurrence of substring “there” in the string.

int indexOf (int ch, int fromIndex) : This method is same as the preceding method but the only difference is that the search will start from the specified index (i.e. fromIndex)

instead of 0. For example, s1. indexOf ( ‘e’ ,2) will return 6 as searching will start from index 2.

Another version of this method is int indexOf (String str, int fromIndex)

It is same as above except that it accepts a string as the first argument instead of a character.

For example, The statement s3.indexOf (“there”, 8) will return 23.

The lastIndexOf () method also has four versions as that in case of indexOf () method. The four versions of lastIndexOf () method have the same parameters as the four versions of the indexOf ()method. The difference is that this method locates the last occurrence of the character or substring in the string depending upon the argument passed. This method performs the search from the end of the string towards the beginning of the string. If it finds the character or substring, the index is returned otherwise it returns -1. For example, consider the following statements.

sl.lastIndexOf(‘e’) // returns 6

s2.lastIndexOf(‘e’,3) // returns 1

s3.lastIndexOf(“there”) // returns -23

s3.lastIndexOf(“there”,20) // returns 6

s3.lastIndexOf(“Hi”,5) // returns -1

public class SearchingStrings 
{
      public static void main(String[] args)
      {
         String str = "Dinesh Thakur" ;
         System.out.println("str.indexOf('e') = "+ str.indexOf('e'));
         System.out.println("str.indexOf('e,3) = "+str.indexOf('e',3) );
         System.out.println("str.indexOf(\"Thakur\") = " +str.indexOf("Thakur"));
         System.out.println("str.indexOf(\"Thakur\",4) = "+str.indexOf("Thakur",4));
         System.out.println("str.lastindexOf('e') = "+str.lastIndexOf('e'));
         System.out.println("str.lastindexOf('e',3) = "+str.lastIndexOf('e',3));
         System.out.println("str.lastindexOf(\"Thakur\') = "+ str.lastIndexOf("Thakur") );
         System.out.println("str.lastindexOf(\"Thakur\",4) = "+str.lastIndexOf("Thakur",4) );
         }
}

Searching Strings in Java

public class SearchingStrings  
{
            public static void main(String args[])
            {
                        String s = "God is Great";
                        String t = " Beleive in God ";
                        int m,n;
                        System.out.println(s);
                        System.out.println(s.toUpperCase());
                        System.out.println(s.toLowerCase());
                        System.out.println(s+t);
                        t=t.trim();
                        System.out.println(t);
                        s=s.replace('i','I');
                        s=s.replace('s','S');
                        System.out.println(s);
                        m = s.indexOf('I');
                        n = s.indexOf('S');
                        char k[] = s.toCharArray();
                        k[m]='i';
                        k[n]='s';
                        s = new String(k);
                        System.out.println(s);
            }
}

Searching Strings

Getting String Length, Characters and Concat Strings in Java

By Dinesh Thakur

The String class provides methods for obtaining length, retrieving individual characters and concatenating strings. These include

length();

charAt();

concat();

int length (): This method returns the number of characters in a string. For example: The statement,

int k = sl.length();

will store 7 in a variable k i.e. the number of characters in the String object referenced by s1 ( i.e. Welcome).

char charAt (int index) : This method returns the character in the string at the specified index position. The index of the first character is 0, the second character is 1 and that of the last character is one less than the string length. The index argument must be greater than or equal to 0 and less than the length of the string. For example:

sl.charAt(1)

will return character ‘e’ i.e. character at index position 1 in the string referenced by s1.

String concat (String str): This method concatenates the specified string to the end of the string. For example : The statement,

sl.concat(” Everybody”);

will concatenates the strings ‘Welcome’ and ‘ Everybody’.

public class StringMethods 
{
      public static void main(String[] args)
   {
        String s1 = "Welcome";
        System.out.println("s1.length() = "+ s1.length());
        System.out.println("s1.charAt(1) = "+ s1.charAt(1));
        System.out.println("s1.concat(\"Everybody\") = "+s1.concat(" Everyboday"));
    }
}

Getting String Length, Characters and Concat Strings in Java

String Constructors in Java with Example

By Dinesh Thakur

The String object can be created explicitly by using the new keyword and a constructor in the same way as you have created objects in previously. For example The statement
String str = new String(“Welcome to Java”);

Creates a String object initialised to the value of the string literal “Welcome to Java” and assigns a reference to string reference variable str. Here, String (“Welcome to Java”) is actually a constructor of the form String (string literals). When this statement compiled, the Java compiler invokes this constructor and initialises the String object with the string literal enclosed in parentheses which passed as an argument.
You can also create a string from an array of characters. To create a string initialised by an array of characters, use the constructor of the form
String (charArray)
For example, consider the following character array.
char[] charArray ={‘H’,’i’,’ ‘,’D’,’I’,’N’,’E’,’S’,’H’};
If we want to create a String object, str1 initialised to value contained in the character array chrArr, then use the following statement,
String str1 = new String(chrArr);
One should remember that the contents of the character array are copied, subsequent modification of the character array does not affect the newly created string.
In addition to these two constructors, String class also supports the following constructors,
• String (): It constructs a new String object which is initialized to an empty string (” “). For example:
String s = new String();
Will create a string reference variable s that will reference an empty string.
• String (String strObj): It constructs a String object which is initialized to same character sequence as that of the string referenced by strObj. For example, A string reference variable s references a String object which contains a string Welcome On execution of the following statement
String s2 = new String(s);
The string reference variable s2 will refer to a new String object with the same character sequence Welcome in it.

string reference variable
• String (char [] chArr, int startIndex, int count): It constructs a new String object whose contents are the same as the character array, chArr, starting from index startlndex upto a maximum of count characters. For example: Consider the following statements
char[] str = {‘W’,’e’,’l’,’c’,’o’,’m’,’e’};
String s3 = new String(str,5,2);
On execution, the string reference variable s3 will refer to a string object containing a character sequence me in it.
• String (byte [] bytes): It constructs a new String object by converting the bytes array into characters using the default charset. For example, consider the following statements,
byte[] ascii ={65,66,67,68,70,71,73};
String s4 = new string (ASCII);
On execution, the string reference variable s4 will refer to a String object containing the character equivalent to the one in the bytes array.
• String (byte [] bytes, int startIndex, int count): It constructs a new String object by converting the bytes array starting from index startIndex upto a maximum of count bytes into characters using the default charset. For example: On executing the statement,
String s5 = new String(ascii,2,3);
The string reference variable s5 will refer to a String object containing character sequence CDE.
• String (byte [] bytes, String charsetName): It constructs a new String object by converting bytes array into characters using the specified charset.
• String(byte[] bytes, int startIndex, int count, String charsetName): It constructs a new String object by converting the bytes array starting from index startIndex upto a maximum of count bytes into characters using the specified charset.
• String (StringBuffer buffer): It constructs a new String object from a StringBuffer object.
Now let us consider an example to explain how these constructors are used.

public class StringConstructors 
{
       public static void main(String[] args)
    {
          char[] charArray ={'H','i',' ','D','I','N','E','S','H'};
          byte[] ascii ={65,66,67,68,70,71,73};
          String str  = "Welcome";
          String strl =new String("Java");
          String str2 =new String(charArray);
          String str3 =new String(charArray,3,3);
          String str4 =new String(ascii);
          String str5 =new String(ascii,2,3);
          String str6 =new String();
          String str7 =new String(str);
          System.out.println("str : "+ str);
          System.out.println("strl : "+ strl);
          System.out.println("str2 : "+ str2);
          System.out.println("str3 : "+ str3);
          System.out.println("str4 : "+ str4);
          System.out.println("str5 : "+ str5);
          System.out.println("str6 : "+ str6);
          System.out.println("str7 : "+ str7);
          str += " Dinesh Thakur";
          System.out.println("str : "+ str);
    }
}

String Constructors in Java

Passing Two Dimensional Array to a Method in Java

By Dinesh Thakur

Just like one-dimensional arrays, a two-dimensional array can also be passed to a method and it can also be returned from the method. The syntax is similar to one-dimensional arrays with an exception that an additional pair of square brackets is used.

Now let us consider a program to find the transpose of a matrix.

public class Transpose 
{
      public static void main(String[] args)
      {
            int[] [] table= {{5,6,7},{3,4,2}};
            int[] [] result;
            System.out.println("Matrix Before Transpose : ");
            for(int i=0;i<table.length;i++)
                {
                    for(int j=0;j<table[i].length;j++)
                    System.out.print(table[i][j]+" ");
                 }
                    result=transpose(table);
                    System.out.println("\nMatrix After Transpose :");
             for(int i=0;i<result.length;i++)
                 {
                    for(int j=0;j<result[i].length;j++)
                         System.out.print(result[i][j]+" ");
                         System.out.println();
                 }
         }
                 static int[][] transpose(int[][] a)
             {
        
                   int[][] temp=new int[a[0].length][a.length];
                   for(int i=0;i<a[0].length;i++)
                       {
                          for(int j=0;j<a.length;j++)
                               temp[i][j]= a[j][i];
                       }
                               return temp;
              }
}

Passing Two Dimensional Array to a Method in Java

Arrays Of Arrays with Varying Length in Java

By Dinesh Thakur

when we created arrays of arrays (i.e. two-dimensional array), the arrays in the array were of same length i.e. each row had the same number of elements. As each array in a multidimensional array is a separate array so it can have different number of elements. Such arrays are known as non-rectangular arrays or ragged arrays.

In order to create a two-dimensional ragged array, you have to first declare and instantiate the array by specifying only the number of elements in the first dimension and leaving the second dimension empty. For example: Consider the statement,

int [] [] table = new int [3] [];

This statement declares an array object table of type int [] [] which references an array of 3 elements, each of which holds a reference to a one-dimensional array. With this statement, although three one-dimensional arrays have been declared but the number of elements in each one dimensional array is still undefined. So you can define these arrays individually as follows,

tab1e[0] = new int[l];

table [1] = new int[2];

table [2] = new int[3];

These statements define three possible one-dimensional arrays that can be referenced through the elements of table array. The first element (table [0]) now references an array of one element of type int. The second element (table [1]) now references an array of two elements of type int. The third element (table [2]) now references an array of three elements of type int.

                       Non-Rectangular array table

Like you can initialize arrays of arrays, similarly, the ragged arrays can also be initialized. For example : The statement,

int table [] [] = { {l},{2,2},{3,3,3}};

creates an int-type two dimensional array table containing three array elements. The first element is reference to a one-dimensional array of length one, the second element is reference to one-dimensional array of length two and the third elements is a reference to one-dimensional array of length three.

                      

You can access the elements of the ragged array just as before with the index pair but now the range of the index for each subarray is different.

Now let us consider a program to find the minimum and maximum in a ragged array

//program that find maximum and minimum in ragged array 
public class MaxMin
{
         public static void main(String [] args)
        {
           int[] [] table= { {15,10} ,{5,12,34},{3,32,17,44}};
           int i, j,max,min;
           max = min = table [0] [0];
           for(i=0;i<table.length;i++)
               {
                   for(j=0;j<table[i].length;j++)
                       {
                          if(table[i] [j]>max);
                            max = table[i] [j];
                          if(table[i] [j]<min)
                             min = table[i] [j];
                       }
                }
                        System.out.println("Maximum Element is : "+max);
                        System.out.println("Minimum Element is  : "+min);
          }
}

Variable length (Dynamic) Arrays in Java

Initialization of Two Dimensional Arrays Java

By Dinesh Thakur

Like one dimensional array, one can also initialize multidimensional array when they are declared. For example: A two-dimensional array table with 2 rows and 3 columns can be declared and initialized as follows,

int table[] [] = {{1,2,3},{3,4,5}};

Note that each array row is initialized separately by enclosing them within its own set of curly braces. Moreover, there must be a comma at the end of each row except for the last one. Within each row, the first value will be stored in the first position of the sub array, the second value will be stored in the second position and so on.

Now let us consider a program to calculate sum of elements of each row in two dimensional array.

public class SumRC
{
      public static void main(String [] args)
    {
           int[] [] num = {{7,6,5},{4,5,3}};
           int i,j,sumRow,sumCol;
           for( i=0; i<num.length; i++)
               {
                   sumRow = 0;
                   for (j=0; j<num[i].length;j++)
                        {
                               sumRow += num[i][j];
                               System.out.print( num[i] [j] + "  ");
                        }
                               System.out.println("---  " + sumRow);
          
                }
                  System.out.println("-------------------------- ");
                  for(i=0; i<num[0].length; i++)
                      {
                          sumCol = 0;
                          for( j=0; j<num.length; j++)
                              sumCol += num[j] [i];
                              System.out.print(sumCol + "  ");
                      }
      }
}

Initialization of Two Dimensional Arrays Java

Multidimensional Array in Java Example

By Dinesh Thakur

Multi-dimensional arrays that contain more than one index and can store information in multiple dimensions.  The most common one is a two-dimensional array, also called a matrix or table. In the two-dimensional array, each element associated with two indexes.  We can visualize the two-dimensional array as a spreadsheet, rectangular in shaper and containing elements that divided into columns and rows. However, Java does not indeed support multidimensional arrays. However, one can achieve the same functionality by declaring an array of arrays.

In order to understand arrays of arrays, consider an example where we want to calculate the marks obtained by 4 students of a class in 3 different subjects. An obvious way to store information is in a two-dimensional array (or matrix) which we call marks. In order to create this two dimensional array marks, we are set up much like the arrays we looked at previously but with one difference – two sets of the square brackets. The first set is for the rows and the second set is for the columns. In the code line right above the code, we informed Java that we need an array with 4 rows and 3 columns. Storing values in a multi-dimensional array require care that each row and each column is tracked. 

The two-dimensional array marks of int type can be declared as follows,

int [][] marks;

The above declaration can also be written as,

int[] marks[];

int marks [][] ;

Each of the pairs of square brackets represent one dimension. This statement creates a variable marks that will refer to a two- dimensional int array.

Once you have declared an array variable, you can create an array that it will reference using the following statement,

marks = new int [4][3] ;

On execution of this statement, the JVM creates an array with 4 elements and stores a reference to this array in the variable marks. Each of these four elements is actually a reference variable referring to a (newly created) int array with 3 elements. In the two-dimensional array marks, the first index corresponds to a student and second index corresponds to a subject.

                   Multidimensional Array in Java Example

You can combine the declaration and instantiation of the above array in a single statement as follows,

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

Once this two-dimensional array has been created, an individual element is accessed by indexing the array. Separate index must be provided for each dimension, each of which begins at 0. So in order access marks obtained by 2nd student in 3rd subject can be written as

marks[1][2] // remember arrays are 0 based

As we can calculate the length of one dimensional array using the length field. Similarly, in multidimensional arrays, we can calculate the length of each dimension.  In our example, the length of the first dimension can be calculated by using the following,

marks.length

The length of the second dimension can be calculated using marks[i].length where i ranges from 0<=i<=3.

Accessing all of the items from any multi-dimensional array requires the use of a  loop within a loop. Look at the code below where we use a double-loop to access  all our numbers: 

The complete program is as follows,

import java.util.Scanner; 
public class twoDArray
{
     public static void main(String[] args)
     {
            int[] [] a = new int[3] [2];
            int i, j;
            Scanner input=new Scanner(System.in);
            System.out.print("Enter the Elements of 3 * 2 Matrix :");
            for(i=0;i<3; i++)
                {
                   for(j=0; j<2;j++)
                   a[i] [j]=input.nextInt();
                }
            System.out.println("Elements in Matrix from are :");
            for(i=0;i<3;i++)
                { 
                   for(j=0; j<2; j++)
                       System.out.print(a[i][j]+" ");
                       System.out.println();
                }
       }
}

Multidimensional Array in Java

The initial for loop is used for the rows and the second one is used for the columns. With the first loop, 0 is the value of the i variable. In the for loop, the code is another loop, and the entire double loop is executed for as long as the i variable value stays as 0. The second loop has another variable, named j and both variables, i and j, are used to access the array: 

a[i][j].
We use the double loop system for looping through multi-dimensional array values, one row at a time.

Creating a Two-Dimensional Array

We can do these in three separate ways:   

Using Just an Initializer  

To use just an initializer to create the two-dimensional array, we use the following  
syntax: 

‘{‘[rowinit (‘,’ rowinit)*]’}’  
rowinit has the following syntax:  
‘{‘[expression (‘,’ expression)*]’}’  
With this syntax, we are saying that a two-dimensional array is optional, and it is a  list containing row initializers, each separated by a comma, and all in between a set of curly braces. Each of the row initializers is also an optional list, this time expressions, again with the comma separation and in between a pair of curly braces.   Similar to the one-dimensional array, the expressions all have to evaluate types that are compatible.  
Have a look at this example:  
{{21.5, 31.6, 29.3}, {-39.7, -19.3, -17.2 }}   

Using Just the New Keyword 

When we use the new keyword, it allocates the memory for the array and returns the array reference. It is the syntax:  
‘new’ type ‘[‘ int_expression1 ‘]’ ‘[‘int_expression2 ‘]’  
We are saying that the two-dimensional array is a region of int_expr1, which are positive, row elements and int_expr2, also positive, column elements, all with the same data type. Not only that, every element has been zeroed.  
Have a look at this example:  
new double[2][3] // Create a two row by three column table.  
Using Both Initializer and the New Keyword  
Using both has a syntax approach of:  
‘new’ type ‘[‘ ‘]’ [‘ ‘]’ ‘{‘[rowInit (‘,’ rowInit)*]’}’  
rowInit has a syntax of:  
‘{‘[expression (‘,’ expression)*]’}’  
It is a combination of the syntax from the previous examples; note that there is no int_expr in between either the sets of square brackets because we can already work out how many elements are in the array just by looking at expressions list.  
Have a look at this example:  
new double [][] {{ 21.5, 31.6, 29.3}, {-39.7, -19.3, -17.2}} 

Returning an Array from a Method in Java

By Dinesh Thakur

Just like a method can return a primitive type, similarly a method can also return an array. If a method returns an array then its return type is an array. This is really useful when a method computes a sequence of values.

In order to understand how an array is returned from a method, consider a program that returns an array which is the reverse of another array.

public class ReturningArray 
{
      public static void main(String[] args)
      { 
         int[] num= {5,15,25,30,50};
         System.out.println("Elements in Original Array :");
         for(int i=0;i<num.length;i++)
              System.out.print(num[i]+" ");
          int[] result=reverse(num);
          System.out.println("\nElements in New Array :");
          for(int i=0;i<result.length;i++)
               System.out.print(result[i]+" ");
       }
       static int[] reverse(int[] orgArray)
       {
         
          int[] temp=new int[orgArray.length];
          int j=0;
           for(int i=orgArray.length-1;i>=0;i--,j++)
                temp[j]=orgArray[i];
           return temp;
       }
}

Returning an Array from a Method

In this program, we first input the elements of the array. In order to reverse the array elements, we make a method reverse () that takes array as argument and returns an array that contains the elements in the reverse order. The statement

int[] result = reverse(num)i

invokes the function reverse () and pass the original array as an argument through its reference variable num which is copied into the orgArray parameter. In the method body, the statement

int[] temp = new int[orgArray.length]i

creates a new array of length same as that of original array and stores its reference in the variable temp. Then using the for loop, the elements are copied from orgArray one by one into new array temp in the reversed order. Once all the elements are copied, the loop terminates. The statement,

return temp;

returns the reference of the new array through its variable temp which is then assigned to the reference variable result. Finally, its contents are displayed.

              Returning an Array Example

Passing Arrays to Methods in Java

By Dinesh Thakur

Just as you can pass primitive type values to methods, you can also pass arrays to a method. To pass an array to a method, specify the name of the array without any square brackets within the method call. Unlike C/C++, in Java every array object knows its own length using its length field, therefore while passing array’s object reference into a method, we do not need to pass the array length as an additional argument. For example: Suppose we have an integer array num containing 10 elements.

int[] num = new int[10];

Then the method call will look like, modify (num);

As array reference is passed to the method so the corresponding parameter in the called method header must be of array type. The method body in our example will be

modify (int [] x) {…………………………}

It indicates that the method modify receives the reference of an integer array (in our case num) in parameter x when it is being called. So if parameter x is being used in its body then actually it is referencing an array object num in the calling method.

Recall that when you pass a variable of primitive type as an argument to a method, the method actually gets a copy of value stored in the variable. So when an individual array element of primitive type is passed, the matching parameter receives a copy. However, when an array is passed as an argument, you just pass the array’s reference in matching parameter and not the copy of individual elements. Any modification made in the array using its reference will be visible to the caller.

class sortNumbers 
{
     public static void main(String[] args)
     {
           int[] data={40,50,10,30,20,5};
           System.out.println("Unsorted List is :");
           display(data);
           sort(data);
           System.out.println("\nSorted List is :");
           display(data);
     }
     static void display(int num[])
     {
        for(int i=0; i<num.length;i++)
            System.out.print(num[i] + " ");
     }
     static void sort(int num[])
     {
       int i, j, temp;
       for(i=0; i<num.length-i;i++)
           { 
               for(j=0; j<num.length-i-1;j++)
                   {
                        if(num[j]>num[j+1])
                          {
                               temp = num[j];
                               num[j] = num[j+1];
                               num[j+1] = temp;
                          }
                   }
           }
     }
}

Passing Arrays to Methods in Java

In this example, we sort the numbers by using the concept of passing arrays to methods. The unsorted array is passed to the sort () method. In the method’s definition, the array referenced using num reference variable is sorted and the changes made are reflected back.

Passing Arrays to Methods in Java

Enhanced For Loop in Java with Example

By Dinesh Thakur

With the release of version 1.5, Java introduced a new type of for loop known as enhanced or numerical for loop. It is designed to simplify loops that process elements of array or collection. It is useful when you want to access all the elements of an array but if you want to process only part of the array or modify the values in the array then use the simple for loop.

When used with an array, the enhanced for loop has the following syntax,

for (type itr_var : arrayName)

{ statement(s) }

where type identifies the type of elements in the array and itr_var provides a name for the iteration variable that is used to access each element of the array, one at a time from beginning to end. This variable will be available within the for block and its value will be the same as the current array element. The arrayName is the array through which to iterate. For example:

for (int i : num)

System.out.println(i);

This enhanced for loop header specifies that for each iteration, assign the next element of

the array to int type variable i and then execute the statement. During the first loop iteration, the value contained in num[0] is assigned to i which is then displayed using the println () method. After completion of the first iteration, in the next iteration, the value contained in num[1] is assigned to i which is then displayed using println ()method. This process continues until the last element of the array is processed.

public class EnhancedForLoop 
{
       public static void main(String[] args)
       {
          int[] num = {5,15,25,30,50};
          System.out.println("Display Elements Using Numeric for Loop : ");
              for(int i=0;i<num.length;i++)
                   System.out.print(num[i]+" ");
         System.out.println("\nDispay Elemnts Using Enhanced for Loop : ");
              for(int i : num)
                   System.out.print(i +" ");
       }
}

Enhanced For Loop in Java with Example

Reusing Array Variables in Java Examples

By Dinesh Thakur

Just like simple variables can store different values at different times, an array variable can also be used to store a reference to different arrays at different times. Suppose you have created and initialized array variable num using the following statement,

int[] num = {5,15,25,30,50};

Suppose later on you want to use the array variable num to refer to another array containing 6 elements of int type then you can do this by simply writing the statement,

num = new int[]{10,20,30,40,50,60};

On execution of this statement, the previous array of 5 in t-type elements that is referenced by num is discarded and array variable num now references a new array of 6 values of type int.

Reusing Array Variables in Java Examples

public class ReusingArrayVariables  
{
          public static void main(String[] args)
      {
            int[] num= {5,15,25,30,50};
            System.out.println("Elements in Original Array : ");
            for(int i=0;i<num.length;i++)
                 System.out.print(num[i]+" ");
                 System.out.println("\nElements in New Array : ");
                 num=new int[]{10,20,30,40,50,60};
            for(int i=0;i<num.length;i++)
                 System.out.print(num[i]+" ");
      }
}

Reusing Array Variables in Java

Getting Length of an Array in Java

By Dinesh Thakur

After you create an array, you can access its length i.e. number of elements it holds. You can refer to the length of an array using its length field (which is implicitly public and final).A length field is associated with each array that has been instantiated. Because length field is a public member so it can be directly accessed using the array name and a dot operator. Its syntax is

arrayRefVar.length
The length data field can be accessed using the dot operator. For example: To access the number of elements in an array named num, use the following syntax,
num.length
You can use the length field of an array to control a numerical for loop that iterates over the elements of an array.

for(int i=0; i<num.length; i++)
System.out.println(“Element num[” + i + “] = ” + num[i]);

Now let us consider the following Example to explain it.

class Average 
{
      public static void main (String[] args)
      {
         int [] num={10,20,30,40,50};
         int sum= 0;
         for(int i=0; i<num.length;i++)
             {
                    sum += num[i];
             }
                    double avg = (double)sum/num.length;
                    System.out.println("Average : " +avg);
      }
}

Getting Length of an Array in Java

In this Example, we calculates the average of 5 numbers. The array containing 5 numbers can be referenced using num_array variable. Here, we use num.length to get the length of the array referenced by num.
To calculate the average, we first add all the numbers in the array and then divide by the total numbers of elements. The result is then displayed

Initializing Array in Java Examples

By Dinesh Thakur

When an array is created, each element of the array is set to default initial value according to its type. However, it is also possible to provide value other than the default values to each element of the array.

This is made possible using array initialization. Arrays can be initialized by providing values using a comma separated list within curly braces following their declaration. The syntax for array initialization is

datatype[] arrayName = {value1, value2,………………. };

For example : The statement

int[] num = {5,15,25,30,50};

creates a five element array with index values 0,1,2,3,4. The element num [0] is initialized to 5, num [1] is initialized to 15 and so on.

Note that we do not use the new keyword and do not specify the size of the array also. This is because when the compiler encounters such a statement it counts the number of element in the list to determine the size of the array and performs the task performed by the new operator. Initializing array is useful if you know the exact number and values of elements in an array at compile time.

The above initialization statement is equivalent to

int[] num = new int[5];

num [0] =  5 ;

num [1] = 15;

num [2] = 25;

num [3] = 30;

num [4] = 40;

Similarly, you can initialize an array by providing objects in the list. For example

Rectangle[] rect = {new Rectangle(2,3),new Rectangle()};

It will create rect array of Rectangle objects containing 2 elements.

There is a variation of array initialization in which we use the new keyword explicitly but omit the array length as it is determined from the initializer list. For example:

int[] num = new int[]{5,15,25,30,50};

This form of initialization is useful if you need to declare an array in one location but populate it in another while still taking the advantage of array initialization. For example:

displayData(new String[]{“apple”,”orange”,”litchi”});

An unnamed array created in such a way is called anonymous arrays.

public class InitializingArray 
{
          public static void main(String[] args)
     {
           int[] num = new int[]{5,15,25,30,500};
           for(int i=0;i<num.length;i++)
                 System.out.println("num ["+i+"] : " +num[i]);
          display(new String[] {"apple","orange","1itchi"});
     }
          static void display(String[] str)
     {
          for(int i=0;i<str.length;i++)
                  System.out.println("str ["+i+"] :" +str[i]);
     }
}

Initializing Array in Java

Accessing Array Elements in Java with Example

By Dinesh Thakur

Once the array is created, you can access an array element by using the name of the array followed by an index enclosed between a pair of square brackets. The index or subscript of an array indicates the position of an element in the array. The index of the first element in the array is always 0 (zero), the second element has an index 1 and so on. The index of the last element is always one less than the number of elements in the array. The syntax for accessing an array element is

arrayRefVar[index];

Here, index is an integer literal or an expression that evaluates to an into

In our example, the first element of the array is num[0],the second element is num[1] and the last element is num[4]

public class AccessingArrayElements
{
     public static void main (String [] args)
     {
        int[] num = new int[5];
        num[0] = 5;//Assigning value 5 to element at index 0
        num[1] = 15;
        num[2] = 25;
        num[3] = 30;
        num[4] = 50;
        System.out.println("Array Element num[0] : " + num[0]);
        System.out.println("Array Element num[1] : " + num[1]);
        System.out.println("Array Element num[2] : " + num[2]);
        System.out.println("Array Element num[3] : " + num[3]);
        System.out.println("Array Element num[4] : " + num[4]);
     }
}

Accessing Array Elements in Java

Now let us consider another example that input the elements of an array and prints its contents.

import java.util.Scanner; //program uses Scanner class 
public class ArrayElements
{
      public static void main(String[] args)
      {
         int[] numArray = new int[5];
         int i;
         Scanner input=new Scanner(System.in);
         System.out.print("Enter the 5 Array Elements : ");
         for(i=0; i<5; i++)
              numArray[i]=input.nextInt(); //Read number
         for(i=0; i<numArray.length; i++)
             System.out.println("Array element[" + i + "] : " +numArray[i]);
       }
}

Accessing Array Elements in Java with Example

This example inputs an array and prints its contents.

The statement,

int[] numArray = new int[5];

creates a numArray array variable that references an int-array containing 5 elements. We create a Scanner object to obtain an input from the keyboard. Finally, when all the input has been made it is printed.

Object Reference this in Java

By Dinesh Thakur

Whenever the objects of a class are instantiated, each object will have its own copy of instance variable(s), however all objects share only one copy of each instance method of the class. So the question arises how does a method know for which object the method was called. In other words, how does a method know which instance variable it should get/set or use to calculate a value? This is possible using a special object reference variable named this. When a method starts executing, the JVM sets the object reference this to refer to the object for which the method has been invoked. The compiler uses this implicitly when your method refers to an instance variable of the class. So any instance variable referred to by a method is considered to this. instanceVariable.

class Rectangle 
{
       int length;
       int breadth;
       void setData(int length,int breadth)
       {
         this.length = length;
         this.breadth = breadth;
       }
       int area()
       {
         int rectArea;
         rectArea = length * breadth;
         return rectArea;
       }
}
     class ObjectReferencethis
{
           public static void main(String[] args)
       {
            Rectangle firstRect = new Rectangle();
            Rectangle secondRect = new Rectangle();
            firstRect.setData(5,6);
            System.out.println("Area of First Rectangle : "+ firstRect.area());
            secondRect.setData(10,20);
            System.out.println("Area of Second Rectangle : "+secondRect.area());
       }
}

Object Reference this in Java

Returning Objects from Methods in Java

By Dinesh Thakur

A method can return an object in a similar manner as that of returning a variable of primitive types from methods. When a method returns an object, the return type of the method is the name of the class to which the object belongs and the normal return statement in the method is used to return the object. This can be illustrated in the following program.

//Add two times and display information in proper time format 
class Time
{
       private int hours, mins,secs;
       Time() //Constructor with no parameter
       {
          hours = mins = secs = 0;
       }
       Time(int hh, int m, int ss) //Constructor with 3 parameters
       {
          hours = hh;
          mins = m;
          secs = ss;
       }
       Time add(Time tt2)
       {
           Time Temp = new Time();
           Temp.secs = secs + tt2.secs ; //add seconds
           Temp.mins = mins + tt2.mins;  //add minutes
           Temp.hours = hours + tt2.hours; //add hours
           if(Temp.secs > 59)     //seconds overflow check
             {
                Temp.secs = Temp.secs - 60; //adjustment of minutes
                Temp.hours++; //carry hour
             }
                return Temp;
      
       }
      void display()
      {
         System.out.println(hours + " : "+ mins +" : "+ secs);   
      }
}
   class ReturningObjectsfromMethods
{
      public static void main(String[] args)
      {
        
        Time t1 = new Time(4,58,55);
        Time t2 = new Time(3,20,10);
        Time t3;
        t3 = t1.add(t2);
        System.out.print("Time after addition (hh:min:ss) ---->");
        t3.display();
      }
}

Returning Objects from Methods in Java

 

The above program is used to add two times and display the result in proper time format. We begin by taking a class Time that consists of private data members hours, mins, sees and public methods add () and display (). The objects t1 and t2 are instantiated and their fields are assigned values by invoking the constructor.

The statement,

t3 = t1.add(t2);

invokes the add () method using the object t1 and pass the object t2 as an argument by value. In the add () method, the data members of object t1 can be accessed simply by their name whereas the data members of object t2 can be accessed by its copy t t2 using a dot operator. A local object temp is instantiated that stores the result of addition of two given time.

The object temp is finally returned to object t3 in main () using the return statement. The result is displayed using the statement,

t3.display ();

Pass by Value and Pass by Reference in Java Example

By Dinesh Thakur

In most of the programming languages (like C language), there are two ways of passing arguments to a method : Pass by Value and Pass by Reference.

When an argument is passed by value, the copy of the argument’s value is made and it is this copy that is passed to the method and referenced through the parameter name. As new copy is created, so any changes made to this copy does not affect the actual argument.

When an argument is passed by reference, the called method receives a reference to the original variable. Any changes made to the reference variable in the called method are automatically reflected back.

Unlike most of the programming languages, in Java, arguments are always passed to the method using a mechanism known as pass by value. A method call can pass two types of values to a method using the pass by value mechanism.

  1. Value of primitive type
  2. Value of reference type

Pass By Value: Primitive Type

When a variable of primitive type(s) is passed by value, a copy is made which is passed to the parameter. Any modifications made to the primitive-type parameter(s) in the method body have no effect on the original argument in the calling method. Now let us consider the following example.

//Program to Show Passing Primitive Type as Pass By Value
class PrimitiveType
{
       public static void increase(int n)
        {
          n += 1000;
          System.out.println("Increasd Number : n " + n);  
        }
        public static void main(String[] args)
        {
          int num = 10;
          System.out.println("Before Increment : num : " +num);
          increase(num);
          System.out.println("After Increment : num : " +num);
        }
}

Pass By Value: Primitive Type

In this example, the number entered by user is incremented by 1000. The method call, increase(num); passes a variable num of primitive type int to a method increase ().The parameter n receives a copy of the value stored in num. On increasing the value of n by 1000, this modification is not reflected back to the original variable num. So the original value of num remains unchanged.

Pass by Value: Reference Type

When you pass an object reference variable as an argument to a method, a copy of a reference to the original object is passed to the matching parameter of the method, not a copy of the object itself. Since, the reference stored in the parameter is a copy of the reference that was passed as an argument, so the parameter and argument refer to the same object in memory. Any modification made to the instance variable(s) of an object within the called method will be reflected back to the original object in the calling method as well. Now let us consider the following example.

//program to show passing object as pass by value 
class Test
{
      int num;
      Test()
      {
        num= 10;
      }
      public void increase(Test objRef)
      {
          objRef.num += 1000;
      }
}
class ReferenceType
{
        public static void main(String[] args)
        {
            Test obj = new Test();
            System.out.println("Before Increment : num : " + obj.num);
            obj.increase(obj);
            System.out.println("After Increment : num : " + obj.num);
        }
}

Pass by Value: Reference Type

When the reference variable obj of class type Test is passed as an argument to the method increase (), a copy of contents of obj is made and stored in parameter objRef. Both obj and obj Ref refer to the same object. When the m.un instance variable of object pointed by obj Ref reference variable is incremented by 1000 then this change is also visible to the original object obj .

Access Specifiers in Java with Example

By Dinesh Thakur

In Java, we have three access Specifiers: public, private and protected that can be used with the class members. If no access specifier is used, Java assigns a default package access to the members. Members with default access are accessible from methods in any class in the same package. [Read more…] about Access Specifiers in Java with Example

Copy Constructor in Java Example

By Dinesh Thakur

Copy Constructor: Sometimes a programmer wants to create an exact but separate copy of an existing object so that subsequent changes to the copy should not alter the original or vice versa. This is made possible using the copy constructor. It takes the object of the class as a reference to the parameters. This means that whenever we initialize an instance using value of another instance of same type, a copy constructor is used.

A copy constructor is a constructor that creates a new object using an existing object of the same class and initializes each instance variable of newly created object with corresponding instance variables of the existing object passed as argument. This constructor takes a single argument whose type is that of the class containing the constructor.

class Rectangle 
{
        int length;
        int breadth;
        //constructor to initialize length and bredth of rectang of rectangle
        Rectangle(int l, int b)
        { 
           length = l;
           breadth= b;
        }
        //copy constructor
        Rectangle(Rectangle obj)
        {
          System.out.println("Copy Constructor Invoked");
          length = obj.length;
          breadth= obj.breadth;
        }
       //method to calcuate area of rectangle
       int area()
       {
          return (length * breadth);
       }
}
       //class to create Rectangle object and calculate area
       class CopyConstructor
{
          public static void main(String[] args)
          {
            Rectangle firstRect = new Rectangle(5,6);
            Rectangle secondRect= new Rectangle(firstRect);
            System.out.println("Area  of First Rectangle : "+ firstRect.area());
            System .out.println("Area of First Second Rectangle : "+ secondRect.area());
          }
}

Copy Constructor in Java Example

The statement,

Rectangle firstRect = new  Rectangle(5,6);

creates a Rectangle object and invokes the constructor Rectangle (int l,int b) which initializes values length and breadth with values 5 and 6 respectively and returns the reference to firstRect variable.

The statement,

Rectangle secondRect = new Rectangle (firstRect);

invokes a copy constructor

Rectangle(Rectangle obj)

and initializes the instance variables length and breadth of the newly created Rectangle object and returns its reference to the secondRect variable.

One may think, as in C++ the copy constructor can be invoked using the statement,

Rectangle secondRect = firstRect;

but this is not so. Here the variable secondRect references to the same object as firstRect. No new object is created.

how copy constructor creates a copy

Calling Constructor from Constructor Java

By Dinesh Thakur

A constructor can call another constructor from the same class. This is usually done when a constructor duplicates some of the behavior of an existing constructor. In order to refer to another constructor in the same class, use this as the method name, followed by appropriate arguments enclosed in pair of parentheses, if necessary. Java requires that the call to this () can be used in a constructor and must be the first statement in the constructor followed by any other relevant code.

class Circle 
{
    int x,y; //x,y coordinates of circle
    int radius; //radius of circle
    Circle()
         {
            radius=1;
         }
         Circle(int xl, int yl)
         {
           this();
           x = xl;
           y = yl;
         }
         Circle(int xl, int yl,int r)
         {
           this(xl,yl);
           radius = r;
         }
         void area()
         {
         System.out.println("Area of Circle is  : "+(Math.PI * radius * radius));
         }
}
     
      class CallingConstructor
{
        public static void main(String[] args)
        {
             Circle cl = new Circle(); //call no arg constructor
             cl.area();
             Circle c2 = new Circle(2,3); // calls two arg constructor
             c2.area();
             Circle c3 = new Circle (2,3,4); //calls three arg constructor
             c3.area ();
        }
}

Calling Constructor from Constructor Java

The class Circle contains three constructors : no parameter constructor, two parameter constructor and three-parameter constructor.
The statement,
Circle cl = new Circle();
calls a zero parameter constructor. Here radius is initialized to Iand the coordinates x and y will be set a default value 0 .
The statement,
Circle c2 = new Circle(2,3);
calls a two parameter constructor. The statement this () ; on execution causes the zero-parameter constructor to be executed, as a result of which radius field is set to 1. After this, the other statement; in its body are executed which sets x and y fields with the values specified by the user.
The statement,
Circle c3 = new Circle(2,3,4);
calls a three parameter constructor. The statement this (xl ,yl) ; on execution causes the two parameter constructor to be executed and control shifts there. The statement this () ; in its body further calls a zero parameter constructor which initializes radius to 1 and sets x and y with default values (0 each). These values of x and yare overwritten in the body of the two-parameter constructor which are now set to xl (=2) and yl(=3). When the control shifts back to the next statement in the body of three parameter constructor, the value of radius is overwritten and radius is initialized to 4.

Constructor Overloading in Java with Example

By Dinesh Thakur

We saw that a class had only one constructor with either zero, one or more parameters. The constructor is key for object initialization. The mechanism of constructor is made considerable more powerful by combining with the feature of overloading. Constructor can be overloaded in exactly the same way as you can overload methods.

Constructor Overloading allows a class to have more than one constructor that have same name as that of the class but differs only in terms of number of parameters or parameter’s datatype or both. By overloading a constructor for a class, we make the class more versatile as it allows you to construct objects in a variety of ways. In order to understand the concept of constructor overloading, let us consider the following example.

class Rectangle 
{
      int length ;
      int breadth ;
        Rectangle()
        {
           System.out.println("Constructor with Zero Parameter Called ");
           length = breadth = 0 ;
         }
         Rectangle(int side)
         {
            System.out.println("Constructor with One Parameter Called");
            length = breadth = side ;
         }
         Rectangle(int l,int b)
         {
            System.out.println("Constructor with Two Parameters Called");
            length = l ;
            breadth = b ;
         }
         int area()
         {
           return (length * breadth) ;
         }
}
       class ConstructorOverloading
{
               public static void main(String[] args)
          {
                Rectangle r1 = new Rectangle(); //const. with 0-parameter called
                Rectangle r2 = new Rectangle(5); //const with l parameter called
                Rectangle r3 = new Rectangle(7,8); //const.with2 parameter called
                System.out.println("Area of First Rectangle is : "+ r1.area( ));
                System.out. println("Area of Square is : "+ r2.area( ));
                System.out.println("Area of Second Rectangle is : "+ r3.area( ));
          }
}

Constructor Overloading in Java with Example

In this example, the class Rectangle contains three constructors with the same name Rectangle which differs only in the number of parameters and hence overloaded.

The first constructor () doesn’t take any parameter and initialize both data members to 0. The second constructor Rectangle (int a) takes a parameter a of int type and initialize both the data members length and breadth with a value of a. The third constructor Rectangle (int a, int b) takes two parameters a and b of int types which are used for initializing the data members length and breadth respectively.

Now we have defined three constructors associated with the class Rectangle. Which of these constructors will be executed when an object of rectangle class is created depends upon the number of arguments specified in the creation of an object.

On execution of the first statement Rectangle rl= new Rectangle () ; in main () , an object rl of type Rectangle is created and constructor with no parameter is called as no arguments are specified after rl object definition. It initializes both of its data members to a value 0 and displays the message Constructor with zero parameter called.

The statement Rectangle r2 == new Rectangle (5) ; creates an object r2 of type Rectangle and invokes a constructor with one parameter. As only one argument is specified after r2 object definition. Both the data members length and breadth of object r2 are initialized with the value 5 passed to single parameter constructor. It also displays the message Constructor with one parameter called on the console indicating the type of constructor being called.

The statement, Rectangle r3 =: new Rectangle (7 ,8) ; creates an object r3 of type Rectangle and invokes a constructor with two parameters. As two arguments are specified after r3 object definition. This constructor initialize the data members length and breadth with values of parameters a and b (i.e. 7 and 8) respectively. It also displays the message Constructor with two parameters called on the console indicating the type of constructor being called. Finally, these values are used to calculate the area of three rectangles represented by objects r1, r2 and r3.

Parameterized Constructor in Java Example

By Dinesh Thakur

Unlike default constructor which do not have any parameters, it is however possible to have one or more parameters in a constructor. This type of constructor which have parameters is known as parameterized constructor. Using parameterized constructor, it is possible to initialize objects with different set of values at the time of their creation. These different set of values initialized to objects must be passed as arguments when constructor is invoked. The parameter list can be specified in the parentheses in the same way as parameter list is specified in the method. [Read more…] about Parameterized Constructor in Java Example

Default Constructor in Java with Example

By Dinesh Thakur

If you omit implementation of a constructor within your class, a constructor added by the Java compiler, each class must have a constructor and the one used is called the default constructor. You won’t see it listed anywhere in your Java code as the compiler adds at compilation time into the .class file. Should you implement a constructor in your code, the compiler not add the default one. It does not contain any parameters nor does it contain any statements in its body. Its only purpose is to enable you to create an object of class type. The default constructor looks like

public Rectangle(){ }

When the compiler creates a default constructor; it does nothing. The objects created by the default constructor will have fields with their default values. It should be remembered that constructors are invoked only after the instance variables of a newly created object of the class have been assigned their default initial values and after their explicit initializes are executed.

class Display 
{
       int a=9; //initializer expression
       int b=4; //initializer expression
       int c;   //assigned default value
       Display()
       {
     
         a=4; //override default and initializer expression
       }
       void show()
       {
         System.out.println("Value of a : " +a);
         System.out.println("Value of b : " +b);
         System.out.println("Value of c : " +c);
       }
}
   class DefaultConstructor
{
     public static void main(String[] args)
     {
       Display data=new Display();
       data.show();
     }
}

Default Constructor in Java with Example

Static Methods in Java Examples

By Dinesh Thakur

It is possible to have static methods in a class in the same way as we have static fields. The static method is similar to instance method) of a class but the only difference is that the static method can be called through its class name without creating any object of that class. A static method is also called class method as it is associated with a class and not with individual instance of the class. We have already seen the sqrt () method which is a static method within Java standard Math class. A method is declared static when its behavior is not dependent on the instance variable just like Math.sqrt (4.5).This method never uses instance variables so it does not need to know about the specific object.

There is an important restriction on the static method that it can access only static fields and other static methods of a class. This is because static methods can exist and be used even if no objects of that class have been created. If an attempt is made to access a non-static field from the static method then the compiler will generate an error as the static method does not know which nonstatic field value to use. Similarly, a static method cannot access non-static method either because non-static methods are usually associated with instance variable state.

To understand the concept of static method, let us consider the same example as we discussed with static field. Now let us consider another program. Consider a bank decides to change the rate of interest for all its customers then we need to make a method in the class that update it. This can be illustrated in the following program.

// Program That Maintain Bank Account Information about Various Customers 
class Account
{
      int accountNo; //account ID
      double balance ;
      static double rate = 0.05;
      void setData(int n,double bai)
      {
         accountNo = n ;
         balance = bai ;
      }
      void quarterRatecal()
      {
         double interest = balance * rate * 0.25 ;
         balance += interest ;  
      }
      static void modifyRate(double incr)
      {
         rate += incr;
         System.out.println("Modified Rate of Interest : " + rate);
      }
      void show()
      { 
         System.out.println("Account Number : " + accountNo);
         System.out.println("Rate of Interest : " +rate);
         System.out.println("Balance : "+ balance);
      }
}
  public class StaticMethod
  {
      public static void main(String[] args)
      {  
        Account acc1 = new Account();
        Account acc2 = new Account();
        Account.modifyRate(0.01);
        System.out.println("Customel Information......");
        acc1.setData(201,1000);
        acc1.quarterRatecal();  //Calculate interest
        acc1.show(); //display account interest
        System.out.println("Customer2 Information......");
        acc1.setData(202,1000);
        acc2.quarterRatecal(); //Calcuate interest
        acc2.show(); //display account information
      }
  }

Static Methods in Java Examples

The Account class contains a static method modifyRate ().It modifies the rate of interest by the value specified as argument (0.01). The method modifyRate () is made static in the class as we are only using static field rate in it. Only static method can access a static field.

The following points should be remembered while working with static methods.

.  A static method should be called using the class name rather than !in object reference variable.
.  A static method is good for a utility method that does not depend upon a particular instance variable value.
.  A static method can neither access a non-static field nor a non-static method .
. If you have a class with only static methods and you do not want the class to be instantiated, you can mark the constructor private. For example: In the Math class, the constructor is marked private because it contains only static methods.

Static Fields in Java with Example

By Dinesh Thakur

In each object of a class will have its own copy of all the fields of the class. However, in certain situations, it may be required to share a common copy of fields among all the objects of the same class. This is accomplished by declaring the field(s) to be static and such fields are known as static field(s). If a field is declared static then there is one field for the entire class instead of one per object. A static field of a class is often referred to as a class variable because static field is associated with a class and not with individual instances of the class. A static field gets memory only once for the whole class no matter how many objects of a class are created. To declare a static field, prefix the field declaration in the class with the static modifier. Its syntax is,

static datatype fieldName;

class Rectangle 
{
     int length; //length of rectangle
     int breadth; //breadth of rectangle
     static int rectCount =0; //count rectang objects
  
    void setData(int l,int b)
     {
     
        length=l;
        breadth=b;
        rectCount++;
     }
     //method to calculate area of rectangle
     int area()
     {
        int rectArea;
        rectArea = length * breadth;
        return rectArea;
       
     }
}
  //class to create Rectangle objects and access static field
  class StaticField
  {
     public static void main(String[] args)
     {
        //create first rectangle object
       Rectangle firstRect =new Rectangle();
       firstRect.setData(5,6);
       System.out.println("Area of Rectangle 1 : "+firstRect.area());
       //create second rectangle object
       Rectangle secondRect =new Rectangle();
       secondRect.setData(10,20);
       System.out.println("Area of Rectangle 2 : "+secondRect.area());
       // access static field of rectangle class
       System.out.println("Total Number of Objects : "+ Rectangle.rectCount);
       }
   }

Static Fields in Java with Example

In the above example, the class Rectangle has two instance variables length and breadth and one class variable rectCount. When we create firstRect and secondRect objects of type Rectangle, each has its own copy of length and breadth instance variables but both share a single copy of class variable rectCount. The class variable rectCount is initialized to 0 only when the class is first loaded, not each time a new object is made. When the object firstRect is created and the setData () method is invoked, the static variable rectCount is incremented by 1 and it is set to 1 (= 0+ l). Similarly, when the object secondRect is created and the setData () method in invoked the value of rectCount variable is set to 2 (= 1+l). Finally, the statement,

System.out.println(“Total Number of Objects : “+ Rectangle.rectCount);

prints the total number of objects.

From the above example, we find that one use of class variable is to keep a count of how many objects of a class have been created in your program another use of class variable is to define constants which are shared by all the objects of the class. To understand this, let us consider a problem which maintains account information of multiple customers by updating the balance periodically with the same interest. In order to simulate it, we create a Account class which contains the fields like account number, balance, rate of interest etc. To represent individual customer, we need to create an object. Each object will store all its fields in separate memory location. As we have different account number and balance for every Account object but the rate of interest for all the account object is the same. So allocation of separate memory to data member rate of interest for all the objects will cause the following problems.

a) Wastage of memory space will occur because the same value of rate of interest is maintained by all the objects of Account class.

b) If the value of rate of interest changes over time, then each copy would have to be updated that can lead to inefficiency, wastage of time and greater potential of errors.

So in order to overcome this problem, we need to store the rate of interest only once in memory which can be shared by all the objects of the same class. This problem can be solved by declaring the ‘rate of interest’ as a static field. But this may lead to accidental modification as it may be accessed from outside the class and lead to undesirable effects on the efficiency and reliability of the program. In such a case, you have to use the final keyword along with static so that this field can never have its value changed.

Properties of Static Field

A static field of a class has the following characteristics:

1. There is only one copy of static field in a class which is shared among all the objects of the class.

2. A static field can be accessed before any object of a class is created, without reference to any object.

3. To make a static field constant in Java, make a variable as both static and final.

4. The static field is similar to static variable. The main difference is that a static variable is used to retain information between calls whereas static field is used to share information among multiple objects of a class.

Program to Compute the Electricity Bill of a Person

By Dinesh Thakur

In this example, we compute the electricity bill of a particular customer. The class ElectricityBil1 contains field customerNo, name and units. It also contains methods setData () show () and billcalculate ().The statement,

ElectricityBill b = new ElectricityBill();

creates a ElectricityBill object in memory and assigns it to the reference variable b. Then the setData () method is invoked that initializes the fields custornerNo,name and units with 001, Dinesh Thakur and 280 values respectively.

The statement,

double billpay = b.billCalculate();

invokes the billCalculate ()method for the object b and stores the result obtained in the billpay variable. Finally, the bill details are displayed.

class Electricitybill 
{
     private int customerNo;
     private String name;
     private int units;
     void setData(int num,String cname,int nounits )
     {
         customerNo = num;
         name = cname ;
         units=  nounits;
     }
     void show()
     {   
           System.out.println("Customer Number : " + customerNo);
           System.out.println("Customer Number : " + name);
           System.out.println("Units Consumed  : " + units);
     }
     double billcalculate ( )
     {
         double bill;
         if(units<100)
           bill = units * 1.20 ;
         else if(units <= 300)
            bill = 100 * 1.20 + (units - 100) * 2 ;
         else
            bill = 100 * 1.20 + 200 * 2 + (units - 300) * 3 ;
         return bill;
     }
  };
 
class ComputeElectricityBill
{
        public static void main(String[] args)
   {  
        Electricitybill b = new Electricitybill();
        b.setData(001,"Dinesh Thakur", 280);
        double billpay = b.billcalculate();
        b.show( );
        System.out.println("Bill to pay : " + billpay);
   }
}

Compute the Electricity Bill of a Person

Program to Calculate Area and Circumference of Circle in Java Example

By Dinesh Thakur

This example is used to calculate the area and circumference of a circle with given radius. The class Circle contains the field radius and methods setData (), area ()and circumference ().The statement.

Circle obj = new Circle();

creates a Circle object in memory and assign it to the reference variable obj,

The statement,

obj.setData(3.5) ;

assigns the radius field of the Circle object to 3.5 using the reference variable obj.

The statement,

obj.area ();

obj.circumference() ;

calculates the area and circumference of the corresponding Circle object, which is finally displayed.

class circle 
{
     double radius; //radius of circle
     void setData(double r)
     {
        radius = r;
     }
     void area ()
     {
        double circleArea = Math.PI * radius *radius;
        System.out.println("Area of circle is = " + circleArea);
     }
     void circumference()
     {
        double cir = 2 * Math.PI * radius ;
        System.out.println("circumference of circle is = " + cir);
     }
     
  }
  public class AreaAndCircumference
{
     public static void main(String[] args)
     {
      
        circle obj = new circle();
        obj.setData(3.5 );  //call setData method
        obj.area( );  //call area method
        obj.circumference( );  //call circumference method
     }
}

Area and Circumference of Circle

« Previous Page
Next Page »

Primary Sidebar

Java Tutorials

Java Tutorials

  • Java - Home
  • Java - IDE
  • Java - Features
  • Java - History
  • Java - this Keyword
  • Java - Tokens
  • Java - Jump Statements
  • Java - Control Statements
  • Java - Literals
  • Java - Data Types
  • Java - Type Casting
  • Java - Constant
  • Java - Differences
  • Java - Keyword
  • Java - Static Keyword
  • Java - Variable Scope
  • Java - Identifiers
  • Java - Nested For Loop
  • Java - Vector
  • Java - Type Conversion Vs Casting
  • Java - Access Protection
  • Java - Implicit Type Conversion
  • Java - Type Casting
  • Java - Call by Value Vs Reference
  • Java - Collections
  • Java - Garbage Collection
  • Java - Scanner Class
  • Java - this Keyword
  • Java - Final Keyword
  • Java - Access Modifiers
  • Java - Design Patterns in Java

OOPS Concepts

  • Java - OOPS Concepts
  • Java - Characteristics of OOP
  • Java - OOPS Benefits
  • Java - Procedural Vs OOP's
  • Java - Polymorphism
  • Java - Encapsulation
  • Java - Multithreading
  • Java - Serialization

Java Operator & Types

  • Java - Operator
  • Java - Logical Operators
  • Java - Conditional Operator
  • Java - Assignment Operator
  • Java - Shift Operators
  • Java - Bitwise Complement Operator

Java Constructor & Types

  • Java - Constructor
  • Java - Copy Constructor
  • Java - String Constructors
  • Java - Parameterized Constructor

Java Array

  • Java - Array
  • Java - Accessing Array Elements
  • Java - ArrayList
  • Java - Passing Arrays to Methods
  • Java - Wrapper Class
  • Java - Singleton Class
  • Java - Access Specifiers
  • Java - Substring

Java Inheritance & Interfaces

  • Java - Inheritance
  • Java - Multilevel Inheritance
  • Java - Single Inheritance
  • Java - Abstract Class
  • Java - Abstraction
  • Java - Interfaces
  • Java - Extending Interfaces
  • Java - Method Overriding
  • Java - Method Overloading
  • Java - Super Keyword
  • Java - Multiple Inheritance

Exception Handling Tutorials

  • Java - Exception Handling
  • Java - Exception-Handling Advantages
  • Java - Final, Finally and Finalize

Data Structures

  • Java - Data Structures
  • Java - Bubble Sort

Advance Java

  • Java - Applet Life Cycle
  • Java - Applet Explaination
  • Java - Thread Model
  • Java - RMI Architecture
  • Java - Applet
  • Java - Swing Features
  • Java - Choice and list Control
  • Java - JFrame with Multiple JPanels
  • Java - Java Adapter Classes
  • Java - AWT Vs Swing
  • Java - Checkbox
  • Java - Byte Stream Classes
  • Java - Character Stream Classes
  • Java - Change Color of Applet
  • Java - Passing Parameters
  • Java - Html Applet Tag
  • Java - JComboBox
  • Java - CardLayout
  • Java - Keyboard Events
  • Java - Applet Run From CLI
  • Java - Applet Update Method
  • Java - Applet Display Methods
  • Java - Event Handling
  • Java - Scrollbar
  • Java - JFrame ContentPane Layout
  • Java - Class Rectangle
  • Java - Event Handling Model

Java programs

  • Java - Armstrong Number
  • Java - Program Structure
  • Java - Java Programs Types
  • Java - Font Class
  • Java - repaint()
  • Java - Thread Priority
  • Java - 1D Array
  • Java - 3x3 Matrix
  • Java - drawline()
  • Java - Prime Number Program
  • Java - Copy Data
  • Java - Calculate Area of Rectangle
  • Java - Strong Number Program
  • Java - Swap Elements of an Array
  • Java - Parameterized Constructor
  • Java - ActionListener
  • Java - Print Number
  • Java - Find Average Program
  • Java - Simple and Compound Interest
  • Java - Area of Rectangle
  • Java - Default Constructor Program
  • Java - Single Inheritance Program
  • Java - Array of Objects
  • Java - Passing 2D Array
  • Java - Compute the Bill
  • Java - BufferedReader Example
  • Java - Sum of First N Number
  • Java - Check Number
  • Java - Sum of Two 3x3 Matrices
  • Java - Calculate Circumference
  • Java - Perfect Number Program
  • Java - Factorial Program
  • Java - Reverse a String

Other Links

  • Java - PDF Version

Footer

Basic Course

  • Computer Fundamental
  • Computer Networking
  • Operating System
  • Database System
  • Computer Graphics
  • Management System
  • Software Engineering
  • Digital Electronics
  • Electronic Commerce
  • Compiler Design
  • Troubleshooting

Programming

  • Java Programming
  • Structured Query (SQL)
  • C Programming
  • C++ Programming
  • Visual Basic
  • Data Structures
  • Struts 2
  • Java Servlet
  • C# Programming
  • Basic Terms
  • Interviews

World Wide Web

  • Internet
  • Java Script
  • HTML Language
  • Cascading Style Sheet
  • Java Server Pages
  • Wordpress
  • PHP
  • Python Tutorial
  • AngularJS
  • Troubleshooting

 About Us |  Contact Us |  FAQ

Dinesh Thakur is a Technology Columinist and founder of Computer Notes.

Copyright © 2025. All Rights Reserved.

APPLY FOR ONLINE JOB IN BIGGEST CRYPTO COMPANIES
APPLY NOW