Drop Down MenusCSS Drop Down MenuPure CSS Dropdown Menu

Tuesday, 31 January 2017

String Class Constructors In Java

String class provides various constructor .To create empty constructor we call default constructor as String s = new String(); Here we will discuss each and every constructor one by one. In below program we have discussed each constructor in detail.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;

public class StringConstructors {

 public static void main(String[] args) throws UnsupportedEncodingException {
  //Default Constructor
  String s1 = new String();

  //Constructor with char array 
  char[] charArr = {'j','a','v','a'};
  String s2 = new String(charArr);
  System.out.println("S2 : "+s2);
  
  //Constructor with byte array
  String original = new String("A" + "\u00ea" + "\u00f1" + "\u00fc" + "C");
  String s3 = new String(original.getBytes());
  System.out.println("S3 : "+s3);
  
  //Constructor with String
  String s4 = new String("Java Identifiers");
  System.out.println("S4 : "+s4);
  
  //Constructor with StringBuffer
  String s5 = new String(new StringBuffer("Java"));
  System.out.println("S5 : "+s5);
  
  //Constructor with StringBuilder
  String s6 = new String(new StringBuilder("Java"));
  System.out.println("S6 : "+s6);  
  
  //Constructor with Bytes and character encoding
  byte[] utf8Bytes = original.getBytes("UTF8");
  String s7 = new String(utf8Bytes, "UTF8");
  System.out.println("S7 : "+s7);  
  
  //Constructor with Bytes and Charset class
  String s8 = new String(utf8Bytes,Charset.defaultCharset());
  System.out.println("S8 : "+s8);
  
  //Constructor with char array, offset and count
  String s9 = new String(charArr,0,2);
  System.out.println("S9 : "+s9);
  
  //Constructor with ASCII array
  byte ascii[] = {65, 66, 67, 68, 69, 70 }; 
  String s10 = new String(ascii);
  System.out.println("S10 : "+s10);
 }

}

Output:

S2 : java
S3 : AêñüC
S4 : Java Identifiers
S5 : Java
S6 : Java
S7 : AêñüC
S8 : AêñüC
S9 : ja
S10 : ABCDEF



      
Blog Author - Pushkar Khosla,
Software Developer by Profession with 3.0 Yrs of Experience , through this blog i'am sharing my industrial Java Knowledge to entire world. For any question or query any one can comment below or mail me at pushkar.itsitm52@gmail.com.

This blog is all about to learn Core Java ,Interview Programs and Coding tricks to polish your Java Knowledge. If you like the content of this blog please share this with your friends.



Read More »

Monday, 30 January 2017

What is String Concatenation In Java ?

String concatenation means joining two or more strings. For example full name is a combination of first name and last name. Java provides multiple ways to concatenate string 
  1. + operator
  2. concat() method
  3. StringBuffer class
  4. StringBuilder class
+ operator:
This is the the most easy way to concatenate string. For example suppose we have two string i.e. "java" and "identifiers", the concatenation of "java"+"identifiers" will produce the output "javaidentifiers".

concat() method:
This is a string class method which is used to concat two or more strings. For example suppose we have two strings i.e. "java" and "identifiers" ,we can concate these strings as "java".concat("identifiers"); and this will produce the output "javaidentifiers".

StringBuffer class:
This class belongs to java.lang; package and this class provide append() method to concate strings. If we want to concate strings using this class then we have to create object of this class and then using append() method we can concate string as shown below.
StringBuffer sb = new StringBuffer();
sb.append("java").append("identifiers");
this will produce the output "javaidentifiers".

StringBuilder class:
This class is same as StringBuffer class click to know differences between StringBuffer and StringBuilder. This class also belongs to java.lang; package and this class also provide append() method to concate strings. If we want to concate strings using this class then we have to create object of this class and then using append() method we can concate string as shown below.
StringBuilder sb = new StringBuilder();
sb.append("java").append("identifiers");
this will produce the output "javaidentifiers".

