Packages and Interfaces

Array: Array is the most important thing in any programming language. By definition, array is the static memory allocation. It allocates the memory for the same data type in sequence. It contains multiple values of same types. It also store the values in memory at the fixed size. Multiple types of arrays are used in any programming language such as: one – dimensional, two – dimensional or can say multi – dimensional.

Declaration of an array:  
int num[]; or int num = new int[2];
Some times user declares an array and it’s size simultaneously. You may or may not be define the size in the declaration time. such as:
int num[] = {50,20,45,82,25,63};

In this program we will see how to declare and implementation. This program illustrates that the array working way. This program takes the numbers present in the num[] array in unordered list and prints numbers in ascending order. In this program the sort() function of the java.util.*; package is using to sort all the numbers present in the num[] array. The Arrays.sort() automatically sorts the list of number in ascending order by default. This function held the argument which is the array name num.

Here is the code of the program:-

import java.util.*;

public class  array{
public static void main(String[] args){
int num[] = {50,20,45,82,25,63};
int l = num.length;
int i,j,t;
System.out.print(“Given number : “);
for (i = 0;i < l;i++ ){
System.out.print(”  ” + num[i]);
}
System.out.println(“\n”);
System.out.print(“Accending order number : “);
Arrays.sort(num);
for(i = 0;i < l;i++){
System.out.print(”  ” + num[i]);
}
}
}

Output of the program:

C:\chandan>javac array.java

C:\chandan>java array
Given number : 50 20 45 82 25 63

Ascending order number : 20 25 45 50 63 82

Now lets 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.

Structure of Java Arrays

Now lets 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.

Lets 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 12 elements as shown  in the figure. Each element is holding a distinct value. Here the first element is refrenced by a[0] i.e. the first  index value. We have filled the 12 distinct values in the array each referenced as:

a[0]=1

a[1]=2

a[n-1]=n

a[11]=12

The figure below shows the structure of an Array more precisely.

Two-Dimensional Arrays

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 command

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

declares a variable, A, 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 A, and that there are 4 ints in each of those arrays.
To process a two-dimensional array, we use nested for loops. We already know about for loop. A loop in a loop is called a Nested loop. That means we can run another loop in a loop.

Notice in the following example how the rows are handled as separate objects.

Code: Java
int[][] a2 = new int[10][5];
 // print array in rectangular form
 for (int i=0; i<a2.length; i++) {
     for (int j=0; j<a2[i].length; j++) {
         System.out.print(" " + a2[i][j]);
     }
     System.out.println("");
 }

In this example, “int[][] a2 = new int[10][5];” notation shows a two-dimensional array. It declares a variable a2 of type int[][],and it initializes that variable to refer to a newly created object. The notation int[10][5] indicates that there are 10 arrays of ints in the array a2, and that there are 5 ints in each of those arrays.

Here is the complete code of the example:

public class twoDimension{
  public static void main(String[] args) {
  int[][] a2 = new int[10][5];
  for (int i=0; i<a2.length; i++) {
  for (int j=0; j<a2[i].length; j++) {
  a2[i][j] = i;
  System.out.print(" " + a2[i][j]);
  }
  System.out.println("");
  }
  }
}

Here is the output for the program:

C:\tamana>javac twoDimension.java
C:\tamana>java twoDimension
 0 0 0 0 0
 1 1 1 1 1
 2 2 2 2 2
 3 3 3 3 3
 4 4 4 4 4
 5 5 5 5 5
 6 6 6 6 6
 7 7 7 7 7
 8 8 8 8 8
 9 9 9 9 9
C:\tamana>_

Multi-dimensional arrays

So far we have studied about the one-dimensional and two-dimensional arrays. To store data in more dimensions a multi-dimensional array is used. A multi-dimensional array of dimension n is a collection of items. These items are accessed via n subscript expressions. For example, in a language that supports it, the element of the two-dimensional array x is denoted by x[i,j].
The Java programming language does not really support multi-dimensional arrays. It does, however, supports an array of arrays. In Java, a two-dimensional array ‘x’ is an array of one-dimensional array. For instance :-

int[][] x = new int[3][5];

The expression x[i] is used to select the one-dimensional array; the expression x[i][j] is ued to select the element from that array. The first element of this array will  be indexed with the “0” value and the last integer will be referenced by “length-1” indexed value. There is no array assignment operator.

Strings in java

Java String Class is immutable, i.e. Strings in java, once created and initialized, cannot be changed on the same reference. A java.lang.String class is final which implies no class and extend it. The java.lang.String class differs from other classes, one difference being that the String objects can be used with the += and + operators for concatenation.

Two useful methods for String objects are equals( ) and substring( ). The equals( ) method is used for testing whether two Strings contain the same value. The substring( ) method is used to obtain a selected portion of a String.

Java.lang.String class creation

A simple String can be created using a string literal enclosed inside double quotes as shown;

String str1 = “My name is bob”;

Since a string literal is a reference, it can be manipulated like any other String reference. The reference value of a string literal can be assigned to another String reference.

If 2 or more Strings have the same set of characters in the same sequence then they share the same reference in memory. Below illustrates this phenomenon.

String str1 = “My name is bob”;
String str2 = “My name is bob”;
String str3 = “My name ”+ “is bob”; //Compile time expression
String name = “bob”;
String str4 = “My name is” + name;
String str5 = new String(“My name is bob”);

In the above code all the String references str1, str2 and str3 denote the same String object, initialized with the character string: “My name is bob”. But the Strings str4 and str5 denote new String objects.

Constructing String objects can also be done from arrays of bytes, arrays of characters, or string buffers. A simple way to convert any primitive value to its string representation is by concatenating it with the empty string (””), using the string concatenation operator (+).

public class StringsDemo {

    public static void main(String[] args) {

      byte[] bytes = {2, 4, 6, 8};

      char[] characters = {'a', 'b', 'C', 'D'};

      StringBuffer strBuffer = new StringBuffer("abcde");

//          Examples of Creation of Strings

      String byteStr = new String(bytes);      

      String charStr = new String(characters); 

      String buffStr = new String(strBuffer);

      System.out.println("byteStr : "+byteStr);

      System.out.println("charStr : "+charStr);

      System.out.println("buffStr : "+buffStr);

    }

}

Output

byteStr :
charStr : abCD
buffStr : abcde

String Equality

public class StringsDemo2 {

        public static void main(String[] args) {
               String str1 = "My name is bob";
               String str2 = "My name is bob";
               String str3 = "My name " + "is bob"; //Compile time expression
               String name = "bob";
               String str4 = "My name is " + name;
               String str5 = new String("My name is bob");
               System.out.println("str1 == str2 : " + (str1 == str2));
               System.out.println("str2 == str3 : " + (str2 == str3));
               System.out.println("str3 == str1 : " + (str3 == str1));
               System.out.println("str4 == str5 : " + (str4 == str5));
               System.out.println("str1 == str4 : " + (str1 == str4));
               System.out.println("str1 == str5 : " + (str1 == str5));
               System.out.println("str1.equals(str2) : " + str1.equals(str2));
               System.out.println("str2.equals(str3) : " + str2.equals(str3));
               System.out.println("str3.equals(str1) : " + str3.equals(str1));
               System.out.println("str4.equals(str5) : " + str4.equals(str5));
               System.out.println("str1.equals(str4) : " + str1.equals(str4));
               System.out.println("str1.equals(str5) : " + str1.equals(str5));
        }
}

Output

str1 == str2 : true
str2 == str3 : true
str3 == str1 : true
str4 == str5 : false
str1 == str4 : false
str1 == str5 : false
str1.equals(str2) : true
str2.equals(str3) : true
str3.equals(str1) : true
str4.equals(str5) : true
str1.equals(str4) : true
str1.equals(str5) : true

Java String Functions

The following program explains the usage of the some of the basic String methods like ;

1. compareTo(String anotherString)
Compares two strings lexicographically.

2. charAt(int index)
Returns the character at the specified index.

3. getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
Copies characters from this string into the destination character array.

4. length()
Returns the length of this string.

5. equals(Object anObject)
Compares this string to the specified object.

6. equalsIgnoreCase(String anotherString)
Compares this String to another String, ignoring case considerations.

7. toUpperCase()
Converts all of the characters in this String to upper case using the rules of the default locale.

7. toLowerCase()
Converts all of the characters in this String to upper case using the rules of the default locale.

9. concat(String str)
Concatenates the specified string to the end of this string.

10. indexOf(int ch)

Returns the index within this string of the first occurrence of the specified character.

11. indexOf(int ch, int fromIndex)

Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index.

12. indexOf(String str)

Returns the index within this string of the first occurrence of the specified substring.

13. indexOf(String str, int fromIndex)

Returns the index within this string of the first occurrence of the specified substring, starting at the specified index.

14. lastIndexOf(int ch)

Returns the index within this string of the last occurrence of the specified character.

15. lastIndexOf(int ch, int fromIndex)

Returns the index within this string of the last occurrence of the specified character, searching backward starting at the specified index.

16. lastIndexOf(String str)

Returns the index within this string of the rightmost occurrence of the specified substring.

17. lastIndexOf(String str, int fromIndex)

Returns the index within this string of the last occurrence of the specified substring, searching backward starting at the specified index.

18. substring(int beginIndex)

Returns a new string that is a substring of this string.

19. substring(int beginIndex, int endIndex)

Returns a new string that is a substring of this string.

20. replace(char oldChar, char newChar)

Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.

21. trim()

Returns a copy of the string, with leading and trailing whitespace omitted.

22. toString()

This object (which is already a string!) is itself returned.

public class StringsDemo3 {

        public static void main(String[] args) {
               String str1 = "My name is bob";
               char str2[] = new char[str1.length()];
               String str3 = "bob";
               String str4 = "cob";
               String str5 = "BoB";
                String str6 = "bob";
               System.out.println("Length of the String str1 : " + str1.length());
               System.out.println("Character at position 3 is : "
                               + str1.charAt(3));
               str1.getChars(0, str1.length(), str2, 0);
               System.out.print("The String str2 is : ");
               for (int i = 0; i < str2.length; i++) {
                       System.out.print(str2[i]);
               }
               System.out.println();
               System.out.print("Comparision Test : ");
               if (str3.compareTo(str4) < 0) {
                       System.out.print(str3 + " < " + str4);
               } else if (str3.compareTo(str4) > 0) {
                       System.out.print(str3 + " > " + str4);
               } else {
                       System.out.print(str3 + " equals " + str4);
               }
               System.out.println();
               System.out.print("Equals Test");
               System.out.println("str3.equalsIgnoreCase(5) : "
                               + str3.equalsIgnoreCase(str5));
                System.out.println("str3.equals(6) : " + str3.equals(str6));
               System.out.println("str1.equals(3) : " + str1.equals(str3));
               str5.toUpperCase(); //Strings are immutable
               System.out.println("str5 : " + str5);
               String temp = str5.toUpperCase();
               System.out.println("str5 Uppercase: " + temp);
               temp = str1.toLowerCase();
               System.out.println("str1 Lowercase: " + str1);
               System.out.println("str1.concat(str4): " + str1.concat(str4));
               String str7temp = "  \t\n Now for some Search and Replace Examples    ";
               String str7 = str7temp.trim();
               System.out.println("str7 : " + str7);
               String newStr = str7.replace('s', 'T');
               System.out.println("newStr : " + newStr);
               System.out.println("indexof Operations on Strings");
               System.out.println("Index of p in " + str7 + " : "
                               + str7.indexOf('p'));
               System.out.println("Index of for in " + str7 + " : "
                               + str7.indexOf("for"));
               System.out.println("str7.indexOf(for, 30) : "
                               + str7.indexOf("for", 30));
               System.out.println("str7.indexOf('p', 30) : "
                               + str7.indexOf('p', 30));
               System.out.println("str7.lastIndexOf('p') : "
                               + str7.lastIndexOf('p'));
               System.out.println("str7.lastIndexOf('p', 4) : "
                               + str7.lastIndexOf('p', 4));
               System.out.print("SubString Operations on Strings");
               String str8 = "SubString Example";
               String sub5 = str8.substring(5); // "ring Example"
               String sub3_6 = str8.substring(3, 6); // "Str"
               System.out.println("str8 : " + str8);
               System.out.println("str8.substring(5) : " + sub5);
               System.out.println("str8.substring(3,6) : " + sub3_6);
        }
}

Output

Length of the String str1 : 14
Character at position 3 is : n
The String str2 is : My name is bob
Comparision Test : bob < cob
Equals Teststr3.equalsIgnoreCase(5) : true
str3.equals(6) : true
str1.equals(3) : false
str5 : BoB
str5 Uppercase: BOB
str1 Lowercase: My name is bob
str1.concat(str4): My name is bobcob
str7 : Now for some Search and Replace Examples
newStr : Now for Tome Search and Replace ExampleT
Indexof Operations on Strings
Index of p in Now for some Search and Replace Examples : 26
Index of for in Now for some Search and Replace Examples : 4
str7.indexOf(for, 30) : -1
str7.indexOf(’p’, 30) : 36
str7.lastIndexOf(’p’) : 36
str7.lastIndexOf(’p’, 4) : -1
SubString Operations on Stringsstr8 : SubString Example
str8.substring(5) : ring Example
str8.substring(3,6) : Str

Below is a program to check for Alpha Numeric character’s in the string.

public class TestAlphaNumericCharacters {

      private void isAlphaNumeric(final String input) {
            boolean isCharFlag = false;
            boolean isNumberFlag = false;
            final char[] chars = input.toCharArray();
            for (int x = 0; x < chars.length; x++) {
                  char c = chars[x];
                  //                 lowercase && uppercase alphabet
                  if ((c >= 'a') && (c <= 'z') || (c >= 'A') && (c <= 'Z')) {
                        isCharFlag = true;
                        continue;
                  }
                  if ((c >= '0') && (c <= '9')) { // numeric
                        isNumberFlag = true;
                        continue;
                  }
            }
            System.out.println("characters are present:" + isCharFlag);
            System.out.println("Numbers are present :" + isNumberFlag);
      }
      public static void main(String[] args) {
            TestAlphaNumericCharacters tANC = new TestAlphaNumericCharacters();
            tANC.isAlphaNumeric("beginn3ers");
      }
}

Output

characters are present:true
Numbers are present :true

Below is a java program to Reverse a string (Reverse by words / characters)

import java.util.*;

public class StringReverse {

        public static void main(String[] args) {
               String input = "beginner java tutorial";
               Stack stack = new Stack(); //A Stack is a Last In First Out Data Structure
               StringTokenizer stringTokenizer = new StringTokenizer(input);
               while (stringTokenizer.hasMoreTokens()) {
                       stack.push(stringTokenizer.nextElement());
               }
               System.out.println("Original String: " + input);
               System.out.print("Reversed String by Words: ");
               while (!stack.empty()) {
                       System.out.print(stack.pop());
                       System.out.print(" ");
               }
               System.out.println();
               System.out.print("Reversed String by characters: ");
               StringBuffer rev = new StringBuffer(input).reverse();
               System.out.print(rev);
        }
}

Output

Original String: beginner java tutorial
Reversed String by Words: tutorial java beginner
Reversed String by characters: lairotut avaj rennigeb

Java String Comparison:

 

Java String compare to determine Equality

java string compare can be done in many ways as shown below. Depending on the type of java string compare you need, each of them is used.

* == Operator
* equals method
* compareTo method

Comparing using the == Operator

The == operator is used when we have to compare the String object references. If two String variables point to the same object in memory, the comparison returns true. Otherwise, the comparison returns false. Note that the ‘==’ operator does not compare the content of the text present in the String objects. It only compares the references the 2 Strings are pointing to. The following Program would print “The strings are unequal” In the first case and “The strings are equal” in the second case.

<br /><font size=-1>

public class StringComparision1 {

public static void main(String[] args) {

String name1 = “Bob”;

String name2 = new String(“Bob”);

String name3 = “Bob”;

// 1st case

if (name1 == name2) {

System.out.println(“The strings are equal.”);

} else {

System.out.println(“The strings are unequal.”);

}

// 2nd case

if (name1 == name3) {

System.out.println(“The strings are equal.”);

} else {

System.out.println(“The strings are unequal.”);

}

}

}

Comparing using the equals Method

The equals method is used when we need to compare the content of the text present in the String objects. This method returns true when two String objects hold the same content (i.e. the same values). The following Program would print “The strings are unequal” In the first case and “The strings are equal” in the second case.

public class StringComparision2 {

public static void main(String[] args) {

String name1 = “Bob”;

String name2 = new String(“Bob1”);

String name3 = “Bob”;

// 1st case

if (name1.equals(name2)) {

System.out.println(“The strings are equal.”);

} else {

System.out.println(“The strings are unequal.”);

}

// 2nd case

if (name1.equals(name3)) {

System.out.println(“The strings are equal.”);

} else {

System.out.println(“The strings are unequal.”);

}

}

}

Comparing using the compareTo Method

The compareTo method is used when we need to determine the order of Strings lexicographically. It compares char values similar to the equals method. The compareTo method returns a negative integer if the first String object precedes the second string. It returns zero if the 2 strings being compared are equal. It returns a positive integer if the first String object follows the second string. The following Program would print “name2 follows name1” In the first case and “name1 follows name3” in the second case.

public class StringComparision3 {

public static void main(String[] args) {

String name1 = “bob”;

String name2 = new String(“cob”);

String name3 = “Bob”;

// 1st case

if (name1.compareTo(name2) == 0) {

System.out.println(“The strings are equal.”);

} else if (name1.compareTo(name2) < 0) {

System.out.println(“name2 follows name1”);

} else {

System.out.println(“name1 follows name2”);

}

// 2nd case. Comparing Ascii Uppercase will be smaller then Lower Case

if (name1.compareTo(name3) == 0) {

System.out.println(“The strings are equal.”);

} else if (name1.compareTo(name3) < 0) {

System.out.println(“name3 follows name1”);

} else {

System.out.println(“name1 follows name3”);

}

}

}

Java String Buffer:

StringBuffer Class

StringBuffer class is a mutable class unlike the String class which is immutable. Both the capacity and character string of a StringBuffer Class. StringBuffer can be changed dynamically. String buffers are preferred when heavy modification of character strings is involved (appending, inserting, deleting, modifying etc).

