Monday, 14 March 2016

String Program like convert string to integer

Q-

How to convert string to int in Java

ans-
1st:- Using Integer.parseInt()
2nd:-Using Integer.valueOf()
example:-
package com.string.to.integer;

public class StringtoInteger2 {

public static void main(String[] args) {
String str="-123";
int num1=100;
int num2=Integer.valueOf(str);
int sum=num1+num2;
System.out.println(""+sum);

}

}

Q2:-

Convert int to String conversion?

ans:-There are two ways to convert an integer value to a String.
1) Method 1: Using String.valueOf(int i):
2) Method 2: Using Integer.toString(int i)


1) Method 1: Using String.valueOf(int i): This method takes integer value as an argument and returns a string representing the int augment.
Method declaration:
public static String valueOf(int i)
parameters:
i – integer that needs to be converted to a string
returns:
A string representing the integer argument

2) Method 2: Using Integer.toString(int i): This method works same as String.valueOf(int i) method. It belongs to the Integer class and converts the specified integer value to String. for e.g. if passed value is 101 then the returned string value would be “101”.

example:-int ivar2 = 200;
String str2 = Integer.toString(ivar2);

example:-
package com.convertnt.to.convertstring;

public class ConvertInttoString {

public static void main(String[] args) {
/* Method 1: using valueOf() method
         * of String class.
         */
int var=111;
String str2=String.valueOf(var);
System.out.println(""+str2);
/* Method 2: using toString() method 
         * of Integer class
         */

int var2=222;
String str3=Integer.toString(var2);
System.out.println(""+str3);
}

}

How to convert String to Double in Java?

ans:-Method 1: Using Double.parseDouble
       Method 2: Using Double.valueOf
     Method 3: Double class constructor
============ Example of string to double=======

package com.convert.string.to.doublle;

public class StringToDouble {

public static void main(String[] args) {
//Using parseDouble
String str1="12.33";
Double var=Double.parseDouble(str1);
System.out.println(var);
//Using valueOf method
String str2="123.234";
Double var2=Double.valueOf(str2);
System.out.println(var2);
//using Double class constructor
String str4="1234.2345";
Double var3=new Double(str4);
System.out.println(var3);
}

}

Q-double to string conversion?

ans:- 

Method 1:Using String.valueOf() method 

Method 2: Using Double.toString() method.

Example:-
package com.convert.doublle.to.string;

public class DoubleToString {

public static void main(String[] args) {
/* Method 1: using valueOf() method
       * of String class
       */
double var=121.23;
String str=String.valueOf(var);
System.out.println("String1 is:"+str);
/* Method 2: using toString() method 
       * of Double class
       */
double var2=123.342;
String str2=Double.toString(var2);
System.out.println("String2 is:"+str2);
}

}

Q-How to convert String to long in Java?
ans:-1) Long.parseLong:
      2) Long.valueOf:
Example:-
package com.convert.string.convertlong;

public class StringtoLong {

public static void main(String[] args) {
String str="203456";
      //Conversion using parseInt method
      long num = Long.parseLong(str);

      //Conversion using valueOf method
      long num2 = Long.valueOf(str);

      //Conversion: Long(String s) constructor
      long num3 = new Long(str);

      //Displaying variables values
      System.out.println(num);
      System.out.println(num2);
      System.out.println(num3);
}

}
Q-long to String conversion?
ans:-1) Method 1: Using String.valueOf(long l):
2) Method 2: Using Long.toString(long l): 
Example:-
package com.convert.string.convertlong;

public class LongToString {

public static void main(String[] args) {
/* Method 1: using valueOf() method
         * of String class.
         */
        long lvar = 123;
        String str = String.valueOf(lvar);
        System.out.println("String is: "+str);
        
        /* Method 2: using toString() method 
         * of Long class
         */
        long lvar2 = 200;
        String str2 = Long.toString(lvar2);
        System.out.println("String2 is: "+str2);
}

}
Q-

Convert String to boolean primitive in Java: parseBoolean() method

ans:-using Boolean.parseBoolean(str);
Example:-