Example of String Concatenation:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class StringConcatenation {

 public static void main(String[] args) {
  String s1 = "Java ";
  String s2 = "Identifier";
  
  //String Concatenation using + operator
  System.out.println(s1+s2);
  
  //String Concatenation using concat() method
  System.out.println(s1.concat(s2));
  
  //String Concatenation using StringBuffer Class
  StringBuffer sb = new StringBuffer();
  sb.append(s1).append(s2);
  System.out.println(sb);
  
  //String Concatenation using StringBuilder Class
  StringBuilder sb1 = new StringBuilder();
  sb1.append(s1).append(s2);
  System.out.println(sb1);
 }
}

Output:

Java Identifier
Java Identifier
Java Identifier
Java Identifier

      
Blog Author - Pushkar Khosla,
Software Developer by Profession with 3.0 Yrs of Experience , through this blog i'am sharing my industrial Java Knowledge to entire world. For any question or query any one can comment below or mail me at pushkar.itsitm52@gmail.com.

This blog is all about to learn Core Java ,Interview Programs and Coding tricks to polish your Java Knowledge. If you like the content of this blog please share this with your friends.



Read More »

Sunday, 29 January 2017

What is String Comparison ?

String class have numbers of methods for comparing strings and portions of strings. Strings can be compare on the basis of content and their references. Below some string class methods which are used to compare strings are :

Modifier and Method Name
Description
boolean endsWith(String suffix)
boolean startsWith(String prefix)
Returns true if this string ends with or begins with the substring specified as an argument to the method.
boolean startsWith(String prefix, int offset)
Considers the string beginning at the index offset, and returns true if it begins with the substring specified as an argument.
int compareTo(String anotherString)
Compares two strings lexicographically. Returns an integer indicating whether this string is greater than (result is > 0), equal to (result is = 0), or less than (result is < 0) the argument.
int compareToIgnoreCase(String str)
Compares two strings lexicographically, ignoring differences in case. Returns an integer indicating whether this string is greater than (result is > 0), equal to (result is = 0), or less than (result is < 0) the argument.
boolean equals(Object anObject)
Returns true if and only if the argument is a String object that represents the same sequence of characters as this object.
boolean equalsIgnoreCase(String anotherString)
Returns true if and only if the argument is a String object that represents the same sequence of characters as this object, ignoring differences in case.
boolean matches(String regex)
Tests whether this string matches the specified regular expression. 

1) String Comparison using equals() method
this method compares two strings content
String s1 = "pushkar";
String s2 = "pushkar";  
System.out.println(s1.equals(s2));
It will print true because both strings s1 and s2 have same content.

2) String Comparison using equalsIgnoreCase() method
this method compares two strings content weather, it's in uppercase or lowercase, but both strings contains same sequence of characters .

String s1 = "pushkar";
String s2 = "PUSHKAR";
System.out.println(s1.equalsIgnoreCase(s2));
It will print true because this method will ignore case.

3) String Comparison using == operator
The == operator is used to compare two strings references not their content. Here references means their memory addresses, weather they belongs to same memory or not. Because Java uses two memory locations to store Strings i.e all the String literals are store in StringConstantPool and Strings created with new operator are store in Heap memory.
String s1 = "pushkar";
String s2 = "pushkar";
System.out.println(s1 == s2); // Line 1
String s3 = new String("pushkar");
System.out.println(s2 == s3); // Line 2
Line 1 will print true because both refer to same reference.
Line 2 will print false because both have different memory references.

4) String Comparison using compareTo() method
This method return integer values i.e. 0,1 and -1. Suppose we have two strings s1 and s2 and if s1 == s2 it will return 0, if s1 > s2 it will return 1 and if s1 < s2 it will return -1.
String s1 = "pushkar";
String s2 = "pushkar";
String s3 = "pushkara";
  
System.out.println(s1.compareTo(s2)); //it will print 0
System.out.println(s3.compareTo(s1)); //it will print 1
System.out.println(s1.compareTo(s3)); //it will print -1



      
Blog Author - Pushkar Khosla,
Software Developer by Profession with 3.0 Yrs of Experience , through this blog i'am sharing my industrial Java Knowledge to entire world. For any question or query any one can comment below or mail me at pushkar.itsitm52@gmail.com.

This blog is all about to learn Core Java ,Interview Programs and Coding tricks to polish your Java Knowledge. If you like the content of this blog please share this with your friends.



Read More »

What is String Class in Java ?

Class String

All Implemented Interfaces:
Serializable, CharSequence, Comparable<String>