Strings can be obtained from string buffers. Since the StringBuffer class does not override the equals() method from the Object class, contents of string buffers should be converted to String objects for string comparison.
A StringIndexOutOfBoundsException is thrown if an index is not valid when using wrong index in String Buffer manipulations

Creation of StringBuffers

StringBuffer Constructors

public class StringBufferDemo {

        public static void main(String[] args) {
               //      Examples of Creation of Strings
               StringBuffer strBuf1 = new StringBuffer("Bob");
               StringBuffer strBuf2 = new StringBuffer(100); //With capacity 100
               StringBuffer strBuf3 = new StringBuffer(); //Default Capacity 16
               System.out.println("strBuf1 : " + strBuf1);
               System.out.println("strBuf2 capacity : " + strBuf2.capacity());
               System.out.println("strBuf3 capacity : " + strBuf3.capacity());
        }
}

Output

strBuf1 : Bob
strBuf2 capacity : 100
strBuf3 capacity : 16

StringBuffer Functions

The following program explains the usage of the some of the basic StringBuffer methods like ;

1. capacity()
Returns the current capacity of the String buffer.

2. length()
Returns the length (character count) of this string buffer.

3. charAt(int index)
The specified character of the sequence currently represented by the string buffer, as indicated by the index argument, is returned.

4. setCharAt(int index, char ch)
The character at the specified index of this string buffer is set to ch

5. toString()
Converts to a string representing the data in this string buffer

6. insert(int offset, char c)
Inserts the string representation of the char argument into this string buffer.
Note that the StringBuffer class has got many overloaded ‘insert’ methods which can be used based on the application need.

7. delete(int start, int end)
Removes the characters in a substring of this StringBuffer

8. replace(int start, int end, String str)
Replaces the characters in a substring of this StringBuffer with characters in the specified String.

9. reverse()
The character sequence contained in this string buffer is replaced by the reverse of the sequence.

10. append(String str)
Appends the string to this string buffer.
Note that the StringBuffer class has got many overloaded ‘append’ methods which can be used based on the application need.

11. setLength(int newLength)
Sets the length of this String buffer.

public class StringBufferFunctionsDemo {

        public static void main(String[] args) {
               //      Examples of Creation of Strings
               StringBuffer strBuf1 = new StringBuffer("Bobby");
               StringBuffer strBuf2 = new StringBuffer(100); //With capacity 100
               StringBuffer strBuf3 = new StringBuffer(); //Default Capacity 16
               System.out.println("strBuf1 : " + strBuf1);
               System.out.println("strBuf1 capacity : " + strBuf1.capacity());
               System.out.println("strBuf2 capacity : " + strBuf2.capacity());
               System.out.println("strBuf3 capacity : " + strBuf3.capacity());
               System.out.println("strBuf1 length : " + strBuf1.length());
               System.out.println("strBuf1 charAt 2 : " + strBuf1.charAt(2));
               //      A StringIndexOutOfBoundsException is thrown if the index is not valid.
               strBuf1.setCharAt(1, 't');
               System.out.println("strBuf1 after setCharAt 1 to t is : "
                               + strBuf1);
               System.out
                               .println("strBuf1 toString() is : " + strBuf1.toString());
               strBuf3.append("beginner-java-tutorial");
               System.out.println("strBuf3 when appended with a String : "
                               + strBuf3.toString());
               strBuf3.insert(1, 'c');
               System.out.println("strBuf3 when c is inserted at 1 : "
                               + strBuf3.toString());
               strBuf3.delete(1, 'c');
               System.out.println("strBuf3 when c is deleted at 1 : "
                               + strBuf3.toString());
               strBuf3.reverse();
               System.out.println("Reversed strBuf3 : " + strBuf3);
               strBuf2.setLength(5);
               strBuf2.append("jdbc-tutorial");
               System.out.println("strBuf2 : " + strBuf2);
               //      We can clear a StringBuffer using the following line
               strBuf2.setLength(0);
               System.out.println("strBuf2 when cleared using setLength(0): "
                               + strBuf2);
        }
}

Output

strBuf1 : Bobby
strBuf1 capacity : 21
strBuf2 capacity : 100
strBuf3 capacity : 16
strBuf1 length : 5
strBuf1 charAt 2 : b
strBuf1 after setCharAt 1 to t is : Btbby
strBuf1 toString() is : Btbby
strBuf3 when appended with a String : beginner-java-tutorial
strBuf3 when c is inserted at 1 : bceginner-java-tutorial
strBuf3 when c is deleted at 1 : b
Reversed strBuf3 : b
strBuf2 :

Vector implements a dynamic array. It is similar to ArrayList, but with two differences:  Vector is synchronized, and it contains many legacy methods that are not part of the collections framework. With the release of Java 2, Vector was reengineered to extend AbstractList and implement the List interface, so it now is fully compatible with collections.

Here are the Vector constructors:

Vector( )
Vector(int size)
Vector(int size, int incr)
Vector(Collection c)

The first form creates a default vector, which has an initial size of 10. The second form creates a vector whose initial capacity is specified by size. The third form creates a vector whose initial capacity is specified by size and whose increment is specified by incr. The increment specifies the number of elements to allocate each time that a vector is resized upward. The fourth form creates a vector that contains the elements of collection c. This constructor was added by Java 2.

All vectors start with an initial capacity. After this initial capacity is reached, the next time that you attempt to store an object in the vector, the vector automatically allocates space for that object plus extra room for additional objects. By allocating more than just the required memory, the vector reduces the number of allocations that must take place. This reduction is important, because allocations are costly in terms of time. The amount of extra space allocated during each reallocation is determined by the increment that you specify when you create the vector. If you don’t specify an increment, the vector’s size is doubled by each allocation cycle.

Vector :defines these protected data members:

int capacityIncrement;
int elementCount;
Object elementData[ ];

The increment value is stored in capacityIncrement. The number of elements currently in the vector is stored in elementCount. The array that holds the vector is stored in elementData.

Because Vector implements List, you can use a vector just like you use an ArrayList instance. You can also manipulate one using its legacy methods. For example, after you instantiate a Vector, you can add an element to it by calling addElement( ). To obtain the element at a specific location, call elementAt( ). To obtain the first element in the vector, call firstElement( ). To retrieve the last element, call lastElement( ). You can obtain the index of an element by using indexOf( ) and lastIndexOf( ). To remove an element, call removeElement( ) or removeElementAt( ).

The following program uses a vector to store various types of numeric objects. It demonstrates several of the legacy methods defined by Vector. It also demonstrates the Enumeration interface.

// Demonstrate various Vector operations.
import java.util.*;
class VectorDemo {
public static void main(String args[]) {
// initial size is 3, increment is 2
Vector v = new Vector(3, 2);
System.out.println(“Initial size: ” + v.size());
System.out.println(“Initial capacity: ” +
v.capacity());
v.addElement(new Integer(1));
v.addElement(new Integer(2));
v.addElement(new Integer(3));
v.addElement(new Integer(4));
System.out.println(“Capacity after four additions: ” +
v.capacity());
v.addElement(new Double(5.45));
System.out.println(“Current capacity: ” +
v.capacity());
v.addElement(new Double(6.08));
v.addElement(new Integer(7));
System.out.println(“Current capacity: ” +
v.capacity());
v.addElement(new Float(9.4));
v.addElement(new Integer(10));
System.out.println(“Current capacity: ” +
v.capacity());
v.addElement(new Integer(11));
v.addElement(new Integer(12));
System.out.println(“First element: ” +
(Integer)v.firstElement());
System.out.println(“Last element: ” +
(Integer)v.lastElement());
if(v.contains(new Integer(3)))
System.out.println(“Vector contains 3.”);
// enumerate the elements in the vector.
Enumeration vEnum = v.elements();
System.out.println(“\\nElements in vector:”);
while(vEnum.hasMoreElements())
System.out.print(vEnum.nextElement() + ” “);
System.out.println();
}
}

The output from this program is shown here:

Initial size: 0
Initial capacity: 3
Capacity after four additions: 5
Current capacity: 5
Current capacity: 7
Current capacity: 9
First element: 1
Last element: 12
Vector contains 3.
Elements in vector:
1 2 3 4 5.45 6.08 7 9.4 10 11 12

With the release of Java 2, Vector adds support for iterators. Instead of relying on an enumeration to cycle through the objects (as the preceding program does), you now can use an iterator. For example, the following iterator-based code can be substituted into the program:

// use an iterator to display contents
Iterator vItr = v.iterator();
System.out.println(“\\nElements in vector:”);
while(vItr.hasNext())
System.out.print(vItr.next() + ” “);
System.out.println();

Because enumerations are not recommended for new code, you will usually use an iterator to enumerate the contents of a vector. Of course, much legacy code exists that employs enumerations. Fortunately, enumerations and iterators work in nearly the same manner.

Wrapper Classes

In this section you will learn about Wrapper classes and all the methods that manipulate data and allows to operate a certain work.

Wrapper class is a wrapper around a primitive data type. It represents primitive data types in their corresponding class instances e.g. a boolean data type can be represented as a Boolean class instance. All of the primitive wrapper classes in Java are immutable i.e. once assigned a value to a wrapper class instance cannot be changed further.

Wrapper Classes are used broadly with Collection classes in the java.util package and with the classes in the java.lang.reflect reflection package.

Following table lists the primitive types and the corresponding wrapper classes:

Primitive

Wrapper

boolean

  java.lang.Boolean

byte

  java.lang.Byte

char

  java.lang.Character

double

  java.lang.Double

float

  java.lang.Float

int

  java.lang.Integer

long

  java.lang.Long

short

  java.lang.Short

void

  java.lang.Void

In Java 5.0 version, additional wrapper classes were introduced in the java.util.concurrent.atomic package. They provide atomic operations for assignment, addition and increment. These classes act like variables  and cannot be used as a substitute for the regular wrapper classes. Few of these new wrapper classes like AtomicInteger and AtomicLong are the subclasses of the Number Classes.

Primitive

Wrapper

boolean

  AtomicBoolean

int

  AtomicInteger

long

  AtomicLong

V

  AtomicReference<V>

Features Of the Wrapper Classes

Some of the sound features maintained by the Wrapper Classes are as under :

  • All the methods of the wrapper classes are static.
  • The Wrapper class does not contain constructors.
  • Once a value is assigned to a wrapper class instance it can not be changed, anymore.

Wrapper Classes : Methods with examples

There are some of the methods of the Wrapper class which are used to manipulate the data. Few of them are given below:

1.  add(int, Object): Learn to insert an element at the specified position.

2.  add(Object): Learn to insert an object at the end of a list.

3.  addAll(ArrayList): Learn to insert an array list of objects to another list.

4.  get(): Learn to retrieve the elements contained with in an ArrayList object.

5.  Integer.toBinaryString(): Learn to convert the Integer type object to a String object.

6.  size(): Learn to get the dynamic capacity of a list.

7.  remove(): Learn to remove an element from a particular position specified by a  index value.

8.  set(int, Object): Learn to replace an element at the position specified by a  index value.

Java Interface

In Java, this multiple inheritance problem is solved with a powerful construct called interfaces. Interface can be used to define a generic template and then one or more abstract classes to define partial implementations of the interface. Interfaces just specify the method declaration (implicitly public and abstract) and can only contain fields (which are implicitly public static final). Interface definition begins with a keyword interface. An interface like that of an abstract class cannot be instantiated.

Multiple Inheritance is allowed when extending interfaces i.e. one interface can extend none, one or more interfaces. Java does not support multiple inheritance, but it allows you to extend one class and implement many interfaces.

If a class that implements an interface does not define all the methods of the interface, then it must be declared abstract and the method definitions must be provided by the subclass that extends the abstract class.

Example 1: Below is an example of a Shape interface

interface Shape {

      public double area();
      public double volume();
}

Below is a Point class that implements the Shape interface.

public class Point implements Shape {

      static int x, y;
      public Point() {
            x = 0;
            y = 0;
      }
      public double area() {
            return 0;
      }
      public double volume() {
            return 0;
      }
      public static void print() {
            System.out.println("point: " + x + "," + y);
      }
      public static void main(String args[]) {
            Point p = new Point();
            p.print();
      }
}

Similarly, other shape objects can be created by interface programming by implementing generic Shape Interface.

Example 2: Below is a java interfaces program showing the power of interface programming in java

Listing below shows 2 interfaces and 4 classes one being an abstract class.
Note: The method toString in class A1 is an overridden version of the method defined in the class named Object. The classes B1 and C1 satisfy the interface contract. But since the class D1 does not define all the methods of the implemented interface I2, the class D1 is declared abstract.
Also,
i1.methodI2() produces a compilation error as the method is not declared in I1 or any of its super interfaces if present. Hence a downcast of interface reference I1 solves the problem as shown in the program. The same problem applies to i1.methodA1(), which is again resolved by a downcast.

When we invoke the toString() method which is a method of an Object, there does not seem to be any problem as every interface or class extends Object and any class can override the default toString() to suit your application needs. ((C1)o1).methodI1() compiles successfully, but produces a ClassCastException at runtime. This is because B1 does not have any relationship with C1 except they are “siblings”. You can’t cast siblings into one another.

When a given interface method is invoked on a given reference, the behavior that results will be appropriate to the class from which that particular object was instantiated. This is runtime polymorphism based on interfaces and overridden methods.

interface I1 {

        void methodI1(); // public static by default
}

interface I2 extends I1 {

        void methodI2(); // public static by default
}

class A1 {

        public String methodA1() {
               String strA1 = "I am in methodC1 of class A1";
               return strA1;
        }
        public String toString() {
               return "toString() method of class A1";
        }
}

class B1 extends A1 implements I2 {

        public void methodI1() {
               System.out.println("I am in methodI1 of class B1");
        }
        public void methodI2() {
               System.out.println("I am in methodI2 of class B1");
        }
}

class C1 implements I2 {

        public void methodI1() {
               System.out.println("I am in methodI1 of class C1");
        }
        public void methodI2() {
               System.out.println("I am in methodI2 of class C1");
        }
}

// Note that the class is declared as abstract as it does not
// satisfy the interface contract
abstract class D1 implements I2 {

        public void methodI1() {
        }
        // This class does not implement methodI2() hence declared abstract.
}

public class InterFaceEx {

        public static void main(String[] args) {
               I1 i1 = new B1();
               i1.methodI1(); // OK as methodI1 is present in B1
               // i1.methodI2(); Compilation error as methodI2 not present in I1
               // Casting to convert the type of the reference from type I1 to type I2
               ((I2) i1).methodI2();
               I2 i2 = new B1();
               i2.methodI1(); // OK
               i2.methodI2(); // OK
               // Does not Compile as methodA1() not present in interface reference I1
               // String var = i1.methodA1();
               // Hence I1 requires a cast to invoke methodA1
               String var2 = ((A1) i1).methodA1();
               System.out.println("var2 : " + var2);
               String var3 = ((B1) i1).methodA1();
               System.out.println("var3 : " + var3);
               String var4 = i1.toString();
               System.out.println("var4 : " + var4);
               String var5 = i2.toString();
               System.out.println("var5 : " + var5);
               I1 i3 = new C1();
               String var6 = i3.toString();
               System.out.println("var6 : " + var6); // It prints the Object toString() method
               Object o1 = new B1();
               // o1.methodI1(); does not compile as Object class does not define
               // methodI1()
               // To solve the probelm we need to downcast o1 reference. We can do it
               // in the following 4 ways
               ((I1) o1).methodI1(); // 1
               ((I2) o1).methodI1(); // 2
               ((B1) o1).methodI1(); // 3
               /*
                *
                * B1 does not have any relationship with C1 except they are "siblings".
                *
                * Well, you can't cast siblings into one another.
                *
                */
               // ((C1)o1).methodI1(); Produces a ClassCastException
        }
}

Output

I am in methodI1 of class B1
I am in methodI2 of class B1
I am in methodI1 of class B1
I am in methodI2 of class B1
var2 : I am in methodC1 of class A1
var3 : I am in methodC1 of class A1
var4 : toString() method of class A1
var5 : toString() method of class A1
var6 : C1@190d11
I am in methodI1 of class B1
I am in methodI1 of class B1
I am in methodI1 of class B1

Enum Data Types

Enum type is a type which consist of fixed set of constant fields. like direction and days includes values NORTH, SOUTH, EAST, and WEST and SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY and SATURDAY respectively. Since they are constants so we are taking these values into the uppercase letters.

Lets take an example of enum data types:

EnumTestResult.java

public class EnumTestResult {
  DaysOfWeek day;
  
  public EnumTestResult(DaysOfWeek day) {
  this.day = day;
  }
  
  public void howsday() {
  switch (day) {
  case MONDAY: System.out.println("Mondays are working days.");
 break;
  
  case THURSDAY: System.out.println
   ("Thursday are also working days.");
 break;
 
  case SATURDAY:
  case SUNDAY: System.out.println("Weekends are best.");
 break;
 
  default: System.out.println("Midweek days are so-so.");
 break;
  }
  }
  
  public static void main(String[] args) {
  EnumTestResult FirstDay = new EnumTestResult(DaysOfWeek.MONDAY);
  FirstDay.howsday();
  EnumTestResult ThirdDay = new EnumTestResult(DaysOfWeek.WEDNESDAY);
  ThirdDay.howsday();
  EnumTestResult FourthDay = new EnumTestResult(DaysOfWeek.FRIDAY);
  FourthDay.howsday();
  EnumTestResult SixthDay = new EnumTestResult(DaysOfWeek.SATURDAY);
  SixthDay.howsday();
  EnumTestResult SeventhDay = new EnumTestResult(DaysOfWeek.SUNDAY);
  SeventhDay.howsday();
  
  
  }
}

DaysOfWeek.java

public enum DaysOfWeek { 
  SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY 
}

Here is the Output:

C:\Documents and Settings\compaq 20\Desktop\Tutorials>java EnumTestResult
Mondays are working days.
Midweek days are so-so.
Midweek days are so-so.
Weekends are best.
Weekends are best.

What Are Packages?

A package allows a developer to group classes (and interfaces) together. These classes will all be related in some way – they might all be to do with a specific application or perform a specific set of tasks. For example, the Java API is full of packages. One of them is the javax.xml package. It and its subpackages contain all the classes in the Java API to do with handling XML.

Defining a Package

