Powered by Blogger.

Monday 16 May 2022

Constructor and Constructor Chaining

No comments :
constructor
is the same as a method but the only difference is that the constructor has the same name as the class name. It is used to create an instance of the class. It is called automatically when we create an object of the class. It has no return type. Remember that a constructor cannot be abstract, final, synchronized, and static. We cannot override a constructor.
There are two types of constructor in Java:
  • Default Constructor (also known as a no-argument constructor) 
  • Parameterized Constructor

Constructor chaining: Constructor chaining is the process of calling one constructor from another constructor with respect to current object. 
Constructor chaining can be done in two ways:
  • Within same class: It can be done using this() keyword for constructors in same class 
  •  From base class: by using super() keyword to call constructor from the base class.



The Need of Constructor Chaining
Suppose, there are five tasks to perform. There are two ways to perform these tasks, either implement all the tasks in a single constructor or create separate tasks in a single constructor.
By using the constructor chaining mechanism, we can implement multiple tasks in a single constructor. So, whenever we face such types of problems, we should use constructor chaining. We can make the program more readable and understandable by using constructor chaining.

Watch YouTube video for live working example and develop yourself.



Tuesday 20 September 2016

Modifying a String

No comments :
String objects are immutable, whenever you want to modify a String, you must either copy it into a StringBuffer or StringBuilder, or use a String Method that constructs a new copy of the string with your modifications complete. A sampling of these methods are described here.
Substring() Method You can extract a substring using substring(). It has two forms. The first is

Here, startIndex specifies the index at which the substring will begin. This form returns a copy of the substring that begins at startIndex and runs to the end of the invoking string .
The second form of substring() allows you to specify both the beginning and ending index of the substring:

Here, startIndex specifies the beginning index, and endIndex specifies the stopping point. the string returned contains all characters from the beginning index, up to, but not including, the ending index.
The following program use substring() to replace all instances of one substring with another within a string:
The Output from this program is shown here.
                           This is a test. this is, too.
                           Thwas is a test. this is, too.
                           Thwas was a test. this is, too.
                           Thwas was a test. thwas is, too.
                           Thwas was a test. thwas was, too.
concat() Method:You can concatenate two string using concat() method, shown here:
This method creates a new object that contains the invoking string with the contents of str appended to the concat() performs the same function as +. for Example

puts the string "onetwo" into s2. It generates the same result as the following sequence:

replace() Method: The replace() method has two forms. The first replaces all occurrences of one character in the invoking string with another character. It has the following general form:

Here, originalch specifies the character to be replaced by the character specified by replacement. The resulting string is returned. for example,

puts the String "Hewwo" into s.
The second form of replace() replaces one character sequence with another. It has this general form:

trim() Method:The trim() Method returns a copy of the invoking string from which any leading and trailing whitespace has been removed. It has this general form:

Here is an example:

This puts the string "hello world" into s.
The trim() method is quite useful when you process user commands. for example, the following program prompts the user for the name of a state and the display that state's capital. It user trim() to remove any leading or trailing whitespace that may have inadvertently been entered by the user.

Searching Strings

No comments :
The String class provides two methods that allow you to search a string for a specified character or substring:
  • indexOf()              Searches for the first occurrence of a character or substring. 
  • lastIndexOf()       Searches for the last occurrence of a character or substring.
These two methods are overloaded in several different ways. In all cases, The methods return the index at which the character or substring was found, or -1 on failure.
To search for the first occurrence of a character use

To search for the last occurrence of a character, use

Here, ch is the character being sought.
To search for the first or last occurrence of a substring, use

Here, startIndex specifies the index at which point the search begins. for indexOf(), the search runs from startIndex to the end of the string. for lastIndexOf(), the search runs from startIndex to zero.
The following example shows how to use the various index methods to search inside of a string:

output:
Now is the time for all good mento come to the aid of their country.
indexOf(t)=7
lastIndexOf(t)=64
indexOd(the)=7
lastIndexOf(the)=54
indexOf(t,10)=11
lastIndexOf(t, 60)=54

Sunday 18 September 2016

String Comparison in java

No comments :
The String class includes a number of methods that compare String or substrings within strings. several are examined here.
equals() and equalsIgnoreCase(): To compare two string for equality, use equals(). It has this general form:

Here, str is the String object being compared with the invoking String object. It returns True if the String contain the same characters in the same order, and false otherwise. The comparison is case-sensitive.
To perform a comparison that ignores case differences, call equalsIgnoreCase(). when it compares two String, it considers A-Z to be the same as a-z. it has this general form:

Here, str is the String object being compared with the invoking String object. It, too, returns true if the string contain the same character in same order, and false otherwise.
Here is an Example that demonstrates equals() and equalsIgnoreCase():

The output form the program is shown here:
                      hello equls hello -> true
                      hello equls good-bay -> false
                      hello equls HELLO -> false
                      hello equalsIgnoreCase HELLO -> true
regionMatches() Method:  The regionMatches() method compares a specific region inside a String with another specific region in another string. There is an overloaded form that allows you to ignore case in such comparisons. Here are the general forms for these two methods:

For both versions, startIndex specifies the index at which the region begins within the invoking String object. The String being compared is specified by str2. the index at which the comparison will start within str2 is specified by str2StarIndex. the length of the substring being compared is passed in numChars. In the second version, if ignore-case is true, the case of the characters is ignored. Otherwise, case is significant. for Example:

Output is:
                               Return Value : true
                               Return Value : false
                               Return Value : false
                               Return Value : false
                              Return Value : true
startsWith() and endsWith() Method : String defines two methods that are, more or less, specialized forms of regionMatches(). The startsWith() method determines whether a given String begins with a specified string. conversely, endsWith() determines whether the String in question ends with a specified string in question ends with a specified String. they have the following general forms:

Here, str is the String being tested. If the String matches, true is returned. Otherwise, false is returned. for Example:


are both true. A second form of starsWith(), shown here, lets you specify a starting point:

Here, startIndex specifies the index into the invoking string at which point the search will begin. For example:
return true.
equals() Versus == :  It is important to understand that the equals() method and the == operator perform two different operation. As just explained, the equals() method compares to see whether they refer to the same instance. The following program shows how two different String objects can contain the same characters. but references to these objects will not compare as equal:

The variable s1 refers to the String instance created by "Hello". The object referred to by s2 is created with s1 as an initializer. Thus, the contents of the two String objects are identical, but they are distinct objects. This means that s1 and s2 do not refer to the same objects and are, therefore, not ==, as is shown here by the output of the preceding example:

CompareTo() : Often, it is not enough to simply know whether two strings are identical. For sorting applications, you need to know which is less than, equal to or greater than the next. A String is less than another if it comes before the other in dictionary order. A string is greater than an other if it comes after the other in dictionary order. A String is Greater Than this purpose. it is specified by the Comparable interface, which String implements. It has the general Form:

Here, str is the String being compared with the invoking String. The result of the comparison is returned and is interpreted as show here:
Value Meaning
Less than Zero The invoking String is less than str
Greater than zero The invoking String is greater than str.
zero The two string are equal.

Here, is a sample program that sorts an array of Strings. The program uses compareTo() to determine sort ordering for a bubble sort:
Outup :
                       Now 
                       aid 
                       all 
                      come 
                      country 
                      for 
                      good 
                      is 
                      men 
                     of 
                     the 
                     the 
                     their 
                     time 
                     to 
                     to 
As you can see from the output of this example, compareTo() takes into account uppercase and lowercase letters. The word "Now" come out before all the others because it begins with an uppercase letter, which means it has a lower value in the ASCII character set. If you want to ignore case differences when comparing two strings use
compareToIgnoreCase(), as shown here:

This method returns the same results as compareTo(), except the case differences are ignored. you might want to try substituting it into the previous program. After doing so, "Now" will no longer be first.

Saturday 17 September 2016

Character Extraction in java

No comments :
The String class provides a number of ways in which characters can be extracted from a String object. Several are examined here. Although the characters that comprise a String within a String object can not be indexed as if they were a character array,Many of the String methods employ an index into the String for there operation. Like the Arrays the String indexes begin at zero.
charAt() Methid:To Extract a Single character from a String,you can refer directly to an individual character via the charAt() method. It has this general form

Here, where is the index of the character that you want to obtain. The value of where must be nonnegative and specify a location within the String. charAt() returns the character at the specified location For Example:


getChars() Method: If you need to Extract more then one character at a ttime you can use the getChars() method. It has this General form:

Here, sourceStart specifies the index of the beginning of the substring, and sourceEnd specifies an index that is one part the end of the desired substring. Thus, the substring character is specified by target. the index within target at which the substring will be copied is passed in targetStart. Care must be taken to assure that the target array is large enough to hold the number of character in the specified substring.
The Following program demonstrates getChars().