package com.convert.string.convertlong;

public class StringToBoolean {

public static void main(String[] args) {
// String Objects
     String str = "false";
     // Case does not matter for conversion
     String str2 = "TrUe";
  
     // String to boolean conversion
     boolean bvar = Boolean.parseBoolean(str);
     boolean bvar2 = Boolean.parseBoolean(str2);
   
     // Displaying boolean values
     System.out.println("boolean value of String str is: "+bvar);
     System.out.println("boolean value of String str2 is: "+bvar2);

}

}

Java – boolean to String conversion

ans:-1) Method 1: Using String.valueOf(boolean b): 
2) Method 2: Using Boolean.toString(boolean b):
Example:-
package com.convert.booleans.convertstring;

public class BooleanToString {

public static void main(String[] args) {
/* Method 1: using valueOf() method
         * of String class.
         */
        boolean boovar = true;
        String str = String.valueOf(boovar);
        System.out.println("String is: "+str);
        
        /* Method 2: using toString() method 
         * of Boolean class
         */
        
        boolean boovar2 = false;
        String str2 = Boolean.toString(boovar2);
        System.out.println("String2 is: "+str2);
        
}

}


String to ArrayList conversion

ans:-1) First we are splitting the string using String split() method and storing the substrings into a String array.
2) Creating an ArrayList while passing the substring reference to it using Arrays.asList() method.

     import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class StringToArrayList {

public static void main(String[] args) {

String str1="11,32,45,67,88";
String arr[]=str1.split(",");

List<String> al=new ArrayList<String>();
al=Arrays.asList(arr);
for (String s : al) {
System.out.println(s);
}
//System.out.println(al);

}

}

How to convert a char array to a string in Java?

ans:-There are two ways to convert a char array (char[]) to String in Java:
1) Creating String object by passing array name to the constructor
2) Using valueOf() method of String class.
Example:-

public class CharArrayToString {

public static void main(String[] args) {
// Method 1: Using String object
     char ch[] = {'g', 'o', 'o', 'd', ' ', 'm', 'o', 'r', 'n', 'i', 'n', 'g'};
     
     // Method 1: Using String object
     String str1=new String(ch);
     System.out.println(str1);
     
     // Method 1: Using ValueOf Method
     String str2=String.valueOf(ch);
     System.out.println(str2);
}

}
Q-Reverse a String Without using String API?
ans-input my name is xyz
      output:-xyz is name my
example:-
public class ReverseStringWithoutUsingMethod {

public static void main(String[] args) {

System.out.println("Enter String");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
String arr[] = input.split(" ");
for (int i = arr.length-1; i >= 0; i--) {
System.out.print(arr[i] + " ");
}
}


}
Q-how to replace string?
input: how are you modi
output:-are how  modi you
Example:
public class StringREplace {

public static void main(String[] args) {

System.out.println("Enter string:- ");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();

String s[] = input.split(" ");
//for even 
if (s.length % 2 == 0) {
for (int i = 0; i <= s.length - 1; i++) {
if (i % 2 != 0)
System.out.print(s[i - 1] + " ");
else
System.out.print(s[i + 1] + " ");
}
//for odd
} else {
for (int i = 0; i <= s.length - 2; i++) {
if (i % 2 != 0)
System.out.print(s[i - 1] + " ");
else
System.out.print(s[i + 1] + " ");
}
if ((s.length - (s.length - 1)) <= 1) {
System.out.print(s[s.length - 1] + " ");
}
}
}

}

Q-How to reverse a String  same possition (alternate)  in java
answer should be come like this
input:- i love my india
output: i evol my aidni

Ezample:-import java.util.Scanner;

public class ReplacesomeString {

public static String rev(String x) {

StringBuilder sb = new StringBuilder(x);
String y = sb.reverse().toString();
return y;
}

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a String:- ");
String input = sc.nextLine();
String arr[] = input.split(" ");
for (int i = 0; i < arr.length; i++) {
if (i % 2 != 0) {
String x = arr[i];
String output = rev(x);
arr[i] = output;
}
}
System.out.println("After Operation Output Are:- ");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}

}