To group classes into a package each class must have a package statement defined at the top of its .java file. It lets the compiler know which package the class belongs to and must be the first line of code. For example, imagine you’re making a simple Battleships game. It makes sense to put all the classes needed in a package called battleships:

 package battleships

 class GameBoard{

 } 

Every class with the above package statement at the top will now be part of the Battleships package.

Typically packages are stored in a corresponding directory on the filesystem but it is possible to store them in a database. The directory on the filesystem must have the same name as the package. It’s where all the classes belonging to that package are stored. For example, if the battleships package contains the classes GameBoard, Ship, ClientGUI then there will be files called GameBoard.java, Ship.java and ClientGUI.java stored in a directory call battleships.

Creating a Hierarchy

Organizing classes doesn’t have to be at just one level. Every package can have as many subpackages as needed. To distinguish the package and subpackage a “.” is placed in-between the package names. For example, the name of the javax.xml package shows that xml is a subpackage of the javax package. It doesn’t stop there, under xml there are 11 subpackages: bind, crypto, datatype, namespace, parsers, soap, stream, transform, validation, ws and xpath.

The directories on the file system must match the package hierarchy. For example, the classes in the javax.xml.crypto package will live in a directory structure of ..\javax\xml\crypto.

It should be noted that the hierarchy created is not recognized by the compiler. The names of the packages and subpackages show the relationship that the classes they contain have with each other. But, as far as the compiler is concerned each package is a distinct set of classes. It does not view a class in a subpackage as being part of its parent package. This distinction becomes more apparent when it comes to using packages.

Naming Packages

There is a standard naming convention for packages. Names should be in lowercase. With small projects that only have a few packages the names are typically simple (but meaningful!) names:

 package pokeranalyzer
 package mycalculator 

In software companies and large projects, where the packages might be imported into other classes, the names need to be distinctive. If two different packages contain a class with the same name it’s important that there can be no naming conflict. This is done by ensuring the package names are different by starting the package name with the company domain, before being split into layers or features:

 package com.mycompany.utilities 
 package org.bobscompany.application.userinterface 

At some point every programmer needs to use a public class that is contained within a package. If the class is contained within a different package then the program must tell the compiler where to find it. There are three ways to reference a class in another package: use its fully qualified name, import the class, import the package.

Using the Fully Qualified Name

Using a fully qualified name is the same principle as giving the full location of a file by adding its directory path. For example, to use a JOptionPane all I need to know is its package name is javax.swing:

javax.swing.JOptionPane.showMessageDialog( null, "I'm fully qualified!"); 

This is fine in a one off situation but if a class needs to use several JOptionPanes then writing the full name for each one is not very exciting for the programmer.

Import the Class

To avoid using the fully qualified name the packaged class can be specifically referenced. This is done using an import statement. Import statements are placed after the package statement but before the class declaration. To import just one class put its fully qualified name after the import keyword:

 package thisPackage;

 import javax.swing.JOptionPane;

 public class myClass{

   JOptionPane.showMessageDialog(null, "Just my class is imported!");
 } 

As you can see from the above code the JOptionPane in myClass can now be used by just using its class name.

Import the Package

An advantage of importing each class used in a program separately is that a programmer can easily see which ones are being used. However, if a lot of classes are needed from the same package it might make more sense to just reference the entire package. For example, if a class is designed to create a complex user interface then a lot of the classes in the javax.swing package might be needed. In this case its easier to import the entire package by adding an “.*” at the end of the import statement:

 package thisPackage;

 import javax.swing.*;

 public class myClass{

   JOptionPane.showMessageDialog(null, "My entire package is imported!");
 } 

The “.*” tells the compiler that the class might want to use any of the classes contained in the javax.swing package. It does not include the classes in any subpackages. For example, if the class needed to use the EtchedBorder class in the javax.swing.border package it would need to be imported separately:

 import javax.swing.*;
 import javax.swing.border.EtchedBorder; 

There is no run-time overhead incurred by importing the entire package – the compiled code will be the same size whether each individual class or the entire package is referenced. The choice is mainly about the readability of the code.

Using Classes With the Same Name

If there are two classes that share the same name but are imported from different packages, the compiler will get confused and the code will not compile:

 import apackage.Person;
 import anotherpackage.Person;

If both classes need to be used then use their fully qualified names to avoid compiler (and programmer) confusion:

 apackage.Person bob = new apackage.Person();
 anotherpackage.Person bill = new anotherpackage.Person(); 

Importing Static Fields and Methods

There is a shortcut for using static fields and static methods in a class. By adding the static modifier to the import statement the class name for the static field or static method is not needed. For example, all the color static fields can be imported by using:

 import static java.awt.Color.*; 

In the code the color constants can then be used without the need for the color class prefix:

 JButton pressMeButton = new JButton("Press Me");
 pressMeButton.setForeground(RED); 

Be careful with the use of static imports because they can cause readability issues for programmers new to the code. It can be hard to spot a static field without its class name attached.

What Is a Naming Convention?

A naming convention is a rule to follow as you decide what to name your identifiers (e.g. class, package, variable, method, etc..).

Why Use Naming Conventions?

Different Java programmers can have different styles and approaches to the way they program. By using standard Java naming conventions they make their code easier to read for themselves and for other programmers. Readability of Java code is important because it means less time is spent trying to figure out what the code does, leaving more time to fix or modify it.

To illustrate the point it’s worth mentioning that most software companies will have a document that outlines the naming conventions they want their programmers to follow. A new programmer who becomes familiar with those rules will be able to understand code written by a programmer who might have left the company many years before hand.

Picking a Name for Your Identifier

When choosing a name for an identifier make sure it’s meaningful. For instance, if your program deals with customer accounts then choose names that make sense to dealing with customers and their accounts (e.g., customerName, accountDetails). Don’t worry about the length of the name. A longer name that sums up the identifier perfectly is preferable to a shorter name that might be quick to type but ambiguous.

A Few Words About Cases

Using the right letter case is the key to following a naming convention:

  • Lowercase is where all the letters in a word are written without any capitalization (e.g., while, if, mypackage).
  • Uppercase is where all the letters in a word are written in capitals. When there are more than two words in the name use underscores to separate them (e.g., MAX_HOURS, FIRST_DAY_OF_WEEK).
  • CamelCase (also known as Upper CamelCase) is where each new word begins with a capital letter (e.g., CamelCase, CustomerAccount, PlayingCard).
  • Mixed case (also known as Lower CamelCase) is the same as CamelCase except the first letter of the name is in lowercase (e.g., hasChildren, customerFirstName, customerLastName).

Standard Java Naming Conventions

The below list outlines the standard Java naming conventions for each identifier type:

  • Packages: Names should be in lowercase. With small projects that only have a few packages it’s okay to just give them simple (but meaningful!) names:
·          package pokeranalyzer
 package mycalculator 

In software companies and large projects where the packages might be imported into other classes, the names will normally be subdivided. Typically this will start with the company domain before being split into layers or features:

 package com.mycompany.utilities
 package org.bobscompany.application.userinterface 
  • Classes: Names should be in CamelCase. Try to use nouns because a class is normally representing something in the real world:
·          class Customer
 class Account 
  • Interfaces: Names should be in CamelCase. They tend to have a name that describes an operation that a class can do:
·          interface Comparable
 interface Enumerable 

Note that some programmers like to distinguish interfaces by beginning the name with an “I”:

 interface IComparable
 interface IEnumerable 
  • Methods: Names should be in mixed case. Use verbs to describe what the method does:
·          void calculateTax()
 string getSurname() 
  • Variables: Names should be in mixed case. The names should represent what the value of the variable represents:
·          string firstName
 int orderNumber 

Only use very short names when the variables are short lived, such as in for loops:

 for (int i=0; i<20;i++)
 {
    //i only lives in here
 } 
  • Constants: Names should be in uppercase.
·          static final int DEFAULT_WIDTH
 static final int MAX_HEIGHT 

OOP Concepts in JAVA

 Classes:  A class is nothing but a blueprint for creating different objects which defines its properties and behaviors. An object exhibits the properties and behaviors defined by its class. A class can contain fields and methods to describe the behavior of an object. Methods are nothing but members of a class that provide a service for an object or perform some business logic.

Objects:  An object is an instance of a class created using a new operator. The new operator returns a reference to a new instance of a class. This reference can be assigned to a reference variable of the class. The process of creating objects from a class is called instantiation. An object reference provides a handle to an object that is created and stored in memory. In Java, objects can only be manipulated via references, which can be stored in variables.

Interface:  An Interface is a contract in the form of collection of method and constant declarations. When a class implements an interface, it promises to implement all of the methods declared in that interface.

Instance Members:  Each object created will have its own copies of the fields defined in its class called instance variables which represent an object’s state. The methods of an object define its behaviour called instance methods. Instance variables and instance methods, which belong to objects, are collectively called instance members. The dot ‘.’ notation with a object reference is used to access Instance Members.

Static Members:  Static members are those that belong to a class as a whole and not to a particular instance (object). A static variable is initialized when the class is loaded. Similarly, a class can have static methods. Static variables and static methods are collectively known as static members, and are declared with a keyword static. Static members in the class can be accessed either by using the class name or by using the object reference, but instance members can only be accessed via object references.Below is a program showing the various parts of the basic language syntax that were discussed above.

/** Comment * Displays “Hello World!” to the standard output.  */

public class HelloWorld {

      String output = “”;

      static HelloWorld helloObj;  //Line 1

       public HelloWorld(){

            output = “Hello World”;

      }

       public String printMessage(){

            return output;

      }

      public static void main (String args[]) {

            helloObj = new HelloWorld();  //Line 2

            System.out.println(helloObj.printMessage());

  } }

Class Name: HelloWorld
Object Reference: helloObj (in Line 1)
Object Created: helloObj (In Line 2)
Member Function: printMessage
Field: output (String)
Static Member: helloObj
Instance Member : output (String)

 Java Operators:They are used to manipulate primitive data types. Java operators can be classified as unary, binary, or ternary—meaning taking one, two, or three arguments, respectively. A unary operator may appear
before (prefix) its argument or after (postfix) its argument. A binary or ternary operator appears between its arguments.

Operators in java fall into 8 different categories:Java operators fall into eight different categories: assignment, arithmetic, relational, logical, bitwise,
compound assignment, conditional, and type.

 Assignment Operators               =

Arithmetic Operators                 -      +       *      /       %      ++     --

Relational Operators                 >      <       >=     <=      ==      !=

L Logical Operators                  &&     ||       &      |       !       ^

Bit wise Operator                    &       |        ^      >>      >>>

Compound Assignment Operators     +=      -=      *=     /=      %= 

                                    <<=      >>=    >>>=

Conditional Operator                 ?:

Java has eight different operator types: assignment, arithmetic, relational, logical, bitwise, compound assignment, conditional, and type.

Assignment operators:

The java assignment operator statement has the following syntax:

<variable> = <expression>

If the value already exists in the variable it is overwritten by the assignment operator (=).

public class AssignmentOperatorsDemo {       public AssignmentOperatorsDemo() {            //            Assigning Primitive Values

            int j, k;

            j = 10; // j gets the value 10.

            j = 5; // j gets the value 5. Previous value is overwritten.

            k = j; // k gets the value 5.

            System.out.println(“j is : ” + j);

            System.out.println(“k is : ” + k);

            //            Assigning References

            Integer i1 = new Integer(“1”);

            Integer i2 = new Integer(“2”);

            System.out.println(“i1 is : ” + i1);

            System.out.println(“i2 is : ” + i2);

            i1 = i2;

            System.out.println(“i1 is : ” + i1);

            System.out.println(“i2 is : ” + i2);

            //            Multiple Assignments

            k = j = 10; // (k = (j = 10))

            System.out.println(“j is : ” + j);

            System.out.println(“k is : ” + k);

      }

      public static void main(String args[]) {

            new AssignmentOperatorsDemo();

      } }

Arithmetic operators:Java provides eight Arithmetic operators. They are for addition, subtraction, multiplication, division, modulo (or remainder), increment (or add 1), decrement (or subtract 1), and negation. An example program is shown below that demonstrates the different arithmetic operators in java.

The binary operator + is overloaded in the sense that the operation performed is determined by the type of the operands. When one of the operands is a String object, the other operand is implicitly converted to its string representation and string concatenation is performed.

String message = 100 + “Messages”; //”100 Messages”

public class ArithmeticOperatorsDemo {       public ArithmeticOperatorsDemo() {      int x, y = 10, z = 5;

      x = y + z;

      System.out.println(“+ operator resulted in ” + x);

      x = y – z;

      System.out.println(“- operator resulted in ” + x);

      x = y * z;

      System.out.println(“* operator resulted in ” + x);

      x = y / z;

      System.out.println(“/ operator resulted in ” + x);

      x = y % z;

      System.out.println(“% operator resulted in ” + x);

      x = y++;

      System.out.println(“Postfix ++ operator resulted in ” + x);

      x = ++z;

      System.out.println(“Prefix ++ operator resulted in ” + x);

      x = -y;

      System.out.println(“Unary operator resulted in ” + x);

      // Some examples of special Cases

      int tooBig = Integer.MAX_VALUE + 1; // -2147483648 which is

      // Integer.MIN_VALUE.

      int tooSmall = Integer.MIN_VALUE – 1; // 2147483647 which is

      // Integer.MAX_VALUE.

      System.out.println(“tooBig becomes ” + tooBig);

      System.out.println(“tooSmall becomes ” + tooSmall);

      System.out.println(4.0 / 0.0); // Prints: Infinity

      System.out.println(-4.0 / 0.0); // Prints: -Infinity

      System.out.println(0.0 / 0.0); // Prints: NaN

double d1 = 12 / 8; // result: 1 by integer division. d1 gets the value

      // 1.0.

      double d2 = 12.0F / 8; // result: 1.5

      System.out.println(“d1 is ” + d1);

      System.out.println(“d2 iss ” + d2);

      }

      public static void main(String args[]) {

      new ArithmeticOperatorsDemo();

      } }

Relational operators: Relational operators in Java are used to compare 2 or more objects. Java provides six relational operators:
greater than (>), less than (<), greater than or equal (>=), less than or equal (<=), equal (==), and not equal (!=).
All relational operators are binary operators, and their operands are numeric expressions.
Binary numeric promotion is applied to the operands of these operators. The evaluation results in a boolean value. Relational operators have precedence lower than arithmetic operators, but higher than that of the assignment operators. An example program is shown below that demonstrates the different relational operators in java.

 public class RelationalOperatorsDemo {     public RelationalOperatorsDemo( ) {       int x = 10, y = 5;

      System.out.println(“x > y : “+(x > y));

      System.out.println(“x < y : “+(x < y));

      System.out.println(“x >= y : “+(x >= y));

      System.out.println(“x <= y : “+(x <= y));

      System.out.println(“x == y : “+(x == y));

      System.out.println(“x != y : “+(x != y));

    }

   public static void main(String args[]){

                new RelationalOperatorsDemo();

   }}

Logical operators:Logical operators return a true or false value based on the state of the Variables. There are six logical, or boolean, operators. They are AND, conditional AND, OR, conditional OR, exclusive OR, and NOT. Each argument to a logical operator must be a boolean data type, and the result is always a boolean data type. An example program is shown below that demonstrates the different Logical operators in java.

public class LogicalOperatorsDemo {       public LogicalOperatorsDemo() {            boolean x = true;

            boolean y = false;

            System.out.println(“x & y : ” + (x & y));

            System.out.println(“x && y : ” + (x && y));

            System.out.println(“x | y : ” + (x | y));

            System.out.println(“x || y: ” + (x || y));

            System.out.println(“x ^ y : ” + (x ^ y));

            System.out.println(“!x : ” + (!x));

      }

      public static void main(String args[]) {

            new LogicalOperatorsDemo();

      }}

Given that x and y represent boolean expressions, the boolean logical operators are defined in the Table below.

x

y

!x

x & y

x && y

x | y

x || y

x ^ y

true true false true true false
true false false false true true
false true true false true true
false false true false false false

Bitwise operators:

Java provides Bit wise operators to manipulate the contents of variables at the bit level.
These variables must be of numeric data type ( char, short, int, or long). Java provides seven bitwise
operators. They are AND, OR, Exclusive-OR, Complement, Left-shift, Signed Right-shift, and Unsigned Right-shift. An example program is shown below that demonstrates the different Bit wise operators in java.

public class BitwiseOperatorsDemo {       public BitwiseOperatorsDemo() {            int x = 0xFAEF; //1 1 1 1 1 0 1 0 1 1 1 0 1 1 1 1

            int y = 0xF8E9; //1 1 1 1 1 0 0 0 1 1 1 0 1 0 0 1

            int z;

            System.out.println(“x & y : ” + (x & y));

            System.out.println(“x | y : ” + (x | y));

            System.out.println(“x ^ y : ” + (x ^ y));

            System.out.println(“~x : ” + (~x));

            System.out.println(“x << y : ” + (x << y));

            System.out.println(“x >> y : ” + (x >> y));

            System.out.println(“x >>> y : ” + (x >>> y));

            //There is no unsigned left shift operator

      }

      public static void main(String args[]) {

            new BitwiseOperatorsDemo();

      } }

The result of applying bitwise operators between two corresponding bits in the operands is shown in the Table below.

A

B

~A

A & B

A | B

A ^ B

1 1 0 1 1 0
1 0 0 0 1 1
0 1 1 0 1 1
0 0 1 0 0 0

Output

3,0,3

/* * The below program demonstrates bitwise operators keeping in mind operator precedence * Operator Precedence starting with the highest is -> |, ^, &

*/

 

public class BitwisePrecedenceEx {

       public static void main(String[] args) {

            int a = 1 | 2 ^ 3 & 5;

            int b = ((1 | 2) ^ 3) & 5;

            int c = 1 | (2 ^ (3 & 5));

            System.out.print(a + “,” + b + “,” + c);

      }}

Compound operators: The compound operators perform shortcuts in common programming operations. Java has eleven compound assignment operators.
Syntax:

argument1 operator = argument2.

The above statement is the same as, argument1 = argument1 operator argument2. An example program is shown below that demonstrates the different Compound operators in java.

public class CompoundOperatorsDemo {       public CompoundOperatorsDemo() {      int x = 0, y = 5;

      x += 3;

      System.out.println(“x : ” + x);

      y *= x;