Here is the output of the program:
Demo

getBytes() Method: There is an alternative to getChars() that stores the characters in an array of bytes. this method is called getBytes(), and it used the default character-to-byte conversions provided by the platform. Here is its simplest form:

Other Forms of getBytes() are also available. getBytes() is most useful when you are exporting a String value into an environment that does not support 16-bit Unicode characters. for example, most Internet protocols and text file formats use 8-bit ASCII for all text interchange.
toCharArray() method: if you want to convert all the characters in a String object into a character array, the easiest way is to call toCharArray(). It returns an array of characters for the entire String. It has this general form:

This function is provided as a convenience, since it is possible to use getChars() to achiev the same result.

Special String Oprations


These Operations include the automatic creation of new String instances from string literals, concatenation of multiple String objects by use of the "+" operator, and the conversion of other data types to a string representation.
String Literals: There is an easier way to do this using a String literal. For each String literal in your program, java automatically constructs a String object. Thus, you can use a string literal to initialize a String object. For Example:

A String object is created for every string literal, you can use a string literal any place you can use a String object.For Example, you can call methods directly on a quoted string as if it were an object reference, as the following statement shows. It calls the leangth() method on the string "abc". As expected, it prints "3".

String Concatenation: In java does not allow operators to applied to String objects. The one exception to this rule is the + operator, which concatenates two strings, producing a String object as the result. this allows you to chain together a series of + operations. for Example:

This display the string "he is 27 years old."
String Concatenation with Other Data Type:

In this case, age is an int rather then another String, but the output is display "he is 9 years old.". This is because the int value in age is automatically converted into its String representation within a String object. This String is then concatenated as before. the compiler will convert an operand to its string equivalent whenever the other operand of the + is an instance of String.
Be careful when you mix other types of operations with string concatenation expression, however. you might get surprising results. consider the following:

This fragment displays four: 22 rather then the four: 4.
That you probably expected. Here's way. Operator precedence causes the concatenation of "four" with the string equivalent of 2 to take please first. This result is then concatenated with the string equivalent of 2 a second time. to complete the integer addition first, you must use parentheses, like this:

Out put is four: 4.
String Conversion and toString(): When java converts data into its string representation during concatenation, it does so by calling one of the overloaded versions of the String conversion method valueOf() defined by String. valueOf() is overloaded for all the primitive types and for type object. For the Primitive types, valueOf() returns a string that contains the human-readable equivalent of the value with which it is called. for objects. valueOf() call the toString() method on the object. Here, let's examine the toString() method, because it is the means by which you can determine the string representation for objects of classes that you create.
Every class implements toString() because it is defined by Object. However, the default implementation of toString() is seldom sufficient. For Most important classes that you create, you will want to override toString() and provide your own string representations. fortunately, this is easy to do. the toString() method has this general form:
String tiString()
To implement toString(), simply return a String object that contains the human-readable string that appropriately describes an object of your class.
For Example:

Output :
                        Box b:Dimentions are 10.0 By 12.0 By 14.0
                        Dimentions are 10.0 By 12.0 By 14.0
As you can see, Box's toString() method os automatically invoked when a Box object is used in a concatenation expression or in a call to Println().

Sunday 29 May 2016

The String Constructors

No comments :
The String class supports several constructors. To create an empty String, call the default constructor. for example,

will create an instance of String with no characters in it.
The String class provides a variety of constructor to handle this. To create a String initialized by an array of characters, use the constructor show here:

Here is an example:

This constructor initializes s with the string "manoj".
You can secify a subrange of a character array as an initializer using the following constructor:

Here, startIndex specifies the index at which the subrange begins, namd numChars specifies the number of characters to use. Here is an example:

This initializes s which the characters "noj".
You can construct a String object that contains the same character sequence as another String object using this constructor:

Here, strObj is String object. consider this example:

This programming generates the following output:
manoj
manoj
As you can see, s1 and s2 contain the same String.
Java's char type uses 16 bit to represent the basic Unicode character set, the typical formate for strings on the Internet uses arrays of 8-bit bytes constructed from the ASCII characters that initialize a string when given a byte array. Two forms are show here:

Here is an example:

This programming generates the following output:
MANOJ
NOJ

You can construct a string from a StringBuffer by using the constructor shown here:

You can construct a string from a StringBuilder by using the constructor shown here:

The following constructor supports the extended Unicode character set:

Here, codePrints is an array that contains Unicode code points.