Declaration of String:
public final class String
extends Object
implements Serializable, Comparable<String>, CharSequence

String is a sequence of characters and java implements string as a object of string type.String is a final class which belongs to java.lang; package. String is also a immutable(means value can not changed after it is created) class. Where as StringBuffer and StringBuilder are mutable(means value can be changed after it is created) class these classes are also belongs to java.lang; package.

For Example:
String str = "pushkar";

Above string is equivalent to 
char[] arr = {'p','u','s','h','k','a','r'};
String str = new String(arr);

There are two ways to create string objects in java:
1) using String Literals : String str = "pushkar";
2) using new operator : String str = new String("pushkar");

String literals are store in String Constant Pool where as string created with new operator are store in heap memory.

Java provide special support of string concatenation using + operator for conversion of other objects to string.

Constructor Summary of String Class:

Constructor
Description
String()
Initializes a newly created String object so that it represents an empty character sequence.
String(byte[] bytes)
Constructs a new String by decoding the specified array of bytes using the platform's default charset.
String(byte[] bytes, Charset charset)
Constructs a new String by decoding the specified array of bytes using the specified charset.
String(byte[] ascii, int hibyte)
Deprecated.
This method does not properly convert bytes into characters. As of JDK 1.1, the preferred way to do this is via the String constructors that take a Charset, charset name, or that use the platform's default charset.
String(byte[] bytes, int offset, int length)
Constructs a new String by decoding the specified subarray of bytes using the platform's default charset.
String(byte[] bytes, int offset, int length, Charset charset)
Constructs a new String by decoding the specified subarray of bytes using the specified charset.
String(byte[] ascii, int hibyte, int offset, int count)
Deprecated.
This method does not properly convert bytes into characters. As of JDK 1.1, the preferred way to do this is via the String constructors that take a Charset, charset name, or that use the platform's default charset.
String(byte[] bytes, int offset, int length, String charsetName)
Constructs a new String by decoding the specified subarray of bytes using the specified charset.
String(byte[] bytes, String charsetName)
Constructs a new String by decoding the specified array of bytes using the specified charset.
String(char[] value)
Allocates a new String so that it represents the sequence of characters currently contained in the character array argument.
String(char[] value, int offset, int count)
Allocates a new String that contains characters from a subarray of the character array argument.
String(int[] codePoints, int offset, int count)
Allocates a new String that contains characters from a subarray of the Unicode code point array argument.
String(String original)
Initializes a newly created String object so that it represents the same sequence of characters as the argument; in other words, the newly created string is a copy of the argument string.
String(StringBuffer buffer)
Allocates a new string that contains the sequence of characters currently contained in the string buffer argument.
String(StringBuilder builder)
Allocates a new string that contains the sequence of characters currently contained in the string builder argument.

Method Summary of String Class:

Modifier and Method Name
Description
char charAt(int index)
Returns the char value at the specified index.
int codePointAt(int index)
Returns the character (Unicode code point) at the specified index.
int codePointBefore(int index)
Returns the character (Unicode code point) before the specified index.
int codePointCount(int beginIndex, int endIndex)
Returns the number of Unicode code points in the specified text range of this String.
int compareTo(String anotherString)
Compares two strings lexicographically.
int compareToIgnoreCase(String str)
Compares two strings lexicographically, ignoring case differences.
String concat(String str)
Concatenates the specified string to the end of this string.
boolean contains(CharSequence s)
Returns true if and only if this string contains the specified sequence of char values.
boolean contentEquals(CharSequence cs)
Compares this string to the specified CharSequence.
boolean contentEquals(StringBuffer sb)
Compares this string to the specified StringBuffer.
static String copyValueOf(char[] data)
Returns a String that represents the character sequence in the array specified.
static String copyValueOf(char[] data, int offset, int count)
Returns a String that represents the character sequence in the array specified.
boolean endsWith(String suffix)
Tests if this string ends with the specified suffix.
boolean equals(Object anObject)
Compares this string to the specified object.
boolean equalsIgnoreCase(String anotherString)
Compares this String to another String, ignoring case considerations.
static String format(Locale l, String format, Object... args)
Returns a formatted string using the specified locale, format string, and arguments.
static String format(String format, Object... args)
Returns a formatted string using the specified format string and arguments.
byte[] getBytes()
Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array.
byte[] getBytes(Charset charset)
Encodes this String into a sequence of bytes using the given charset, storing the result into a new byte array.
void getBytes(int srcBegin, int srcEnd, byte[] dst, int dstBegin)
Deprecated.
This method does not properly convert characters into bytes. As of JDK 1.1, the preferred way to do this is via the getBytes() method, which uses the platform's default charset.
byte[] getBytes(String charsetName)
Encodes this String into a sequence of bytes using the named charset, storing the result into a new byte array.
void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
Copies characters from this string into the destination character array.
int hashCode()
Returns a hash code for this string.
int indexOf(int ch)
Returns the index within this string of the first occurrence of the specified character.
int 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.
int indexOf(String str)
Returns the index within this string of the first occurrence of the specified substring.
int indexOf(String str, int fromIndex)
Returns the index within this string of the first occurrence of the specified substring, starting at the specified index.
String intern()
Returns a canonical representation for the string object.
boolean isEmpty()
Returns true if, and only if, length() is 0.
int lastIndexOf(int ch)
Returns the index within this string of the last occurrence of the specified character.
int 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.
int lastIndexOf(String str)
Returns the index within this string of the last occurrence of the specified substring.
int 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.
int length()
Returns the length of this string.
Boolean matches(String regex)
Tells whether or not this string matches the given regular expression.
int offsetByCodePoints(int index, int codePointOffset)
Returns the index within this String that is offset from the given index by codePointOffset code points.
boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)
Tests if two string regions are equal.
boolean regionMatches(int toffset, String other, int ooffset, int len)
Tests if two string regions are equal.
String replace(char oldChar, char newChar)
Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
String replace(CharSequence target, CharSequence replacement)
Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence.
String replaceAll(String regex, String replacement)
Replaces each substring of this string that matches the given regular expression with the given replacement.
String replaceFirst(String regex, String replacement)
Replaces the first substring of this string that matches the given regular expression with the given replacement.
String[] split(String regex)
Splits this string around matches of the given regular expression.
String[] split(String regex, int limit)
Splits this string around matches of the given regular expression.
boolean startsWith(String prefix)
Tests if this string starts with the specified prefix.
boolean startsWith(String prefix, int toffset)
Tests if the substring of this string beginning at the specified index starts with the specified prefix.
CharSequence subSequence(int beginIndex, int endIndex)
Returns a new character sequence that is a subsequence of this sequence.
String substring(int beginIndex)
Returns a new string that is a substring of this string.
String substring(int beginIndex, int endIndex)
Returns a new string that is a substring of this string.
char[] toCharArray()
Converts this string to a new character array.
String toLowerCase()
Converts all of the characters in this String to lower case using the rules of the default locale.
String toLowerCase(Locale locale)
Converts all of the characters in this String to lower case using the rules of the given Locale.
String toString()
This object (which is already a string!) is itself returned.
String toUpperCase()
Converts all of the characters in this String to upper case using the rules of the default locale.
String toUpperCase(Locale locale)
Converts all of the characters in this String to upper case using the rules of the given Locale.
String trim()
Returns a copy of the string, with leading and trailing whitespace omitted.
static String valueOf(boolean b)
Returns the string representation of the boolean argument.
static String valueOf(char c)
Returns the string representation of the char argument.
static String valueOf(char[] data)
Returns the string representation of the char array argument.
static String valueOf(char[] data, int offset, int count)
Returns the string representation of a specific subarray of the char array argument.
static String valueOf(double d)
Returns the string representation of the double argument.
static String valueOf(float f)
Returns the string representation of the float argument.
static String valueOf(int i)
Returns the string representation of the int argument.
static String valueOf(long l)
Returns the string representation of the long argument.
static String valueOf(Object obj)
Returns the string representation of the Object argument.


      
Blog Author - Pushkar Khosla,
Software Developer by Profession with 3.0 Yrs of Experience , through this blog i'am sharing my industrial Java Knowledge to entire world. For any question or query any one can comment below or mail me at pushkar.itsitm52@gmail.com.

This blog is all about to learn Core Java ,Interview Programs and Coding tricks to polish your Java Knowledge. If you like the content of this blog please share this with your friends.



Read More »