      System.out.println(“y :  ” + y);

/*Similarly other operators can be applied as shortcuts. Other

       compound assignment operators include boolean logical

             , bitwiseand shift operators*/

      }

      public static void main(String args[]) {

            new CompoundOperatorsDemo();

      } }

Conditional operators: The Conditional operator is the only ternary (operator takes three arguments) operator in Java. The operator evaluates the first argument and, if true, evaluates the second argument. If the first argument evaluates to false, then the third argument is evaluated. The conditional operator is the expression equivalent of the if-else statement. The conditional expression can be nested and the conditional operator associates from right to left: (a?b?c?d:e:f:g) evaluates as (a?(b?(c?d:e):f):g)

An example program is shown below that demonstrates the Ternary operator in java.

public class TernaryOperatorsDemo {       public TernaryOperatorsDemo() {            int x = 10, y = 12, z = 0;

            z = x > y ? x : y;

            System.out.println(“z : ” + z);

      }

      public static void main(String args[]) {

            new TernaryOperatorsDemo();

      }}

 /*

* The following programs shows that when no explicit parenthesis is used then the conditional operator * evaluation is from right to left

*/

public class BooleanEx1 {

      static String m1(boolean b) {

            return b ? “T” : “F”;

      }

      public static void main(String[] args) {

            boolean t1 = false ? false : true ? false : true ? false : true;

            boolean t2 = false ? false

                        : (true ? false : (true ? false : true));

            boolean t3 = ((false ? false : true) ? false : true) ? false

                        : true;

            System.out.println(m1(t1) + m1(t2) + m1(t3));

      }}

Output

FFT

Type conversion allows a value to be changed from one primitive data type to another. Conversion can occur explicitly, as specified in
the program, or implicitly, by Java itself. Java allows both type widening and type narrowing conversions.

In java Conversions can occur by the following ways:

  • Using a cast operator (explicit promotion)
  • Using an arithmetic operator is used with arguments of different data types (arithmetic promotion)
  • A value of one type is assigned to a variable of a different type (assignment promotion)

Operator Precedence: The order in which operators are applied is known as precedence. Operators with a higher precedence are applied before operators with a lower precedence. The operator precedence order of Java is shown below. Operators at the top of the table are applied before operators lower down in the table. If two operators have the same precedence, they are applied in the order they appear in a statement.
That is, from left to right. You can use parentheses to override the default precedence.

postfix

[] . () expr++ expr–

unary

++expr –expr +expr -expr ! ~

creation/caste

new (type)expr

multiplicative

* / %

additive

+ –

shift

>> >>>

relational

< <= > >= instanceof

equality

== !=

bitwise AND

&

bitwise exclusive OR

^

bitwise inclusive OR

|

logical AND

&&

logical OR

||

ternary

?:

assignment

= “op=”

 

 Example

In an operation such as,

result = 4 + 5 * 3

First (5 * 3) is evaluated and the result is added to 4 giving the Final Result value as 19. Note that ‘*’ takes higher precedence than ‘+’ according to chart shown above. This kind of precedence of one operator over another applies to all the operators.

how to generate a random number between 1 to x, x being a whole number greater than 1

Ans: double result = x * Math.random();

Java Control statements: control the order of execution in a java program, based on data values and conditional logic. There are three main categories of control flow statements;

· Selection statements: if, if-else and switch.

· Loop statements: while, do-while and for.

· Transfer statements: break, continue, return, try-catch-finally and assert.

We use control statements when we want to change the default sequential order of execution

Selection Statements:

The If Statement:

The if statement executes a block of code only if the specified expression is true. If the value is false, then the if block is skipped and execution continues with the rest of the program. You can either have a single statement or a block of code within an if statement. Note that the conditional expression must be a Boolean expression.

The simple if statement has the following syntax:

if (<conditional expression>)
<statement action>

Below is an example that demonstrates conditional execution based on if statement condition.

public class IfStatementDemo {       public static void main(String[] args) {

<font size=-1>

 

            int a = 10, b = 20;

            if (a > b)

                  System.out.println(“a > b”);

            if (a < b)

                  System.out.println(“b > a”);

      }

}

Output

b > a

 

 

The If-else Statement:

The if/else statement is an extension of the if statement. If the statements in the if statement fails, the statements in the else block are executed. You can either have a single statement or a block of code within if-else blocks. Note that the conditional expression must be a Boolean expression.

The if-else statement has the following syntax:

if (<conditional expression>)
<statement action>
else
<statement action>

Below is an example that demonstrates conditional execution based on if else statement condition.

public class IfElseStatementDemo {       public static void main(String[] args) {

            int a = 10, b = 20;

            if (a > b) {

                  System.out.println(“a > b”);

            } else {

                  System.out.println(“b > a”);

            }

      }

}

Output

b > a

Switch Case Statement:The switch case statement, also called a case statement is a multi-way branch with several choices. A switch is easier to implement than a series of if/else statements. The switch statement begins with a keyword, followed by an expression that equates to a no long integral value. Following the controlling expression is a code block that contains zero or more labeled cases. Each label must equate to an integer constant and each must be unique. When the switch statement executes, it compares the value of the controlling expression to the values of each case label. The program will select the value of the case label that equals the value of the controlling expression and branch down that path to the end of the code block. If none of the case label values match, then none of the codes within the switch statement code block will be executed. Java includes a default label to use in cases where there are no matches. We can have a nested switch within a case block of an outer switch.

Its general form is as follows:

switch (<non-long integral expression>) {
caselabel1:<statement1>
caselabel2:<statement2>

caselabeln:<statementn>
default: <statement>
} // end switch

When executing a switch statement, the program falls through to the next case. Therefore, if you want to exit in the middle of the switch statement code block, you must insert a break statement, which causes the program to continue executing after the current code block.

Below is a java example that demonstrates conditional execution based on nested if else statement condition to find the greatest of 3 numbers.

public class SwitchCaseStatementDemo {       public static void main(String[] args) {

            int a = 10, b = 20, c = 30;

            int status = -1;

            if (a > b && a > c) {

                  status = 1;

            } else if (b > c) {

                  status = 2;

            } else {

                  status = 3;

            }

            switch (status) {

            case 1:

                  System.out.println(“a is the greatest”);

                  break;

            case 2:

                  System.out.println(“b is the greatest”);

                  break;

            case 3:

                  System.out.println(“c is the greatest”);

                  break;

            default:

                  System.out.println(“Cannot be determined”);

            }

      }

}

Output

c is the greatest

Control statements control the order of execution in a java program, based on data values and conditional logic.
There are three main categories of control flow statements;

Selection statements: if, if-else and switch.

Loop statements: while, do-while and for.

Transfer statements: break, continue, return, try-catch-finally and assert.

We use control statements when we want to change the default sequential order of execution

Iteration Statements

While Statement:

The while statement is a looping construct control statement that executes a block of code while a condition is true. You can either have a single statement or a block of code within the while loop. The loop will never be executed if the testing expression evaluates to false. The loop condition must be a boolean expression.

The syntax of the while loop is

while (<loop condition>)
<statements>

 

Below is an example that demonstrates the looping construct namely while loop used to print numbers from 1 to 10.

public class WhileLoopDemo {       public static void main(String[] args) {

            int count = 1;

            System.out.println(“Printing Numbers from 1 to 10”);

            while (count <= 10) {

                  System.out.println(count++);

            }

      }

}

Output

Printing Numbers from 1 to 10
1
2
3
4
5
6
7
8
9
10

Do-while Loop Statement:

The do-while loop is similar to the while loop, except that the test is performed at the end of the loop instead of at the beginning. This ensures that the loop will be executed at least once. A do-while loop begins with the keyword do, followed by the statements that make up the body of the loop. Finally, the keyword while and the test expression completes the do-while loop. When the loop condition becomes false, the loop is terminated and execution continues with the statement immediately following the loop. You can either have a single statement or a block of code within the do-while loop.

The syntax of the do-while loop is

do
<loop body>
while (<loop condition>);

Below is an example that demonstrates the looping construct namely do-while loop used to print numbers from 1 to 10.

public class DoWhileLoopDemo {       public static void main(String[] args) {

            int count = 1;

            System.out.println(“Printing Numbers from 1 to 10”);

            do {

                  System.out.println(count++);

            } while (count <= 10);

      }

}

Output

Printing Numbers from 1 to 10
1
2
3
4
5
6
7
8
9
10

Below is an example that creates A Fibonacci sequence controlled by a do-while loop

public class Fibonacci {       public static void main(String args[]) {

            System.out.println(“Printing Limited set of Fibonacci Sequence”);

            double fib1 = 0;

            double fib2 = 1;

            double temp = 0;

            System.out.println(fib1);

            System.out.println(fib2);

            do {

                  temp = fib1 + fib2;

                  System.out.println(temp);

                  fib1 = fib2; //Replace 2nd with first number

                  fib2 = temp; //Replace temp number with 2nd number

            } while (fib2 < 5000);

      }

}

Output

Printing Limited set of Fibonacci Sequence

0.0
1.0
1.0
2.0
3.0
5.0
8.0
13.0
21.0
34.0
55.0
89.0
144.0
233.0
377.0
610.0
987.0
1597.0
2584.0
4181.0
6765.0

For Loops:

The for loop is a looping construct which can execute a set of instructions a specified number of times. It’s a counter controlled loop.

The syntax of the loop is as follows:

for (<initialization>; <loop condition>; <increment expression>)
<loop body>

The first part of a for statement is a starting initialization, which executes once before the loop begins. The <initialization> section can also be a comma-separated list of expression statements. The second part of a for statement is a test expression. As long as the expression is true, the loop will continue. If this expression is evaluated as false the first time, the loop will never be executed. The third part of the for statement is the body of the loop. These are the instructions that are repeated each time the program executes the loop. The final part of the for statement is an increment expression that automatically executes after each repetition of the loop body. Typically, this statement changes the value of the counter, which is then tested to see if the loop should continue.
All the sections in the for-header are optional. Any one of them can be left empty, but the two semicolons are mandatory. In particular, leaving out the <loop condition> signifies that the loop condition is true. The (;;) form of for loop is commonly used to construct an infinite loop.

Below is an example that demonstrates the looping construct namely for loop used to print numbers from 1 to 10.

public class ForLoopDemo {       public static void main(String[] args) {

            System.out.println(“Printing Numbers from 1 to 10”);

            for (int count = 1; count <= 10; count++) {

                  System.out.println(count);

            }

      }

}

Output

Printing Numbers from 1 to 10
1
2
3
4
5
6
7
8
9
10

Control statements control the order of execution in a java program, based on data values and conditional logic. There are three main categories of control flow statements;

Selection statements: if, if-else and switch.

Loop statements: while, do-while and for.

Transfer statements: break, continue, return, try-catch-finally and assert.

We use control statements when we want to change the default sequential order of execution

 

Transfer Statements:

Continue Statement:

A continue statement stops the iteration of a loop (while, do or for) and causes execution to resume at the top of the nearest enclosing loop. You use a continue statement when you do not want to execute the remaining statements in the loop, but you do not want to exit the loop itself.

The syntax of the continue statement is

continue; // the unlabeled form
continue <label>; // the labeled form

You can also provide a loop with a label and then use the label in your continue statement. The label name is optional, and is usually only used when you wish to return to the outermost loop in a series of nested loops.

Below is a program to demonstrate the use of continue statement to print Odd Numbers between 1 to 10.

public class ContinueExample {       public static void main(String[] args) {

            System.out.println(“Odd Numbers”);

            for (int i = 1; i <= 10; ++i) {

                  if (i % 2 == 0)

                        continue;

                  // Rest of loop body skipped when i is even

                  System.out.println(i + “\t”);

            }

      }

}

Output

Odd Numbers
1
3
5
7
9

Break Statement:

The break statement transfers control out of the enclosing loop ( for, while, do or switch statement). You use a break statement when you want to jump immediately to the statement following the enclosing control structure. You can also provide a loop with a label, and then use the label in your break statement. The label name is optional, and is usually only used when you wish to terminate the outermost loop in a series of nested loops.

The Syntax for break statement is as shown below;

break; // the unlabeled form
break <label>; // the labeled form

Below is a program to demonstrate the use of break statement to print numbers Numbers 1 to 10.

public class BreakExample {       public static void main(String[] args) {

            System.out.println(“Numbers 1 – 10”);

            for (int i = 1;; ++i) {

                  if (i == 11)

                        break;

                  // Rest of loop body skipped when i is even

                  System.out.println(i + “\t”);

            }

      }

}

Output

Numbers 1 – 10
1
2
3
4
5
6
7
8
9
10

Java Access Specifiers:

The access to classes, constructors, methods and fields are regulated using access modifiers i.e. a class can control what information or data can be accessible by other classes. To take advantage of encapsulation, you should minimize access whenever possible.

Java provides a number of access modifiers to help you set the level of access you want for classes as well as the fields, methods and constructors in your classes. A member has package or default accessibility when no accessibility modifier is specified.

Access Modifiers

1. private
2. protected
3. default
4. public

public access modifier

Fields, methods and constructors declared public (least restrictive) within a public class are visible to any class in the Java program, whether these classes are in the same package or in another package.

private access modifier

The private (most restrictive) fields or methods cannot be used for classes and Interfaces. It also cannot be used for fields and methods within an interface. Fields, methods or constructors declared private are strictly controlled, which means they cannot be accesses by anywhere outside the enclosing class. A standard design strategy is to make all fields private and provide public getter methods for them.

protected access modifier

The protected fields or methods cannot be used for classes and Interfaces. It also cannot be used for fields and methods within an interface. Fields, methods and constructors declared protected in a superclass can be accessed only by subclasses in other packages. Classes in the same package can also access protected fields, methods and constructors as well, even if they are not a subclass of the protected member’s class.

default access modifier

Java provides a default specifier which is used when no access modifier is present. Any class, field, method or constructor that has no declared access modifier is accessible only by classes in the same package. The default modifier is not used for fields and methods within an interface.

Below is a program to demonstrate the use of public, private, protected and default access modifiers while accessing fields and methods. The output of each of these java files depict the Java access specifiers.

The first class is SubclassInSamePackage.java which is present in pckage1 package. This java file contains the Base class and a subclass within the enclosing class that belongs to the same class as shown below.

package pckage1; class BaseClass {

 

      public int x = 10;

      private int y = 10;

      protected int z = 10;

      int a = 10; //Implicit Default Access Modifier

      public int getX() {

            return x;

      }

      public void setX(int x) {

            this.x = x;

      }

      private int getY() {

            return y;

      }

      private void setY(int y) {

            this.y = y;

      }

      protected int getZ() {

            return z;

      }

      protected void setZ(int z) {

            this.z = z;

      }

      int getA() {

            return a;

      }

      void setA(int a) {

            this.a = a;

      }

}

 

public class SubclassInSamePackage extends BaseClass {

 

      public static void main(String args[]) {

      BaseClass rr = new BaseClass();

      rr.z = 0;

      SubclassInSamePackage subClassObj = new SubclassInSamePackage();

      //Access Modifiers – Public

      System.out.println(“Value of x is : ” + subClassObj.x);

      subClassObj.setX(20);

      System.out.println(“Value of x is : ” + subClassObj.x);

      //Access Modifiers – Public

      //          If we remove the comments it would result in a compilaton

      //          error as the fields and methods being accessed are private

      /*          System.out.println(“Value of y is : “+subClassObj.y);

 

      subClassObj.setY(20);

 

      System.out.println(“Value of y is : “+subClassObj.y);*/

      //Access Modifiers – Protected

      System.out.println(“Value of z is : ” + subClassObj.z);

      subClassObj.setZ(30);

      System.out.println(“Value of z is : ” + subClassObj.z);

      //Access Modifiers – Default

      System.out.println(“Value of x is : ” + subClassObj.a);

      subClassObj.setA(20);

      System.out.println(“Value of x is : ” + subClassObj.a);

      }

}

Output

Value of x is : 10
Value of x is : 20
Value of z is : 10
Value of z is : 30
Value of x is : 10
Value of x is : 20

The second class is SubClassInDifferentPackage.java which is present in a different package then the first one. This java class extends First class (SubclassInSamePackage.java).

import pckage1.*; public class SubClassInDifferentPackage extends SubclassInSamePackage {

 

      public int getZZZ() {

            return z;

      }

 

      public static void main(String args[]) {

            SubClassInDifferentPackage subClassDiffObj = new SubClassInDifferentPackage();

      SubclassInSamePackage subClassObj = new SubclassInSamePackage();

      //Access specifiers – Public

      System.out.println(“Value of x is : ” + subClassObj.x);

      subClassObj.setX(30);

      System.out.println(“Value of x is : ” + subClassObj.x);

      //Access specifiers – Private

      //      if we remove the comments it would result in a compilaton

      //      error as the fields and methods being accessed are private

      /*      System.out.println(“Value of y is : “+subClassObj.y);

 

      subClassObj.setY(20);

 

      System.out.println(“Value of y is : “+subClassObj.y);*/

      //Access specifiers – Protected

      //      If we remove the comments it would result in a compilaton

      //      error as the fields and methods being accessed are protected.

      /*      System.out.println(“Value of z is : “+subClassObj.z);

 

      subClassObj.setZ(30);

 

      System.out.println(“Value of z is : “+subClassObj.z);*/

      System.out.println(“Value of z is : ” + subClassDiffObj.getZZZ());

      //Access Modifiers – Default

      // If we remove the comments it would result in a compilaton

      // error as the fields and methods being accessed are default.

            /*

 

      System.out.println(“Value of a is : “+subClassObj.a);

 

      subClassObj.setA(20);

 

      System.out.println(“Value of a is : “+subClassObj.a);*/

      }

}

Output

Value of x is : 10
Value of x is : 30
Value of z is : 10

The third class is ClassInDifferentPackage.java which is present in a different package then the first one.