Q- How to find Prime number ?
ans-

public class PrimeNumber {

public static void main(String[] args) {
int n = 3;
int temp = 1;
for (int i = 2; i < 200; i++) {
for (int j = 2; j < n; j++) {
if (n % j == 0) {
temp = 0;
break;
}
}
if (temp != 0)
System.out.println("Prime " + n);
n++;
temp=1;
}
}
}
Q- how to print pattern ?
I
I N
I N D
I N D I
I N D I A
ANS:-
import java.util.Scanner;


public class PatternINDIA {

public static void main(String[] args) {
System.out.println("Enter string:- ");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
for (int i = 0; i < input.length(); i++) {
for (int j = 0; j <= i; j++) {
System.out.print(input.charAt(j)+" ");
}
System.out.println();
}

}

}

Q-HOW TO DELETE COMMON VALUE FROM ARRAY LIST.. we have have three arrayList?
note:-i want delete 4 and 5 from frst arrayList
arrayList 1[1, 2, 3, 4, 5, 6, 7, 8, 9]
arrayList 1[1, 2, 3, 4, 5]
arrayList 1[1, 2, 3]

output:-should be come
4, 5]
[1, 2, 3, 6, 7, 8, 9]

Example:-package com.remove.intoarraylist;

import java.util.ArrayList;

public class Array {

public static void main(String[] args) {
ArrayList<Integer> al1=new ArrayList<Integer>();
al1.add(1);
al1.add(2);
al1.add(3);
al1.add(4);
al1.add(5);
al1.add(6);
al1.add(7);
al1.add(8);
al1.add(9);
ArrayList<Integer> al2=new ArrayList<Integer>();
al2.add(1);
al2.add(2);
al2.add(3);
al2.add(4);
al2.add(5);
ArrayList<Integer> al3=new ArrayList<Integer>();
al3.add(1);
al3.add(2);
al3.add(3);
System.out.println("arrayList 1"+al1);
System.out.println("arrayList 1"+al2);
System.out.println("arrayList 1"+al3);
al2.removeAll(al3);
System.out.println(al2);
al1.removeAll(al2);
System.out.println(al1);
}

}


Sunday, 13 March 2016

Java String Class and its methods

String Class and its methods:-

Q what is string?
ans-String is nothing but a sequence of characters, for e.g. “Hello” is a string of 5 characters. In java, string is an immutable object which means it is constant and can cannot be changed once it has been created. 

Creating a String

There are two ways to create a String in Java
  1. String literal
  2. Using new keyword

Difference between string object and string literal  :


  • Whenever you call new() in JAVA it create an object in heap.
  • String literals will go into String Constant Pool.
  • For objects JVM used String constant pool which is for efficient memory management in java. Unlike other Java Objects, instead of managing String object on heap area.
  • Example program:
  1. public class StringCreationDemo {     
  2.                                                                                   
  3. public static void main (String args[]) {
  4.  
  5.     String str1 = "Hello"; 
  6.     String str2 = "Hello";
  7.  
  8.     System.out.println("str1 and str2 : literal");   
  9.     System.out.println("str1 == str2 is " + (str1 == str2)); 
  10.  
  11.     String str3 = new String("Hello"); 
  12.     String str4 = new String("Hello");
  13.  
  14.     System.out.println("str3 and str4 : new operator");   
  15.     System.out.println(" str3 == str4 is " + (str3 == str4)); 
  16.  
  17.     String str5 = "Hel"+ "lo"; 
  18.     String str6 = "He" + "llo";
  19.  
  20.     System.out.println("str5 and str6 : expression.");   
  21.     System.out.println("    str5 == str6 is " + (str5 == str6)); 
  22.  
  23.   }
  24. }  
Q-what is string literal?
ans-string literal is collection of reference to string object.
example:-if we define same content two different object, it refer to same object in string pool.
String str1="welcome"; 
String str2="Welcome";

Using New Keyword:-

but using new keyword if we create two object using new keyword than it refer to two diffrent object