import pckage1.*; public class ClassInDifferentPackage {

 

      public static void main(String args[]) {

      SubclassInSamePackage subClassObj = new SubclassInSamePackage();

      //Access Modifiers – Public

      System.out.println(“Value of x is : ” + subClassObj.x);

      subClassObj.setX(30);

      System.out.println(“Value of x is : ” + subClassObj.x);

      //Access Modifiers – Private

      //      If we remove the comments it would result in a compilaton

      //      error as the fields and methods being accessed are private

      /*      System.out.println(“Value of y is : “+subClassObj.y);

 

      subClassObj.setY(20);

 

      System.out.println(“Value of y is : “+subClassObj.y);*/

      //Access Modifiers – Protected

      //      If we remove the comments it would result in a compilaton

      //      error as the fields and methods being accessed are protected.

      /*      

       System.out.println(“Value of z is : “+subClassObj.z);

 

      subClassObj.setZ(30);

 

      System.out.println(“Value of z is : “+subClassObj.z);*/

      //Access Modifiers – Default

      //      If we remove the comments it would result in a compilaton

      //      error as the fields and methods being accessed are default.

      /*      System.out.println(“Value of a is : “+subClassObj.a);

 

      subClassObj.setA(20);

 

      System.out.println(“Value of a is : “+subClassObj.a);*/

      }

}

 

Output

Value of x is : 10
Value of x is : 30

 

Introduction to Java Classes

A class is nothing but a blueprint or a template for creating different objects which defines its properties and behaviors. Java class objects exhibit the properties and behaviors defined by its class. A class can contain fields and methods to describe the behavior of an object.

Methods are nothing but members of a class that provide a service for an object or perform some business logic. Java fields and member functions names are case sensitive. Current states of a class’s corresponding object are stored in the object’s instance variables. Methods define the operations that can be performed in java programming.

A class has the following general syntax:

<class modifiers>class<class name>
<extends clause> <implements clause>{

// Dealing with Classes (Class body)

<field declarations (Static and Non-Static)>
<method declarations (Static and Non-Static)>
<Inner class declarations>
<nested interface declarations>
<constructor declarations>
<Static initializer blocks>
}

Below is an example showing the Objects and Classes of the Cube class that defines 3 fields namely length, breadth and height. Also the class contains a member function getVolume().

public class Cube {       int length;

      int breadth;

      int height;

      public int getVolume() {

            return (length * breadth * height);

      }

}

How do you reference a data member/function?

This is accomplished by stating the name of the object reference, followed by a period (dot), followed by the name of the member inside the object.
( objectReference.member ). You call a method for an object by naming the object followed by a period (dot), followed by the name of the method and its argument list, like this: objectName.methodName(arg1, arg2, arg3).

For example:

cubeObject.length = 4;
cubeObject.breadth = 4;
cubeObject.height = 4;
cubeObject.getvolume()

Class Variables – Static Fields

We use class variables also know as Static fields when we want to share characteristics across all objects within a class. When you declare a field to be static, only a single instance of the associated variable is created common to all the objects of that class. Hence when one object changes the value of a class variable, it affects all objects of the class. We can access a class variable by using the name of the class, and not necessarily using a reference to an individual object within the class. Static variables can be accessed even though no objects of that class exist. It is declared using static keyword.

Class Methods – Static Methods

Class methods, similar to Class variables can be invoked without having an instance of the class. Class methods are often used to provide global functions for Java programs. For example, methods in the java.lang.Math package are class methods. You cannot call non-static methods from inside a static method.

Instance Variables

Instance variables stores the state of the object. Each class would have its own copy of the variable. Every object has a state that is determined by the values stored in the object. An object is said to have changed its state when one or more data values stored in the object have been modified. When an object responds to a message, it will usually perform an action, change its state etc. An object that has the ability to store values is often said to have persistence.

Consider this simple Java program showing the use of static fields and static methods

// Class and Object initialization showing the Object Oriented concepts in Javaclass Cube { 

        int length = 10;

        int breadth = 10;

        int height = 10;

        public static int numOfCubes = 0; // static variable

        public static int getNoOfCubes() { //static method

               return numOfCubes;

        }

        public Cube() {

               numOfCubes++; //

        }

}

 

public class CubeStaticTest {

 

        public static void main(String args[]) {

               System.out.println(“Number of Cube objects = ” + Cube.numOfCubes);

               System.out.println(“Number of Cube objects = “

                               + Cube.getNoOfCubes());

        }

}

Output

Number of Cube objects = 0
Number of Cube objects = 0

Final Variable, Methods and Classes

In Java we can mark fields, methods and classes as final. Once marked as final, these items cannot be changed.

Variables defined in an interface are implicitly final. You can’t change value of a final variable (is a constant). A final class can’t be extended i.e., final class may not be subclassed. This is done for security reasons with basic classes like String and Integer. It also allows the compiler to make some optimizations, and makes thread safety a little easier to achieve. A final method can’t be overridden when its class is inherited. Any attempt to override or hide a final method will result in a compiler error.

Introduction to Java Objects

The Object Class is the super class for all classes in Java.

Some of the object class methods are

equals
toString()
wait()
notify()
notifyAll()
hashcode()
clone()

An object is an instance of a class created using a new operator. The new operator returns a reference to a new instance of a class. This reference can be assigned to a reference variable of the class. The process of creating objects from a class is called instantiation. An object encapsulates state and behavior.

An object reference provides a handle to an object that is created and stored in memory. In Java, objects can only be manipulated via references, which can be stored in variables.

Creating variables of your class type is similar to creating variables of primitive data types, such as integer or float. Each time you create an object, a new set of instance variables comes into existence which defines the characteristics of that object. If you want to create an object of the class and have the reference variable associated with this object, you must also allocate memory for the object by using the new operator. This process is called instantiating an object or creating an object instance.

When you create a new object, you use the new operator to instantiate the object. The new operator returns the location of the object which you assign o a reference type.

Below is an example showing the creation of Cube objects by using the new operator.

public class Cube {       int length = 10;

      int breadth = 10;

      int height = 10;

      public int getVolume() {

            return (length * breadth * height);

      }

      public static void main(String[] args) {

            Cube cubeObj; // Creates a Cube Reference

            cubeObj = new Cube(); // Creates an Object of Cube

            System.out.println(“Volume of Cube is : ” + cubeObj.getVolume());

      }

}

Download Cube.java

Method Overloading

Method overloading results when two or more methods in the same class have the same name but different parameters. Methods with the same name must differ in their types or number of parameters. This allows the compiler to match parameters and choose the correct method when a number of choices exist. Changing just the return type is not enough to overload a method, and will be a compile-time error. They must have a different signature. When no method matching the input parameters is found, the compiler attempts to convert the input parameters to types of greater precision. A match may then be found without error. At compile time, the right implementation is chosen based on the signature of the method call

Below is an example of a class demonstrating Method Overloading

 public class MethodOverloadDemo { 

      void sumOfParams() { // First Version

            System.out.println(“No parameters”);

      }

      void sumOfParams(int a) { // Second Version

            System.out.println(“One parameter: ” + a);

      }

      int sumOfParams(int a, int b) { // Third Version

            System.out.println(“Two parameters: ” + a + ” , ” + b);

            return a + b;

      }

      double sumOfParams(double a, double b) { // Fourth Version

            System.out.println(“Two double parameters: ” + a + ” , ” + b);

            return a + b;

      }

      public static void main(String args[]) {

            MethodOverloadDemo moDemo = new MethodOverloadDemo();

            int intResult;

            double doubleResult;

            moDemo.sumOfParams();

            System.out.println();

            moDemo.sumOfParams(2);

            System.out.println();

            intResult = moDemo.sumOfParams(10, 20);

            System.out.println(“Sum is  ” + intResult);

            System.out.println();

            doubleResult = moDemo.sumOfParams(1.1, 2.2);

            System.out.println(“Sum is  ” + doubleResult);

            System.out.println();

      }

}

Download MethodOverloadDemo.java

Output

No parameters

One parameter: 2

Two parameters: 10 , 20
Sum is 30

Two double parameters: 1.1 , 2.2
Sum is 3.3000000000000003

Below is a code snippet to shows the interfaces that a Class Implements:

Class cls = java.lang.String.class;Class[] intfs = cls.getInterfaces();// [java.lang.Comparable, java.lang.CharSequence, java.io.Serializable]

// The interfaces for a primitive type is an empty array

cls = int.class;

intfs = cls.getInterfaces(); // []

Below is a code snippet to show whether a Class Object Represents a Class or Interface:

Class cls = java.lang.String.class;boolean isClass = !cls.isInterface(); // truecls = java.lang.Cloneable.class;

isClass = !cls.isInterface(); // false

Java Constructor:

A java constructor has the same name as the name of the class to which it belongs. Constructor’s syntax does not include a return type, since constructors never return a value.

Constructors may include parameters of various types. When the constructor is invoked using the new operator, the types must match those that are specified in the constructor definition.

Java provides a default constructor which takes no arguments and performs no special actions or initializations, when no explicit constructors are provided.

The only action taken by the implicit default constructor is to call the superclass constructor using the super() call. Constructor arguments provide you with a way to provide parameters for the initialization of an object.

Below is an example of a cube class containing 2 constructors. (one default and one parameterized constructor).

public class Cube1 {         int length;

        int breadth;

        int height;

        public int getVolume() {

               return (length * breadth * height);

        }

        Cube1() {

               length = 10;

               breadth = 10;

               height = 10;

        }

        Cube1(int l, int b, int h) {

               length = l;

               breadth = b;

               height = h;

        }

        public static void main(String[] args) {

               Cube1 cubeObj1, cubeObj2;

               cubeObj1 = new Cube1();

               cubeObj2 = new Cube1(10, 20, 30);

<font size=-1>

 

               System.out.println(“Volume of Cube1 is : ” + cubeObj1.getVolume());

               System.out.println(“Volume of Cube1 is : ” + cubeObj2.getVolume());

        }

}

Download Cube1.java

Note: If a class defines an explicit constructor, it no longer has a default constructor to set the state of the objects.
If such a class requires a default constructor, its implementation must be provided. Any attempt to call the default constructor will be a compile time error if an explicit default constructor is not provided in such a case.

Java Overloaded Constructors

Like methods, constructors can also be overloaded. Since the constructors in a class all have the same name as the class, />their signatures are differentiated by their parameter lists. The above example shows that the Cube1 constructor is overloaded one being the default constructor and the other being a parameterized constructor.

It is possible to use this() construct, to implement local chaining of constructors in a class. The this() call in a constructorinvokes the an other constructor with the corresponding parameter list within the same class. Calling the default constructor to create a Cube object results in the second and third parameterized constructors being called as well. Java requires that any this() call must occur as the first statement in a constructor.

Below is an example of a cube class containing 3 constructors which demostrates the this() method in Constructors context

public class Cube2 {         int length;

        int breadth;

        int height;

        public int getVolume() {

               return (length * breadth * height);

        }

        Cube2() {

               this(10, 10);

               System.out.println(“Finished with Default Constructor”);

        }

        Cube2(int l, int b) {

               this(l, b, 10);

               System.out.println(“Finished with Parameterized Constructor having 2 params”);

        }

        Cube2(int l, int b, int h) {

               length = l;

               breadth = b;

               height = h;

               System.out.println(“Finished with Parameterized Constructor having 3 params”);

        }

        public static void main(String[] args) {

               Cube2 cubeObj1, cubeObj2;

               cubeObj1 = new Cube2();

               cubeObj2 = new Cube2(10, 20, 30);

               System.out.println(“Volume of Cube1 is : ” + cubeObj1.getVolume());

               System.out.println(“Volume of Cube2 is : ” + cubeObj2.getVolume());

        }

}

 

public class Cube2 {

 

        int length;

        int breadth;

        int height;

        public int getVolume() {

               return (length * breadth * height);

        }

        Cube2() {

               this(10, 10);

               System.out.println(“Finished with Default Constructor”);

        }

        Cube2(int l, int b) {

               this(l, b, 10);

               System.out.println(“Finished with Parameterized Constructor having 2 params”);

        }

        Cube2(int l, int b, int h) {

               length = l;

               breadth = b;

               height = h;

               System.out.println(“Finished with Parameterized Constructor having 3 params”);

        }

        public static void main(String[] args) {

               Cube2 cubeObj1, cubeObj2;

               cubeObj1 = new Cube2();

               cubeObj2 = new Cube2(10, 20, 30);

               System.out.println(“Volume of Cube1 is : ” + cubeObj1.getVolume());

               System.out.println(“Volume of Cube2 is : ” + cubeObj2.getVolume());

        }

}

Output

Finished with Parameterized Constructor having 3 params
Finished with Parameterized Constructor having 2 params
Finished with Default Constructor
Finished with Parameterized Constructor having 3 params
Volume of Cube1 is : 1000
Volume of Cube2 is : 6000

Download Cube2.java

Constructor Chaining

Every constructor calls its superclass constructor. An implied super() is therefore included in each constructor which does not include either the this() function or an explicit super() call as its first statement. The super() statement invokes a constructor of the super class.
The implicit super() can be replaced by an explicit super(). The super statement must be the first statement of the constructor.
The explicit super allows parameter values to be passed to the constructor of its superclass and must have matching parameter types A super() call in the constructor of a subclass will result in the call of the relevant constructor from the superclass, based on the signature of the call. This is called constructor chaining.

Below is an example of a class demonstrating constructor chaining using super() method.

class Cube {         int length;

        int breadth;

        int height;

        public int getVolume() {

               return (length * breadth * height);

        }

        Cube() {

               this(10, 10);

               System.out.println(“Finished with Default Constructor of Cube”);

        }

        Cube(int l, int b) {

               this(l, b, 10);

               System.out.println(“Finished with Parameterized Constructor having

                                                                     2 params of Cube”);

        }

        Cube(int l, int b, int h) {

               length = l;

               breadth = b;

               height = h;

               System.out.println(“Finished with Parameterized Constructor having

                                                                     3 params of Cube”);

        }

}

 

public class SpecialCube extends Cube {

 

        int weight;

        SpecialCube() {

               super();

               weight = 10;

        }

        SpecialCube(int l, int b) {

               this(l, b, 10);

               System.out.println(“Finished with Parameterized Constructor having

                                                                     2 params of SpecialCube”);

        }

        SpecialCube(int l, int b, int h) {

               super(l, b, h);

               weight = 20;

               System.out.println(“Finished with Parameterized Constructor having

                                                                     3 params of SpecialCube”);

        }

        public static void main(String[] args) {

               SpecialCube specialObj1 = new SpecialCube();

               SpecialCube specialObj2 = new SpecialCube(10, 20);

               System.out.println(“Volume of SpecialCube1 is : “

                               + specialObj1.getVolume());

               System.out.println(“Weight of SpecialCube1 is : “

                               + specialObj1.weight);

               System.out.println(“Volume of SpecialCube2 is : “

                               + specialObj2.getVolume());

               System.out.println(“Weight of SpecialCube2 is : “

                               + specialObj2.weight);

        }

}

Download SpecialCube.java

Output

Finished with Parameterized Constructor having 3 params of SpecialCube
Finished with Parameterized Constructor having 2 params of SpecialCube
Volume of SpecialCube1 is : 1000
Weight of SpecialCube1 is : 10
Volume of SpecialCube2 is : 2000
Weight of SpecialCube2 is : 20

The super() construct as with this() construct: if used, must occur as the first statement in a constructor, and it can only be used in a constructor declaration. This implies that this() and super() calls cannot both occur in the same constructor. Just as the this() construct leads to chaining of constructors in the same class, the super() construct leads to chaining of subclass constructors to superclass constructors.
if a constructor has neither a this() nor a super() construct as its first statement, then a super() call to the default constructor in the superclass is inserted.

Note: If a class only defines non-default constructors, then its subclasses will not include an implicit super() call. This will be flagged as a compile-time error. The subclasses must then explicitly call a superclass constructor, using the super() construct with the right arguments to match the appropriate constructor of the superclass.

Below is an example of a class demonstrating constructor chaining using explicit super() call.

class Cube {         int length;

        int breadth;

        int height;

        public int getVolume() {

               return (length * breadth * height);

        }

        Cube(int l, int b, int h) {

               length = l;

               breadth = b;

               height = h;

               System.out.println(“Finished with Parameterized Constructor having

                                                             3 params of Cube”);

        }

}

 

public class SpecialCube1 extends Cube {

 

        int weight;

        SpecialCube1() {

               super(10, 20, 30); //Will Give a Compilation Error without this line

               weight = 10;

        }

        public static void main(String[] args) {

               SpecialCube1 specialObj1 = new SpecialCube1();

               System.out.println(“Volume of SpecialCube1 is : “+ specialObj1.getVolume());

        }

}

Output

Finished with Parameterized Constructor having 3 params of Cube
Volume of SpecialCube1 is : 6000

Download SpecialCube1.java

Introduction to Object Serialization

Java object serialization is used to persist Java objects to a file, database, network, process or any other system. Serialization flattens objects into an ordered, or serialized stream of bytes. The ordered stream of bytes can then be read at a later time, or in another environment, to recreate the original objects.

Java serialization does not cannot occur for transient or static fields. Marking the field transient prevents the state from being written to the stream and from being restored during deserialization. Java provides classes to support writing objects to streams and restoring objects from streams. Only objects that support the java.io.Serializable interface or the java.io.Externalizable interface can be written to streams.
public interface Serializable

  • The Serializable interface has no methods or fields. (Marker Interface)
  • Only objects of classes that implement java.io.Serializable interface can be serialized or deserialized

Transient Fields and Java Serialization

The transient keyword is a modifier applied to instance variables in a class. It specifies that the variable is not part of the persistent state of the object and thus never saved during serialization.

You can use the transient keyword to describe temporary variables, or variables that contain local information,

<br /><font size=-1>

such as a process ID or a time lapse.

Input and Output Object Streams

ObjectOutputStream is the primary output stream class that implements the ObjectOutput interface for serializing objects. ObjectInputStream is the primary input stream class that implements the ObjectInput interface for deserializing objects.

These high-level streams are each chained to a low-level stream, such as FileInputStream or FileOutputStream.
The low-level streams handle the bytes of data. The writeObject method saves the state of the class by writing the individual fields to the ObjectOutputStream. The readObject method is used to deserialize the object from
the object input stream.

Case 1: Below is an example that demonstrates object Serialization into a File

PersonDetails is the bean class that implements the Serializable interface

import java.io.Serializable;public class PersonDetails implements Serializable { 

        private String name;

        private int age;

        private String sex;

        public PersonDetails(String name, int age, String sex) {

               this.name = name;

               this.age = age;

               this.sex = sex;

        }

        public int getAge() {

               return age;

        }

        public void setAge(int age) {

               this.age = age;

        }

        public String getName() {

               return name;

        }

        public void setName(String name) {

               this.name = name;

        }

        public String getSex() {

               return sex;

        }

        public void setSex(String sex) {

               this.sex = sex;

        }

}

GetPersonDetails is the class that is used to Deserialize object from the File (person.txt).

import java.io.FileInputStream;import java.io.IOException;import java.io.ObjectInputStream;

import java.util.ArrayList;

import java.util.List;

public class GetPersonDetails {

 

        public static void main(String[] args) {

               String filename = “person.txt”;

               List pDetails = null;

               FileInputStream fis = null;

               ObjectInputStream in = null;

               try {

                       fis = new FileInputStream(filename);

                       in = new ObjectInputStream(fis);

                       pDetails = (ArrayList) in.readObject();

                       in.close();

               } catch (IOException ex) {

                       ex.printStackTrace();

               } catch (ClassNotFoundException ex) {

                       ex.printStackTrace();

               }

               // print out the size

               System.out.println(“Person Details Size: ” + pDetails.size());

               System.out.println();

        }

}

PersonPersist is the class that is used to serialize object into the File (person.txt).

public class PersonPersist {         public static void main(String[] args) {

               String filename = “person.txt”;

               PersonDetails person1 = new PersonDetails(“hemanth”, 10, “Male”);

               PersonDetails person2 = new PersonDetails(“bob”, 12, “Male”);

               PersonDetails person3 = new PersonDetails(“Richa”, 10, “Female”);

               List list = new ArrayList();

               list.add(person1);

               list.add(person2);

               list.add(person3);

               FileOutputStream fos = null;

               ObjectOutputStream out = null;

               try {

                       fos = new FileOutputStream(filename);

                       out = new ObjectOutputStream(fos);

                       out.writeObject(list);

                       out.close();

                       System.out.println(“Object Persisted”);

               } catch (IOException ex) {

                       ex.printStackTrace();

               }

        }

}

——————————————————————————–

Case 2: Below is an example that demonstrates object Serialization into the database

PersonDetails remains the same as shown above

GetPersonDetails remains the same as shown above

Create SerialTest Table

create table SerialTest(
name BLOB,
viewname VARCHAR2(30)
);

PersonPersist is the class that is used to serialize object into the into the Database Table SerialTest.

import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.IOException;

import java.io.ObjectInputStream;

import java.io.ObjectOutputStream;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

public class PersonPersist {

 

        static String userid = “scott”, password = “tiger”;

        static String url = “jdbc:odbc:bob”;

        static int count = 0;

        static Connection con = null;

        public static void main(String[] args) {

               Connection con = getOracleJDBCConnection();

               PersonDetails person1 = new PersonDetails(“hemanth”, 10, “Male”);

               PersonDetails person2 = new PersonDetails(“bob”, 12, “Male”);

               PersonDetails person3 = new PersonDetails(“Richa”, 10, “Female”);

               PreparedStatement ps;

               try {

                       ps = con

                                      .prepareStatement(“INSERT INTO SerialTest VALUES (?, ?)”);

                       write(person1, ps);

                       ps.execute();

                       write(person2, ps);

                       ps.execute();

                       write(person3, ps);

                       ps.execute();

                       ps.close();

                       Statement st = con.createStatement();

                       ResultSet rs = st.executeQuery(“SELECT * FROM SerialTest”);

                       while (rs.next()) {

                               Object obj = read(rs, “Name”);

                               PersonDetails p = (PersonDetails) obj;

                               System.out.println(p.getName() + “\t” + p.getAge() + “\t”

                                              + p.getSex());

                       }

                       rs.close();

                       st.close();

               } catch (Exception e) {

               }

        }

        public static void write(Object obj, PreparedStatement ps)

                       throws SQLException, IOException {

               ByteArrayOutputStream baos = new ByteArrayOutputStream();

               ObjectOutputStream oout = new ObjectOutputStream(baos);

               oout.writeObject(obj);

               oout.close();

               ps.setBytes(1, baos.toByteArray());

               ps.setInt(2, ++count);

        }

        public static Object read(ResultSet rs, String column)

                       throws SQLException, IOException, ClassNotFoundException {

               byte[] buf = rs.getBytes(column);

               if (buf != null) {

                       ObjectInputStream objectIn = new ObjectInputStream(

                                      new ByteArrayInputStream(buf));

                       return objectIn.readObject();

               }

               return null;

        }

        public static Connection getOracleJDBCConnection() {

               try {

                       Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);

               } catch (java.lang.ClassNotFoundException e) {

                       System.err.print(“ClassNotFoundException: “);

                       System.err.println(e.getMessage());

               }

               try {

                       con = DriverManager.getConnection(url, userid, password);

               } catch (SQLException ex) {

                       System.err.println(“SQLException: ” + ex.getMessage());

               }

               return con;

        }

}

——————————————————————————–

Case 3: Below is an example that demonstrates object Serialization into the database using Base 64 Encoder

PersonDetails remains the same as shown above

GetPersonDetails remains the same as shown above

Create SerialTest Table

create table SerialTest(
name BLOB,
viewname VARCHAR2(30)
);

PersonPersist is the class that is used to serialize object into the Database Table SerialTest

import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.IOException;

import java.io.ObjectInputStream;

import java.io.ObjectOutputStream;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

public class PersonPersist {

 

        static String userid = “scott”, password = “tiger”;

        static String url = “jdbc:odbc:bob”;

        static int count = 0;

        static Connection con = null;

        static String s;

        public static void main(String[] args) {

               Connection con = getOracleJDBCConnection();

               PersonDetails person1 = new PersonDetails(“hemanth”, 10, “Male”);

               PersonDetails person2 = new PersonDetails(“bob”, 12, “Male”);

               PersonDetails person3 = new PersonDetails(“Richa”, 10, “Female”);

               PreparedStatement ps;

               try {

                       ps = con

                                      .prepareStatement(“INSERT INTO SerialTest VALUES (?, ?)”);

                       write(person1, ps);

                       ps.execute();

                       write(person2, ps);

                       ps.execute();

                       write(person3, ps);

                       ps.execute();

                       ps.close();

                       Statement st = con.createStatement();

                       ResultSet rs = st.executeQuery(“SELECT * FROM SerialTest”);

                       while (rs.next()) {

                               Object obj = read(rs, “Name”);

                               PersonDetails p = (PersonDetails) obj;

                               System.out.println(p.getName() + “\t” + p.getAge() + “\t”

                                              + p.getSex());

                       }

                       rs.close();

                       st.close();

               } catch (Exception e) {

               }

        }

        public static void write(Object obj, PreparedStatement ps)

                       throws SQLException, IOException {

               ByteArrayOutputStream baos = new ByteArrayOutputStream();

               ObjectOutputStream oout = new ObjectOutputStream(baos);

               oout.writeObject(obj);

               oout.close();

               byte[] buf = baos.toByteArray();

               s = new sun.misc.BASE64Encoder().encode(buf);

               ps.setString(1, s);

               // ps.setBytes(1, Base64.byteArrayToBase64(baos.toByteArray()));

               ps.setBytes(1, baos.toByteArray());

               ps.setInt(2, ++count);

        }

        public static Object read(ResultSet rs, String column)

                       throws SQLException, IOException, ClassNotFoundException {

               byte[] buf = new sun.misc.BASE64Decoder().decodeBuffer(s);

               // byte[] buf = Base64.base64ToByteArray(new

               // String(rs.getBytes(column)));

               if (buf != null) {

                       ObjectInputStream objectIn = new ObjectInputStream(

                                      new ByteArrayInputStream(buf));

                       Object obj = objectIn.readObject(); // Contains the object

                       PersonDetails p = (PersonDetails) obj;

                       System.out.println(p.getName() + “\t” + p.getAge() + “\t”

                                      + p.getSex());

               }

               return null;

        }

        public static Connection getOracleJDBCConnection() {

               try {

                       Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);

               } catch (java.lang.ClassNotFoundException e) {

                       System.err.print(“ClassNotFoundException: “);

                       System.err.println(e.getMessage());

               }

               try {

                       con = DriverManager.getConnection(url, userid, password);

               } catch (SQLException ex) {

                       System.err.println(“SQLException: ” + ex.getMessage());

               }

               return con;

        }

}

Below is a program that shows the serialization of a JButton object to a file and a Byte Array Stream. As before theobject to be serialized must implement the Serializable interface.

PersonDetails is the bean class that implements the Serializable interface

import java.io.ByteArrayOutputStream;import java.io.FileOutputStream;import java.io.ObjectOutput;

import java.io.ObjectOutputStream;

 

public class ObjectSerializationExample {

 

        public static void main(String args[]) {

               try {

                       Object object = new javax.swing.JButton(“Submit”);

                       // Serialize to a file namely “filename.dat”

                       ObjectOutput out = new ObjectOutputStream(

                                      new FileOutputStream(“filename.dat”));

                       out.writeObject(object);

                       out.close();

                       // Serialize to a byte array

                       ByteArrayOutputStream bos = new ByteArrayOutputStream();

                       out = new ObjectOutputStream(bos);

                       out.writeObject(object);

                       out.close();

                       // Get the bytes of the serialized object

                       byte[] buf = bos.toByteArray();

               } catch (Exception e) {

                       e.printStackTrace();

               }

        }

}

Download Object Serialization Source code

Java Inheritance:

Java Inheritance defines an is-a relationship between a superclass and its subclasses. This means that an object of a subclass can be used wherever an object of the superclass can be used. Class Inheritance in java mechanism is used to build new classes from existing classes. The inheritance relationship is transitive: if class x extends class y, then a class z, which extends class x, will also inherit from class y.

For example a car class can inherit some properties from a General vehicle class. Here we find that the base class is the vehicle class and the subclass is the more specific car class. A subclass must use the extends clause to derive from a super class which must be written in the header of the subclass definition. The subclass inherits members of the superclass and hence promotes code reuse. The subclass itself can add its own new behavior and properties. The java.lang.Object class is always at the top of any Class inheritance hierarchy.

class Box {         double width;

        double height;

        double depth;

        Box() {

        }

        Box(double w, double h, double d) {

               width = w;

               height = h;

               depth = d;

        }

        void getVolume() {

               System.out.println(“Volume is : ” + width * height * depth);

        }

}

 

public class MatchBox extends Box {

 

        double weight;

        MatchBox() {

        }

        MatchBox(double w, double h, double d, double m) {

               super(w, h, d);

<font size=-1>

 

               weight = m;

        }

        public static void main(String args[]) {

               MatchBox mb1 = new MatchBox(10, 10, 10, 10);

               mb1.getVolume();

               System.out.println(“width of MatchBox 1 is ” + mb1.width);

               System.out.println(“height of MatchBox 1 is ” + mb1.height);

               System.out.println(“depth of MatchBox 1 is ” + mb1.depth);

               System.out.println(“weight of MatchBox 1 is ” + mb1.weight);

        }

}

Output

Volume is : 1000.0
width of MatchBox 1 is 10.0
height of MatchBox 1 is 10.0
depth of MatchBox 1 is 10.0
weight of MatchBox 1 is 10.0

Download MatchBox.java

What is not possible using java class Inheritance?

1. Private members of the superclass are not inherited by the subclass and can only be indirectly accessed.
2. Members that have default accessibility in the superclass are also not inherited by subclasses in other packages, as these members are only accessible by their simple names in subclasses within the same package as the superclass.
3. Since constructors and initializer blocks are not members of a class, they are not inherited by a subclass.
4. A subclass can extend only one superclass

class Vehicle {         // Instance fields

        int noOfTyres; // no of tyres

        private boolean accessories; // check if accessorees present or not

        protected String brand; // Brand of the car

        // Static fields

        private static int counter; // No of Vehicle objects created

        // Constructor

        Vehicle() {

               System.out.println(“Constructor of the Super class called”);

               noOfTyres = 5;

               accessories = true;

               brand = “X”;

               counter++;

        }

        // Instance methods

        public void switchOn() {

               accessories = true;

        }

        public void switchOff() {

               accessories = false;

        }

        public boolean isPresent() {

               return accessories;

        }

        private void getBrand() {

               System.out.println(“Vehicle Brand: ” + brand);

        }

        // Static methods

        public static void getNoOfVehicles() {

               System.out.println(“Number of Vehicles: ” + counter);

        }

}

 

class Car extends Vehicle {

 

        private int carNo = 10;

        public void printCarInfo() {

               System.out.println(“Car number: ” + carNo);

               System.out.println(“No of Tyres: ” + noOfTyres); // Inherited.

               //  System.out.println(“accessories: ”    + accessories); // Not Inherited.

               System.out.println(“accessories: ” + isPresent()); // Inherited.

               //        System.out.println(“Brand: ”     + getBrand());  // Not Inherited.

               System.out.println(“Brand: ” + brand); // Inherited.

               //  System.out.println(“Counter: ”    + counter);     // Not Inherited.

               getNoOfVehicles(); // Inherited.

        }

}

 

public class VehicleDetails { // (3)

 

        public static void main(String[] args) {

               new Car().printCarInfo();

        }

}

Output

Constructor of the Super class called
Car number: 10
No of Tyres: 5
accessories: true
Brand: X
Number of Vehicles: 1

Download VehicleDetails.java

this and super keywords

The two keywords, this and super to help you explicitly name the field or method that you want. Using this and super you have full control on whether to call a method or field present in the same class or to call from the immediate superclass. This keyword is used as a reference to the current object which is an instance of the current class. The keyword super also references the current object, but as an instance of the current class’s super class.

The this reference to the current object is useful in situations where a local variable hides, or shadows, a field with the same name. If a method needs to pass the current object to another method, it can do so using the this reference. Note that the this reference cannot be used in a static context, as static code is not executed in the context of any object.

class Counter {         int i = 0;

        Counter increment() {

               i++;

               return this;

        }

        void print() {

               System.out.println(“i = ” + i);

        }

}

 

public class CounterDemo extends Counter {

 

        public static void main(String[] args) {

               Counter x = new Counter();

               x.increment().increment().increment().print();

        }

}

Output

Volume is : 1000.0
width of MatchBox 1 is 10.0
height of MatchBox 1 is 10.0
depth of MatchBox 1 is 10.0
weight of MatchBox 1 is 10.0

DownloadCounterDemo.java

Object Reference Type Casting

In java object typecasting one object reference can be type cast into another object reference. The cast can be to its own class type or to one of its subclass or superclass types or interfaces. There are compile-time rules and runtime rules for casting in java.

How to Typecast Objects with a dynamically loaded Class ? – The casting of object references depends on the relationship of the classes involved in the same hierarchy. Any object reference can be assigned to a reference variable of the type Object, because the Object class is a superclass of every Java class.
There can be 2 casting java scenarios

· Upcasting
· Downcasting

When we cast a reference along the class hierarchy in a direction from the root class towards the children or subclasses, it is a downcast. When we cast a reference along the class hierarchy in a direction from the sub classes towards the root, it is an upcast. We need not use a cast operator in this case.

The compile-time rules are there to catch attempted casts in cases that are simply not possible. This happens when we try to attempt casts on objects that are totally unrelated (that is not subclass super class relationship or a class-interface relationship) At runtime a ClassCastException is thrown if the object being cast is not compatible with the new type it is being cast to.

<br /><font size=-1>

Below is an example showing when a ClassCastException can occur during object casting

//X is a supper class of Y and Z which are sibblings.public class RunTimeCastDemo { 

        public static void main(String args[]) {

               X x = new X();

               Y y = new Y();

               Z z = new Z();

               X xy = new Y(); // compiles ok (up the hierarchy)

               X xz = new Z(); // compiles ok (up the hierarchy)

               //             Y yz = new Z();   incompatible type (siblings)

               //             Y y1 = new X();   X is not a Y

               //             Z z1 = new X();   X is not a Z

               X x1 = y; // compiles ok (y is subclass of X)

               X x2 = z; // compiles ok (z is subclass of X)

               Y y1 = (Y) x; // compiles ok but produces runtime error

               Z z1 = (Z) x; // compiles ok but produces runtime error

               Y y2 = (Y) x1; // compiles and runs ok (x1 is type Y)

               Z z2 = (Z) x2; // compiles and runs ok (x2 is type Z)

               //             Y y3 = (Y) z;     inconvertible types (siblings)

               //             Z z3 = (Z) y;     inconvertible types (siblings)

               Object o = z;

               Object o1 = (Y) o; // compiles ok but produces runtime error

        }

}

DownloadClassCastException example Source Code

 

Casting Object References: Implicit Casting using a Compiler

In general an implicit cast is done when an Object reference is assigned (cast) to:

* A reference variable whose type is the same as the class from which the object was instantiated.
An Object as Object is a super class of every Class.
* A reference variable whose type is a super class of the class from which the object was instantiated.
* A reference variable whose type is an interface that is implemented by the class from which the object was instantiated.
* A reference variable whose type is an interface that is implemented by a super class of the class from which the object was instantiated.

Consider an interface Vehicle, a super class Car and its subclass Ford. The following example shows the automatic conversion of object references handled by the compiler

interface Vehicle {
}
class Car implements Vehicle {
}class Ford extends Car {
}

Let c be a variable of type Car class and f be of class Ford and v be an vehicle interface reference. We can assign the Ford reference to the Car variable:
I.e. we can do the following

Example 1
c = f; //Ok Compiles fine

Where c = new Car();
And, f = new Ford();
The compiler automatically handles the conversion (assignment) since the types are compatible (sub class – super class relationship), i.e., the type Car can hold the type Ford since a Ford is a Car.

Example 2
v = c; //Ok Compiles fine
c = v; // illegal conversion from interface type to class type results in compilation error

Where c = new Car();
And v is a Vehicle interface reference (Vehicle v)

The compiler automatically handles the conversion (assignment) since the types are compatible (class – interface relationship), i.e., the type Car can be cast to Vehicle interface type since Car implements Vehicle Interface. (Car is a Vehicle).

Casting Object References: Explicit Casting

Sometimes we do an explicit cast in java when implicit casts don’t work or are not helpful for a particular scenario. The explicit cast is nothing but the name of the new “type” inside a pair of matched parentheses. As before, we consider the same Car and Ford Class

class Car {
void carMethod(){
}
}class Ford extends Car {
void fordMethod () {
}
}