when we tried to assign the same string object to two different literals, compiler only created one object and made both of the literals to point the same object. To overcome that approach we can create strings like this:
example:-
String str1 = new String("Welcome");
String str2 = new String("Welcome");
In this case compiler would create two different object in memory having the same text.

Why Strings are immutable in java?

ans:-Because java uses the concept of string literal.Suppose there are 5 reference variables,all referes to one object "welcome".If one reference variable changes the value of the object, it will be affected to all the reference variables. That is why string objects are immutable in java.
example:-all wrapper class are example of string immuatable 
Advantage:-to improve the heap memory.
String is immutable for several reasons:-
1-requirement of string pool:-
2:-Security
3:-Synchronization:-
4:-Caching:-

1. Requirement of String Pool.

The following code will create only one string object in the heap.
String string1 = "abcd";
String string2 = "abcd";
Here is how it looks:
java-string-pool
2. Security
String is widely used as a parameter for many java classes, e.g. network connection, opening files, etc. Were String not immutable, a connection or file would be changed and lead to a serious security threat
Here is a code example:
boolean connect(string s){
    if (!isSecure(s)) { 
throw new SecurityException(); 
}
    //here will cause problem, if s is changed before this by using other references.    
    causeProblem(s);
}

3-Immutable objects are naturally thread-safe
Because immutable objects can not be changed, they can be shared among multiple threads freely. This eliminates the requirements of doing synchronization.
In summary, String is designed to be immutable for the sake of efficiency and security. This is also the reason why immutable classes are preferred in general.
4.Caching Hashcode
Q- how to make immutable class?
ans:-1:- decalare the class as a  final so subclass we should not modify,
             2:-declare the variable firstname as private last name as a final.


============String Methods=========

  1. char charAt(int index): It returns the character at the specified index. Specified index value should be between 0 to length() -1 both inclusive. It throws IndexOutOfBoundsException if index<0||>= length of String.
  2. boolean equals(Object obj): Compares the string with the specified string and returns true if both matches else false.
  3. boolean equalsIgnoreCase(String string): It works same as equals method but it doesn’t consider the case while comparing strings. It does a case insensitive comparison
  4. int hashCode(): It returns the hash code of the string.
  5. int compareTo(String string): This method compares the two strings based on the Unicode value of each character in the strings.
  6. int indexOf(int ch): Returns the index of first occurrence of the specified character ch in the string.
  7. int indexOf(int ch, int fromIndex): Same as indexOf method however it starts searching in the string from the specified fromIndex.
  8. int lastIndexOf(int ch): It returns the last occurrence of the character ch in the string.
  9. int lastIndexOf(int ch, int fromIndex): Same as lastIndexOf(int ch) method, it starts search from fromIndex.
  10. int indexOf(String str): This method returns the index of first occurrence of specified substring str.
  11. int lastindexOf(String str): Returns the index of last occurrence of string str.
  12. String substring(int beginIndex, int endIndex): Returns the substring. The substring starts with character at beginIndex and ends with the character at endIndex.
  13. String replace(char oldChar, char newChar): It returns the new updated string after changing all the occurrences of oldChar with the newChar.
  14. String replaceFirst(String regex, String replacement): It replaces the first occurrence of substring that fits the given regular expression “regex” with the specified replacement string.
  15. String replaceAll(String regex, String replacement): It replaces all the occurrences of substrings that fits the regular expression regex with the replacement string.
  16. String[] split(String regex, int limit): It splits the string and returns the array of substrings that matches the given regular expression. limit is a result threshold here.
  17. String[] split(String regex): Same as split(String regex, int limit) method however it does not have any threshold limit.
  18. String toLowerCase(Locale locale): It converts the string to lower case string using the rules defined by given locale.
  19. String toLowerCase(): Equivalent to toLowerCase(Locale. getDefault()).
  20. String toUpperCase(Locale locale): Converts the string to upper case string using the rules defined by specified locale.
  21. String toUpperCase(): Equivalent to toUpperCase(Locale.getDefault()).
  22. String trim(): Returns the substring after omitting leading and trailing white spaces from the original string.