We also have a breakingSystem() function which takes Car reference (Superclass reference) as an input parameter.
The method will invoke carMethod() regardless of the type of object (Car or Ford Reference) and if it is a Ford object, it will also invoke fordMethod(). We use the instanceof operator to determine the type of object at run time.

public void breakingSystem (Car obj) {
obj.carMethod();
if (obj instanceof Ford)((Ford)obj).fordMethod ();
}

To invoke the fordMethod(), the operation (Ford)obj tells the compiler to treat the Car object referenced by obj as if it is a Ford object. Without the cast, the compiler will give an error message indicating that fordMethod() cannot be found in the Car definition.

The following program shown illustrates the use of the cast operator with references.

Note: Classes Honda and Ford are Siblings in the class Hierarchy. Both these classes are subclasses of Class Car. Both Car and HeavyVehicle Class extend Object Class. Any class that does not explicitly extend some other class will automatically extends the Object by default. This code instantiates an object of the class Ford and assigns the object’s reference to a reference variable of type Car. This assignment is allowed as Car is a superclass of Ford. In order to use a reference of a class type to invoke a method, the method must be defined at or above that class in the class hierarchy. Hence an object of Class Car cannot invoke a method present in Class Ford, since the method fordMethod is not present in Class Car or any of its superclasses. Hence this problem can be colved by a simple downcast by casting the Car object reference to the Ford Class Object reference as done in the program. Also an attempt to cast an object reference to its Sibling Object reference produces a ClassCastException at runtime, although compilation happens without any error.

 class Car extends Object { 

      void carMethod() {

      }

}

 

class HeavyVehicle extends Object {

}

 

class Ford extends Car {

 

      void fordMethod() {

            System.out.println(“I am fordMethod defined in Class Ford”);

      }

}

 

class Honda extends Car {

 

      void fordMethod() {

            System.out.println(“I am fordMethod defined in Class Ford”);

      }

}

 

public class ObjectCastingEx {

 

      public static void main(String[] args) {

            Car obj = new Ford();

            //    Following will result in compilation error

            //    obj.fordMethod(); //As the method fordMethod is undefined for the Car Type

            //  Following will result in compilation error

            // ((HeavyVehicle)obj).fordMethod();

                               //fordMethod is undefined in the HeavyVehicle Type

            //  Following will result in compilation error

            ((Ford) obj).fordMethod();

            //Following will compile and run

            //    Honda hondaObj = (Ford)obj;    Cannot convert as they are sibblings

      }

}

Download Object Reference Casting Source Code

One common casting that is performed when dealing with collections is, you can cast an object reference into a String.

import java.util.Vector; public class StringCastDemo {

 

        public static void main(String args[]) {

               String username = “asdf”;

               String password = “qwer”;

               Vector v = new Vector();

               v.add(username);

               v.add(password);

               //               String u = v.elementAt(0); Cannot convert from object to String

               Object u = v.elementAt(0); //Cast not done

               System.out.println(“Username : ” + u);

               String uname = (String) v.elementAt(0); // cast allowed

               String pass = (String) v.elementAt(1); // cast allowed

               System.out.println();

               System.out.println(“Username : ” + uname);

               System.out.println(“Password : ” + pass);

        }

}


Download
Object String Casting Source Code

Output

Username : asdf
Username : asdf
Password : qwer

instanceof Operator

The instanceof operator is called the type comparison operator, lets you determine if an object belongs to a specific class, or implements a specific interface. It returns true if an object is an instance of the class or if the object implements the interface, otherwise it returns false.

Below is an example showing the use of instanceof operator

class Vehicle {         String name;

        Vehicle() {

               name = “Vehicle”;

        }

}

 

class HeavyVehicle extends Vehicle {

 

        HeavyVehicle() {

               name = “HeavyVehicle”;

        }

}

 

class Truck extends HeavyVehicle {

 

        Truck() {

               name = “Truck”;

        }

}

 

class LightVehicle extends Vehicle {

 

        LightVehicle() {

               name = “LightVehicle”;

        }

}

 

public class InstanceOfExample {

 

        static boolean result;

        static HeavyVehicle hV = new HeavyVehicle();

        static Truck T = new Truck();

        static HeavyVehicle hv2 = null;

        public static void main(String[] args) {

               result = hV instanceof HeavyVehicle;

               System.out.print(“hV is an HeavyVehicle: ” + result + “\n”);

               result = T instanceof HeavyVehicle;

               System.out.print(“T is an HeavyVehicle: ” + result + “\n”);

               result = hV instanceof Truck;

               System.out.print(“hV is a Truck: ” + result + “\n”);

               result = hv2 instanceof HeavyVehicle;

               System.out.print(“hv2 is an HeavyVehicle: ” + result + “\n”);

               hV = T; //Sucessful Cast form child to parent

               T = (Truck) hV; //Sucessful Explicit Cast form parent to child

        }

}

Download instanceof operator Source Code

Output

hV is an HeavyVehicle: true
T is an HeavyVehicle: true
hV is a Truck: false
hv2 is an HeavyVehicle: false

Note: hv2 does not yet reference an HeavyVehicle object, instanceof returns false. Also we can’t use instanceof operator with siblings

Abstract Class in java

Java Abstract classes are used to declare common characteristics of subclasses. An abstract class cannot be instantiated. It can only be used as a superclass for other classes that extend the abstract class. Abstract classes are declared with the abstract keyword. Abstract classes are used to provide a template or design for concrete subclasses down the inheritance tree.

Like any other class, an abstract class can contain fields that describe the characteristics and methods that describe the actions that a class can perform. An abstract class can include methods that contain no implementation. These are called abstract methods. The abstract method declaration must then end with a semicolon rather than a block. If a class has any abstract methods, whether declared or inherited, the entire class must be declared abstract. Abstract methods are used to provide a template for the classes that inherit the abstract methods.

Abstract classes cannot be instantiated; they must be subclassed, and actual implementations must be provided for the abstract methods. Any implementation specified can, of course, be overridden by additional subclasses. An object must have an implementation for all of its methods. You need to create a subclass that provides an implementation for the abstract method.

A class abstract Vehicle might be specified as abstract to represent the general abstraction of a vehicle, as creating instances of the class would not be meaningful.

<br /><font size=-1>

abstract class Vehicle {       int numofGears;

      String color;

      abstract boolean hasDiskBrake();

      abstract int getNoofGears();

}

Example of a shape class as an abstract class

abstract class Shape {       public String color;

      public Shape() {

      }

      public void setColor(String c) {

            color = c;

      }

      public String getColor() {

            return color;

      }

      abstract public double area();

}

We can also implement the generic shapes class as an abstract class so that we can draw lines, circles, triangles etc. All shapes have some common fields and methods, but each can, of course, add more fields and methods. The abstract class guarantees that each shape will have the same set of basic properties. We declare this class abstract because there is no such thing as a generic shape. There can only be concrete shapes such as squares, circles, triangles etc.

public class Point extends Shape {         static int x, y;

        public Point() {

               x = 0;

               y = 0;

        }

        public double area() {

               return 0;

        }

        public double perimeter() {

               return 0;

        }

        public static void print() {

               System.out.println(“point: ” + x + “,” + y);

        }

        public static void main(String args[]) {

               Point p = new Point();

               p.print();

        }

}

Output

point: 0, 0

Notice that, in order to create a Point object, its class cannot be abstract. This means that all of the abstract methods of the Shape class must be implemented by the Point class.

The subclass must define an implementation for every abstract method of the abstract superclass, or the subclass itself will also be abstract. Similarly other shape objects can be created using the generic Shape Abstract class.

A big Disadvantage of using abstract classes is not able to use multiple inheritance. In the sense, when a class extends an abstract class, it can’t extend any other class.

 

 1)      OOP: Stands for “Object-Oriented Programming.” OOP (not Oops!) refers to a programming methodology based on objects, instead of just functions and procedures. These objects are organized into classes, which allow individual objects to be group together. Most modern programming languages including Java, C/C++, and PHP, are object-oriented languages, and many older programming languages now have object-oriented versions..

An “object” in an OOP language refers to a specific type, or “instance,” of a class. Each object has a structure similar to other objects in the class, but can be assigned individual characteristics. An object can also call functions, or methods, specific to that object. For example, the source code of a video game may include a class that defines the structure of characters in the game. Individual characters may be defined as objects, which allows them to have different appearances, skills, and abilities. They may also perform different tasks in the game, which are run using each object’s specific methods.

Object-oriented programming makes it easier for programmers to structure and organize software programs. Because individual objects can be modified without affecting other aspects of the program, it is also easier to update and change programs written in object-oriented languages. As software programs have grown larger over the years, OOP has made developing these large programs more manageable.

2)    Basic Concepts of  Object  Oriented Programming(OOP):

i) Class: In object-oriented programming, a class is a construct that is used as a blueprint to create instances of itself – referred to as class instances, class objects, instance objects or simply objects. A class defines constituent members which enable these class instances to have state and behavior. Data field members (member variables or instance variables) enable a class object to maintain state. Other kinds of members, especially methods, enable a class object’s behavior. Class instances are of the type of the associated class.

ii)Object: In computer science, an object is any entity that can be manipulated by the commands of a programming language, such as a value, variable, function, or data structure. (With the later introduction of object-oriented programming the same word, “object”, refers to a particular instance of a class).

iii)Abstraction

Abstraction denotes the essential characteristics of an object that distinguish it from all other kinds of objects and thus provide crisply defined conceptual boundaries, relative to the perspective of the viewer.

iv)Encapsulation
Encapsulation is the process of compartmentalizing the elements of an abstraction that constitute its structure and behavior ; encapsulation serves to separate the contractual interface of an abstraction and its implementation.

Encapsulation

* Hides the implementation details of a class.
* Forces the user to use an interface to access data
* Makes the code more maintainable.

v)Inheritance

Inheritance is the process by which one object acquires the properties of another object.

vi)Polymorphism

Polymorphism is the existence of the classes or methods in different forms or single name denoting different
implementations.

3)    Benefits of OOPs:

  1. Reusability: In OOP’s programs functions and modules that are written by a user can be reused by other users without any modification.
  2. Inheritance:Through this we can eliminate redundant code and extend the use of existing classes.
  3. Data Hiding: The programmer can hide the data and functions in a class from other classes. It helps the programmer to build the secure programs.
  4. Reduced complexity of a problem: The given problem can be viewed as a collection of different objects. Each object is responsible for a specific task. The problem is solved by interfacing the objects. This technique reduces the complexity of the program design.
  5. Easy to Maintain and Upgrade: OOP makes it easy to maintain and modify existing code as new objects can be created with small differences to existing ones.
  6. Message Passing: The technique of message communication between objects makes the interface with external systems easier.
  7. Modifiability: it is easy to make minor changes in the data representation or the procedures in an OO program. Changes inside a class do not affect any other part of a program, since the only public interface that the external world has to a class is through the use of methods;

4)    Applications of OOP:

OOP Provides Many Applications:-
Real time Systesm : –
A real time system is a system that give output at given instant and its parameters changes at every time. A real time system is nothing but a dynamic system. Dynamic means the system that changes every moment based on input to the system. OOP approach is very useful for Real time system because code changing is very easy in OOP system and it leads toward dynamic behaviour of OOP codes thus more suitable to real time system.
Simulation and Modelling: –
System modelling is another area where criteria for OOP approach is countable. Representing a system is very easy in OOP approach because OOP codes are very easy to understand and thus is preffered to represent a system in simpler form.
Hypertext And Hypermedia : –
Hypertext and hypermedia is another area where OOP approach is spreading its legs. Its ease of using OOP codes that makes it suitable for various media approaches.
Decision support system : –
Decision support system is an example of Real time system that too very advance and complex system. More details is explained in real time system.
CAM/CAE/CAD System : –
Computer has wide use of OOP approach. This is due to time saving in writing OOP codes and dynamic behaviour of OOP codes.
Office Automation System : –
Automation system is just a part or type of real time system. Embeded systems make it easy to use OOP for automated system.
AI and expert system : –
It is mixed system having both hypermedia and real time system.

 5)    Introduction to Java Programming:

Java is a simple and yet powerful object oriented programming language and it is in many respects similar to C++. Java originated at Sun Microsystems, Inc. in 1991. It was conceived by James Gosling, Patrick Naughton, Chris Warth, Ed Frank, and Mike Sheridan at Sun Microsystems, Inc. It was developed to provide a platform-independent programming language. This site gives you an Introduction to Java Programming accompanied with many java examples. Its a complete course in java programming for beginners to advanced java.

Platform independent

Unlike many other programming languages including C and C++ when Java is compiled, it is not compiled into platform specific machine, rather into platform independent byte code. This byte code is distributed over the web and interpreted by virtual Machine (JVM) on whichever platform it is being run.

Java Virtual Machine

6)What is the Java Virtual Machine? What  is its role?

Java was designed with a concept of ‘write once and run everywhere’. Java Virtual Machine plays the central role in this concept. The JVM is the environment in which Java programs execute. It is a software that is implemented on top of real hardware and operating system. When the source code (.java files) is compiled, it is translated into byte codes and then placed into (.class) files. The JVM executes these bytecodes. So Java byte codes can be thought of as the machine language of the JVM. A JVM can either interpret the bytecode one instruction at a time or the bytecode can be compiled further for the real microprocessor using what is called a just-in-time compiler. The JVM must be implemented on a particular platform before compiled programs can run on that platform.

Java is Distributed

With extensive set of routines to handle TCP/IP protocols like HTTP and FTP java can open and access the objects across net via URLs.

Java is Multithreaded

One of the powerful aspects of the Java language is that it allows multiple threads of execution to run concurrently within the same program A single Java program can have many different threads executing independently and continuously. Multiple Java applets can run on the browser at the same time sharing the CPU time.

Java is Secure

Java was designed to allow secure execution of code across network. To make Java secure many of the features of C and C++ were eliminated. Java does not use Pointers. Java programs cannot access arbitrary addresses in memory.

Garbage collection

Automatic garbage collection is another great feature of Java with which it prevents inadvertent corruption of memory. Similar to C++, Java has a new operator to allocate memory on the heap for a new object. But it does not use delete operator to free the memory as it is done in C++ to free the memory if the object is no longer needed. It is done automatically with garbage collector.

7)Java Applications:

Java has evolved from a simple language providing interactive dynamic content for web pages to a predominant enterprise-enabled programming language suitable for developing significant and critical applications. Today, It is used for many types of applications including Web based applications, Financial applications, Gaming applications, embedded systems, Distributed enterprise applications, mobile applications, Image processors, desktop applications and many more. This site outlines the building blocks of java by stating few java examples along with some java tutorials.

Getting Started with Java:

Getting Java Basics quickly has become easy with Javabeginner.com. This site is for the java programmers who want to use the Java programming language to create applications using the Java basics. This site is for absolute beginners to advanced java programmers who do not require any prerequisite Java knowledge. For getting started with Java you’ll have to have some basic understanding of the concepts of programming.

After going through all the tutorials in this site, you would have learnt the essential concepts and features of the Java Programming Language which include exceptions, Swing GUI programming, Collections framework etc. A lot of code examples are used through out tutorial to make you understand the language better.
All the listings and programs in the website are compiled and run using the JDK 1.5.
Download : JDK and JRE 1.5

8)Java Architecture

The Java environment is composed of a number of system components. You use these components at compile time to create the Java program and at run time to execute the program. Java achieves its independence by creating programs designed to run on the Java Virtual Machine rather than any specific computer system.

  • After you write a Java program, you use a compiler that reads the statements in the program and translates them into a machine independent format called bytecode.
  • Bytecode files, which are very compact, are easily transported through a distributed system like the Internet.
  • The compiled Java code (resulting byte code) will be executed at run time.

Java programs can be written and executed in two ways:

  • Stand-alone application (A Java Swing Application)
  • Applet which runs on a web browser (Example: Internet Explorer)

9)Java source code:

A Java program is a collection of one or more java classes. A Java source file can contain more than one class definition and has a .java extension. Each class definition in a source file is compiled into a separate class file. The name of this compiled file is comprised of the name of the class with .class as an extension. Before we proceed further in this section, I would recommend you to go through the ‘Basic Language Elements’.

Below is a java sample code for the traditional Hello World program. Basically, the idea behind this Hello World program is to learn how to create a program, compile and run it. To create your java source code you can use any editor( Text pad/Edit plus are my favorites) or you can use an IDE like Eclipse.

public class HelloWorld {public static void main(String[] args) {

System.out.println(“Hello World”);

}//End of main

}//End of HelloWorld Class

Output
Hello World

ABOUT THE PROGRAM

I created a class named “HelloWorld” containing a simple main function within it. The keyword class specifies that we are defining a class. The name of a public class is spelled exactly as the name of the file (Case Sensitive). All java programs begin execution with the method named main(). main method that gets executed has the following signature : public static void main(String args[]).Declaring this method as public means that it is accessible from outside the class so that the JVM can find it when it looks for the program to start it. It is necessary that the method is declared with return type void (i.e. no arguments are returned from the method). The main method contains a String argument array that can contain the command line arguments. The brackets { and } mark the beginning and ending of the class. The program contains a line ‘System.out.println(”Hello World”);’ that tells the computer to print out on one line of text namely ‘Hello World’. The semi-colon ‘;’ ends the line of code. The double slashes ‘//’ are used for comments that can be used to describe what a source code is doing. Everything to the right of the slashes on the same line does not get compiled, as they are simply the comments in a program.

Java Main method Declarations

class MainExample1 {public static void main(String[] args) {}}
class MainExample2 {public static void main(String []args) {}}
class MainExample3 {public static void main(String args[]) {}}

All the 3 valid main method’s shown above accepts a single String array argument.

10)Compiling and Running an Application:

To compile and run the program you need the JDK distributed by Sun Microsystems. The JDK contains documentation, examples, installation instructions, class libraries and packages, and tools. Download an editor like Textpad/EditPlus to type your code. You must save your source code with a .java extension. The name of the file must be the name of the public class contained in the file.

Steps for Saving, compiling and Running a Java

Step 1:Save the program With .java Extension.
Step 2:Compile the file from DOS prompt by typing javac <filename>.
Step 3:Successful Compilation, results in creation of .class containing byte code
Step 4:Execute the file by typing java <filename without extension>

11)Java Development Kit:

The Java Developer’s Kit is distributed by Sun Microsystems. The JDK contains documentation, examples, installation instructions, class libraries and packages, and tools

javadoc

The javadoc tool provided by Sun is used to produce documentation for an application or program,

Jar Files

A jar file is used to group together related class files into a single file for more compact storage, distribution, and transmission.

PATH and CLASSPATH

The following are the general programming errors, which I think every beginning java programmer would come across. Here is a solution on how to solve the problems when running on a Microsoft Windows Machine.

1. ‘javac’ is not recognized as an internal or external command, operable program or batch file

When you get this error, you should conclude that your operating system cannot find the compiler (javac). To solve this error you need to set the PATH variable.

How to set the PATH Variable?

Firstly the PATH variable is set so that we can compile and execute programs from any directory without having to type the full path of the command. To set the PATH of jdk on your system (Windows XP), add the full path of the jdk<version>\bin directory to the PATH variable. Set the PATH as follows on a Windows machine:

a. Click Start > Right Click “My Computer” and click on “Properties”
b. Click Advanced > Environment Variables.
c. Add the location of bin folder of JDK installation for PATH in User Variables and System Variables. A typical value for PATH is:

C:\jdk<version>\bin (jdk<version is nothing but the name of the directory where jdk is installed)

If there are already some entries in the PATH variable then you must add a semicolon and then add the above value (Version being replaced with the version of JDK). The new path takes effect in each new command prompt window you open after setting the PATH variable.

2. Exception in thread “main” java.lang.NoClassDefFoundError: HelloWorld

If you receive this error, java cannot find your compiled byte code file, HelloWorld.class.If both your class files and source code are in the same working directory and if you try running your program from the current working directory than, your program must get executed without any problems as, java tries to find your .class file is your current directory. If your class files are present in some other directory other than that of the java files we must set the CLASSPATH pointing to the directory that contain your compiled class files.CLASSPATH can be set as follows on a Windows machine:

a. Click Start > Right Click “My Computer” and click on “Properties”
b. Click Advanced > Environment Variables.

Add the location of classes’ folder containing all your java classes in User Variables.

If there are already some entries in the CLASSPATH variable then you must add a semicolon and then add the new value . The new class path takes effect in each new command prompt window you open after setting the CLASSPATH variable.

Java 1.5

The Java 1.5 released in September 2004.

Goals

Less code complexity
Better readability
More compile-time type safety
Some new functionality (generics, scanner)

New Features

Enhanced for loop
Enumerated types
Autoboxing & unboxing
Generic types
Scanner
Variable number of arguments (varargs)
Static imports
Annotations

Basic Language Elements:

This part of the java tutorial teaches you the basic language elements and syntax for the java programming language. Once you get these basic language concepts you can continue with the other object oriented programming language concepts.

12)Keywords:

There are certain words with a specific meaning in java which tell (help) the compiler what the program is supposed to do. These Keywords cannot be used as variable names, class names, or method names. Keywords in java are case sensitive, all characters being lower case.

Keywords are reserved words that are predefined in the language; see the table below (Taken from Sun Java Site). All the keywords are in lowercase.

      abstract    default    if            private      this
      boolean     do         implements    protected    throw
      break       double     import        public       throws
      byte        else       instanceof    return       transient
      case        extends    int           short        try
      catch       final      interface     static       void
      char        finally    long          strictfp     volatile
      class       float      native        super        while
      const       for        new           switch
      continue    goto       package       synchronized

Keywords are marked in yellow as shown in the sample code below

/** This class is a Hello World Program used to introduce
the Java Language*/
public class HelloWorld {
public static void main(String[] args) {
System.out.println(”Hello World”); //Prints output to console

}
}

For more information on different Keywords – Java Keywords

Some Tricky Observations: The words virtual, ifdef, typedef, friend, struct and union are all words related to

the C programming language. const and goto are Java keywords. The word finalize is the name of a method

of the Object class and hence not a keyword. enum and label are not keywords.

13)Comments:

Comments are descriptions that are added to a program to make code easier to understand. The compiler ignores comments and hence its only for documentation of the program.

Java supports three comment styles.

Block style comments begin with /* and terminate with */ that spans multiple lines.

Line style comments begin with // and terminate at the end of the line. (Shown in the above program)

Documentation style comments begin with /** and terminate with */ that spans multiple lines. They are generally created using the automatic documentation generation tool, such as javadoc. (Shown in the above program)

name of this compiled file is comprised of the name of the class with .class as an extension.

Variable, Identifiers and Data Types

14)Variables:

Variables are used for data that change during program execution. All variables have a name, a type, and a scope. The programmer assigns the names to variables, known as identifiers. An Identifier must be unique within a scope of the Java program. Variables have a data type, that indicates the kind of value they can store. Variables declared inside of a block or method are called local variables; They are not automatically initialized. The compiler will generate an error as a result of the attempt to access the local variables before a value has been assigned.

public class localVariableEx {
  public static int a;
  public static void main(String[] args) {
    int b;
    System.out.println("a : "+a);
    System.out.println("b : "+b);    //Compilation error
}}

Note in the above example, a compilation error results in where the variable is tried to be accessed and not at the place where its declared without any value.

15) Data type:

Data type indicates the attributes of the variable, such as the range of values that can be stored and the operators that can be used to manipulate the variable. Java has four main primitive data types built into the language. You can also create your own composite data types.

Java has four main primitive data types built into the language. We can also create our own data types.

  • Integer: byte, short, int, and long.
  • Floating Point: float and double
  • Character: char
  • Boolean: variable with a value of true or false.

The following chart (Taken from Sun Java Site) summarizes the default values for the java built in data types. Since I thought Mentioning the size was not important as part of learning Java, I have not mentioned it in the below table. The size for each Java type can be obtained by a simple Google search.

Data Type

Default Value (for fields)

Range

Byte

0

-127 to +128

Short

0

-32768 to +32767

Int

0

 

Long

0L

 

Float

0.0f

 

double

0.0d

 

Char

‘\u0000′

0 to 65535

String (object)

null

 

boolean

false

 

When we declare a variable we assign it an identifier and a data type.

For Example

String message = “hello world”

In the above statement, String is the data type for the identifier message. If you don’t specify a value when the variable is declared, it will be assigned the default value for its data type.

Identifier Naming Rules

  • Can consist of upper and lower case letters, digits, dollar sign ($) and the underscore ( _ ) character.
  • Must begin with a letter, dollar sign, or an underscore
  • Are case sensitive
  • Keywords cannot be used as identifiers
  • Within a given section of your program or scope, each user defined item must have a unique identifier
  • Can be of any length.

16)The scope of a variable : is the part of the program over which the variable name can be referenced. (from Ivor Horton’s Beginning Java 2, JDK 5 Edition by Ivor Horton)

You cannot refer to a variable before its declaration.

You can declare variables in several different places:

  1. In a class body as class fields. Variables declared here are referred to as class-level variables.
  2. As parameters of a method or constructor.
  3. In a method’s body or a constructor’s body.
  4. Within a statement block, such as inside a while or for block.

Variable scope refers to the accessibility of a variable.

The rule 1 is that variables defined in a block are only accessible from within the block. The scope of the variable is the block in which it is defined. For example, consider the following for statement.

public class MainClass {public static void main(String[] args) {
for (int x = 0; x < 5; x++) {
System.out.println(x);
}
}}

Rule number 2 is a nested block can access variables declared in the outer block. Consider this code.

public class MainClass {public static void main(String[] args) {
for (int x = 0; x < 5; x++) {
for (int y = 0; y < 3; y++) {
System.out.println(x);
System.out.println(y);
}
}
}}

Variables declared as method parameters can be accessed from within the method body. Class-level variables are accessible from anywhere in the class.

If a method declares a local variable that has the same name as a class-level variable, the former will ‘shadow’ the latter. To access the class-level variable from inside the method body, use the this keyword.

17)Variable Scope in a block:
 
public class MainClass {
public static void main(String[] args) {
int outer = 1;{
int inner = 2;
System.out.println(“inner = ” + inner);
System.out.println(“outer = ” + outer);
}int inner = 3;
System.out.println(“inner = ” + inner);
System.out.println(“outer = ” + outer);
}
}
inner = 2outer = 1

inner = 3

outer = 1

Command Line Arguments in Java Program:

Java application can accept any number of arguments directly from the command line. The user can enter command-line arguments when invoking the application. When running the java program from java command, the arguments are provided after the name of the class separated by space. For example, suppose a program named CmndLineArguments that accept command line arguments as a string array and echo them on standard output device.

java CmndLineArguments Mahendra zero one two three

CmndLineArguments.java

   /**
* How to use command line arguments in java program.
*/
class CmndLineArguments {public static void main(String[] args) {
int length = args.length;
if (length <= 0) {
System.out.println(“You need to enter some arguments.”);
}
for (int i = 0; i < length; i++) {
System.out.println(args[i]);
}
}
}

Output of the program:

Run program with some command line arguments like: 
java CmndLineArguments Mahendra zero one two three

OUTPUT
Command line arguments were passed :
Mahendra
zero
one
two
three

19)Symbolic Constants in Java:

symbolic constants are named constants
like :
final double PI = 3.14 ;
They are constants because of the ‘final’ keywords, so they canNOT be reassigned a new value after being declared as final
And they are symbolic , because they have a name

A NON symbolic constant is like the value of ‘2’ in expression
int foo = 2 * 3

20)Type Casting:  refers to changing an entity of one datatype into another. This is important for the type conversion in developing any application. If you will store a int value into a byte variable directly, this will be illegal operation. For storing your calculated int value in a byte variable you will have to change the type of resultant data which has to be stored. This type of operation has illustrated below :

In this example we will see that how to convert the data type by using type casting. In the given line of the code c = (char)(t?1:0); illustrates that if t which is boolean type variable is true then value of c which is the char type variable will be 1 but 1 is a numeric value. So, 1 is changed into character according to the Unicode value. But in this line c = (char)(t?’1′:’0′); 1 is already given as a character which will be stored as it is in the char type variable c.

Code of the program :

public class conversion{
public static void main(String[] args){
boolean t = true;
byte b = 2;
short s = 100;
char c = ‘C’;
int i = 200;
long l = 24000;
float f = 3.14f;
double d = 0.000000000000053;
String g = “string”;
System.out.println(“Value of all the variables like”);
System.out.println(“t = ” + t );
System.out.println(“b = ” + b );
System.out.println(“s = ” + s );
System.out.println(“c = ” + c );
System.out.println(“i = ” + i );
System.out.println(“l = ” + l );
System.out.println(“f = ” + f );
System.out.println(“d = ” + d );
System.out.println(“g = ” + g );
System.out.println();
//Convert from boolean to byte.
b = (byte)(t?1:0);
System.out.println(“Value of b after conversion : ” + b);
//Convert from boolean to short.
s = (short)(t?1:0);
System.out.println(“Value of s after conversion : ” + s);
//Convert from boolean to int.
i = (int)(t?1:0);
System.out.println(“Value of i after conversion : ” + i);
//Convert from boolean to char.
c = (char)(t?’1′:’0′);
System.out.println(“Value of c after conversion : ” + c);
c = (char)(t?1:0);
System.out.println(“Value of c after conversion in unicode : ” + c);
//Convert from boolean to long.
l = (long)(t?1:0);
System.out.println(“Value of l after conversion : ” + l);
//Convert from boolean to float.
f = (float)(t?1:0);
System.out.println(“Value of f after conversion : ” + f);
//Convert from boolean to double.
d = (double)(t?1:0);
System.out.println(“Value of d after conversion : ” + d);
//Convert from boolean to String.
g = String.valueOf(t);
System.out.println(“Value of g after conversion : ” + g);
g = (String)(t?”1″:”0″);
System.out.println(“Value of g after conversion : ” + g);
int sum = (int)(b + i + l + d + f);
System.out.println(“Value of sum after conversion : ” + sum);
}
}

 

 

 

Other computers related blogs!

 http://softcodeguru.blogspot.com

http://computerprogramtechnology.blogspot.com

Data Structure Visualizations

Basic HTML Scripting Codes

HTML = HYPER TEXT MARKUP LANGUAGE

XML  = EXTENSIBLE MARKUP LANGUAGE

SGML = STANDARD GENERALIZED MARKUP LANGUAGE

XML and HTML both are the descendants  of the complex and arcane language SGML(Standard
Generalized Markup Language).

ASP  = (ACTIVE SERVER PAGES) This is used as a web application.To impliment this application
we need a language eg:c#,vb or any other language.

ASP code is generally embedded in HTML Programming and it also takes the help of java script.

Other languages are JSP in JAVA.

The HTML Controls
The .net Framework exposes a namespace for working with server-side HTML control.A server side
HTML Control is simply an HTML element with a runat=”server” attributes,like so:

<INPUT TYPE=”text” ID=”txtname” runat=”server”/>

Following are the HTML tags
1) HTML Anchor : This corresponds to the <A>tag.

2) HTML Button : This corresponds to the <button>tag.

3) HTML Form   : This corresponds to the <form>tag.

4) HTML GenericControl : This corresponds to the unmapped tags ,such as <apan> and <div>.

5) HTML InputButton : This corresponds to the <input type=”button”>,<input type=”submit”>&<input type=”reset”>tags.

6) HTML InputCheckBox: This corresponds to the <input type=”checkbox”>tag.

7) HTML InputFile   : This corresponds to the <input type=”file”>tag.

8) HTML InputHidden : This corresponds to the<input type=”hidden”>tag.

9) HTML InputImage  : This corresponds to the<input type=”image”>tag.

10)HTML InputRadioButton : This corresponds to the <input type=”radio”>tag.

11)HTML InputText : This corresponds to the <input type=”text”> and <input type=”password”>tags.

12)HTML Select :This corresponds to the <select>tag.

13)HTML Table  :This corresponds to <table>tag.

14)HTML TableCell : This corresponds to the <td>tag.

15)HTML TableRow : This corrresponds to the <tr>tag.

16)HTML TextArea: This corresponds to the <textareea>tag.

Remember that all takes to make an HTML Control server-side is the  runat=”server” attribute.

Other tags:
———–
<HTML></HTML> Start and end of the html document.
<HEAD> Head of the document.
<TITLE> Title of the document.
<BODY> Programming area.

BACKGROUND COLOR PICTURE
<BODY bgcolor=”color” background=”picture path” text=”text color”>

Adding Background Music
<Body>
<BGSOUND SRC=”MUSIC FILE.EXTENSION”>
</Body>

Handling Text
<BODY>

Hello! Welcome to My personal Web site.I hope You Like it. This is My First attempt at web Designing Enjoy!

Text with line or paragraph breaks
<BODY>
Hello! Welcome to My personal Web site.<p>I Hope you like it.<p>
This is my First attempt at web design.Enjoy!<p>
</BODY>

<B> Boldface appears like this </B><br>
<I>Italic </I><br>
<U>Underline</U><br>
<B><I>Bold and Italic</I></B><BR>

<DNF> DEFINITIONS
<CITE> journals
<CODE> COMPUTER CODE
<SAMP> FOR COMPUTER OUTPUT
<VAR> VARIABLES
<EM> fOR anything that needs emphasis
<KBD>kEYBOARD ENTRY
<STRONG> Something that deserves extra strong emphasis.

HEADERS
<h1> Level1 heading </h1>

<h2> Level2 heading </h2>

<h3> Level3 heading </h3>

<h4> Level4 heading </h4>

<h5> Level5 heading </h5>

<h6> Level6 heading </h6>

text formating
—————-

<FONT face=” ” size=n color=”  ” >

Inserting Images
<IMG src=”path.extension” width=n height=n border=n bordercolor=”color”>

ANCHORS
<A href=”path or name>name</a>

LISTS
<UL> Un numbered list
<OL> Orderd list
<LI>BEGINING OF EACH LIST ITEM
<DT> DEFINING TERM
<DD>DEFINING DEFINITION
<P> PARA
<DL>DEFINING LIST

TABLES
<TABLE BORDER=N BORDERCOLOR=”COLOR” BGCOLOR=” ” BACKGROUND=” ” CELLPADDING=N CELLSPACING=N ALIGN=” “>
<CAPTION>Title</CAPTION>
<TR align=” ” border=n bordercolor=” “>
<TH align=” ” border=n bordercolor=” “>
</th>
<td align=” ” border=n bordercolor=” “>
</td>
</tr>
</TABLE>

ex:

<TABLE BORDER=2>
<CAPTION> Table with border</CAPTION>
<TH>Column 1</TH> Column 2</TH>
<TR>
<TD>ITEM 1</TD> <TD> ITEM 2 </TD>
</TR>
<TR>
<TD>ITEM 3</TD> <TD> ITEM 4</TD>
</TR>
</TABLE>
<P>

HORIZONTAL RULES
<HR> TAG.
<HR SIZE=N/SIZE=%N WIDTH=N/WIDTH=%N ALIGN=LEFT/RIGT/CENTER COLOR=” “noshade>

MARQUEE
<MARQUEE> SATEESH</MARQUEE>
<MARQUEE DIRECTION=” ” BEHAVIOR=” ” LOOP= ” ” > </ MARQUEE>
DIRECTION= LEFT , RIGHT , UP
BEHAVIOR OF SCROLLING
LOOP=N

BLINK
<BLINK>
Congratulations!
</BLINK>

FRAMES
<FRAMESET ROWS=R1,R2 COLS=C1,C2>
<FRAME SRC=” “NAME=” ” SCROLLING=” ” MARGINWIDTH=N MARGINHEIGHT=N NORESIZE>
<FRAME SRC=” “>
</FRAMESET>

EX:
<FRAMESET COLS=”35%,65%”>
<FRAME SRC=”PATH” NAME=”FRAME1″ SCROLLING =”YES” MARGINWIDTH=10 MARGINHEIGHT=”20″ NORESIZE>
<FRAME SRC=”PATH” NAME=”FRAME2″ SCROLLING=”YES” MARGINWIDTH=10 MARGINHEIGHT=20 NORESIZE>
</FRAMESET>

DESIGNING A FORM
<FORM> </FORM>

<INPUT TYPE=”TEXT”>

<INPUT TYPE=”PASSWORD”>

<TEXTAREA>

<INPUT TYPE=”CHECKBOX”>

<INPUT TYPE=”RADIO”>

<SELECT>

<INPUT TYPE=”SUBMIT”>

<INPUT TYPE=”RESET”>