String hadnling

String is the sequence of character represented by the object of String class in java. Two other classes’ string buffer and string builder can be used for same thing. String object provides some predefined method those are used to manipulate the string.
String object is said to be the immutable this means that you can not manipulate the string object. But you can work with that object. When you manipulate the string object then new string object is created and it consists of manipulated contents. But it is hard to observe by programmer without experience.
Here to solve this problem you can use the String buffer class to create the string object in which you can manipulate the string contents with the same object. That is the object of string class the mutable.
String buffer is the thread safe.

Another class to create the mutable string objects is string builder class. But it is no thread safe.

Creating String

There are many ways to create the string object

1
You can declare string reference variable and assign the string lateral to it, then string object is created automatically and the reference of that object is stored in the reference variable you declared. for example
String str=”this my first string”;

2
You can create the string object using new operator. What you want to write in string is passed in the constructor of string class. there are 11 constructor those are used to create the string through different ways
String str=new String(“this is my first string”);

3
Creating the string using character array
char[] chs = { 'h', 'e', 'l', 'l', 'o', '.'};
String srt = new String(chs);

4
Creating the string using sub character array
char[] chs = { 'h', 'e', 'l', 'l', 'o', '.'};
String srt = new String(chs,2,2);

5
If you leave the string constructor blank, the n it creates the empty string.
String str=new String();

6
There is the constructor  String(byte[] bytes) which can Constructs a new String by decoding the specified array of bytes using the platform's default charset. The length of the new String is a function of the charset, and hence may not be equal to the length of the byte array.
byte b[]={65,66,67,68,68,70};
String str3=new String(b);
System.out.println(str3);
Output: ABCDDF
7
Creating the string of the sub array of byte from specified position of specified length using the constructor  String(byte[] bytes, int offset, int length)

byte b[]={65,66,67,68,68,70};
String str6=new String(b,2,3);
System.out.println(str6);
Output: CDE
8
Creating string from sub array byte by decoding the bytes using specified CharSet. Some Character set are following.

US-ASCII Seven-bit ASCII, a.k.a. ISO646-US, a.k.a. the Basic Latin block of the Unicode character set
ISO-8859-1   ISO Latin Alphabet No. 1, a.k.a. ISO-LATIN-1
UTF-8 Eight-bit UCS Transformation Format
UTF-16BE Sixteen-bit UCS Transformation Format, big-endian byte order
UTF-16LE Sixteen-bit UCS Transformation Format, little-endian byte order
UTF-16 Sixteen-bit UCS Transformation Format, byte order identified by an optional byte-order mark
Try{
     byte b7[]={65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80};
     String str7=new String(b7,0,13,"ISO-8859-1");
     System.out.println(str7);
}catch(UnsupportedEncodingException e){System.out.println(e);}
This constructor throws an exception.
9
Creating string of whole byte array
This is same as above only difference is that we passing complete byte array in the constructor.
Try{
     byte b7[]={65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80};
     String str7=new String(b7,"ISO-8859-1");
     System.out.println(str7);
}catch(UnsupportedEncodingException e){System.out.println(e);}

10
Crating string using array of Unicode characters

int unicodes[]={'\u0041','\u0042','\u0043','\u0044','\u0045','\u0046'};
String str8=new String(unicodes,0,5);
System.out.println(str8);
Output: ABCDE
11
Creating string using anther string
        String str1="This is first string";       
        String str2=new String(str1);
        System.out.println(str2);
12
Creating string from string buffer
                        StringBuffer sb=new StringBuffer("Hemraj");
                        String str12=new String(sb);
                        System.out.println(str12);
13
Creating string from string builder
                        StringBuilder sbu=new StringBuilder("Hemraj");
                        String str13=new String(sbu);
                        System.out.println(str13);


class MyString
{
    public static void main(String args[])
    {
        String str1="This is first string";
        System.out.println(str1);
        
        String str2=new String("This is second string");
        System.out.println(str2);
        
        byte b[]={65,66,67,68,69,70};
        String str3=new String(b);
        System.out.println(str3);
        
        
        String str6=new String(b,2,3);
        System.out.println(str6);

        byte b7[]={65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80};
        try{
            String str7=new String(b7,0,13,"ISO-8859-1");
            System.out.println(str7);
        }catch(UnsupportedEncodingException e){System.out.println(e);}
        
        int unicodes[]={'\u0041','\u0042','\u0043','\u0044','\u0045','\u0046'};
        String str8=new String(unicodes,0,5);
        System.out.println(str8);
        
        String str11=new String(str8);
        System.out.println(str11);
        
        StringBuffer sb=new StringBuffer("Hemraj");
        String str12=new String(sb);
        System.out.println(str12);
        
        StringBuilder sbu=new StringBuilder("Hemraj");
        String str13=new String(sbu);
        System.out.println(str13);
    }
}

Output:

This is first string
This is second string
ABCDEF
CDE
ABCDEFGHIJKLM
ABCDE
ABCDE
Hemraj
Hemraj

Java : Using Runtime to Play song in media player

import java.io.*;
class FileDemo1{
public static void main(String ar[])throws Exception{
//Runtime.getRuntime().exec("D:\\Program Files\\Windows Media Player\\wmplayer.exe");
Runtime.getRuntime().exec("D:\\Program Files\\Windows Media Player\\wmplayer.exe \"F:\\V\\SONGS\\Dostana\\desi girl.mp3\"");
}
}

Java : Properties Class

import java.util.*;
import java.io.*;
class PropertiesDemo
{
public static void main(String ar[])
{
Properties prop=new Properties();
try{
prop.setProperty("my.name","ABC xyz");
prop.setProperty("my.phone","3453545");
FileOutputStream fout=new FileOutputStream("Prop.properties");
prop.store(fout,"My Properties");
}catch(Exception e){}
}
}

******************************************************************************
import java.util.*;
import java.io.*;
class PropertiesDemo2
{
public static void main(String ar[])
{
Properties prop=new Properties();
try{
FileInputStream fin=new FileInputStream("Prop.properties");
prop.load(fin);
String name=prop.getProperty("my.name");
String phone=prop.getProperty("my.phone");
System.out.println("name="+name);
System.out.println("phone="+phone);
}catch(Exception e){}
}
}
/
name=ABC xyz

phone=3453545

*/
*********************************************************************
import java.util.*;
import java.io.*;
class PropertiesDemo3
{
public static void main(String ar[])
{
Properties prop=new Properties();
try{
prop.setProperty("my.name","ABC xyz");
prop.setProperty("my.phone","3453545");
FileOutputStream fout=new FileOutputStream("Prop.xml");
prop.storeToXML(fout,"My Properties");
}catch(Exception e){}
}
}
***************************************************************************
import java.util.*;
import java.io.*;
class PropertiesDemo4
{
public static void main(String ar[])
{
Properties prop=new Properties();
try{
FileInputStream fin=new FileInputStream("Prop.xml");
prop.loadFromXML(fin);
String name=prop.getProperty("my.name");
String phone=prop.getProperty("my.phone");
System.out.println("name="+name);
System.out.println("phone="+phone);
}catch(Exception e){}
}
}

/

name=ABC xyz

phone=3453545

*/

SSL and TLS security

 

SSL and TLS security


SSL statnds for Secure Socket layer and TLS statds for Transport layersecurity. Both are succeser of cryptography protocols which provides secure communication on the network. Both securitiesa are used to secure various services like email, internet faxing, ftp file transfer etc.




SSL provides enpoint authentication and communication privacy over the internet. In typical use only servr is authenticated but in mutual authentication both are authenticated to each other using public key encryption(PKI). The protocol allows client/server applications to coomunicate through secure channel in which data or information is pervanted to eavesdroping, tampering and message forgery.


Working with Date and Time

 
import java.util.*;
import java.text.*;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 *This class has all method to be used by Timesheet throught the date and time related operations
 * @author Hemraj
 */
public class DateTime {

    /**
     * Change the date represented by Date object into the date format that is accepted by MS SQL Server 
     * @param d
     * @return
     */
    public String dateTime(Date d) {
        Calendar c = new java.util.GregorianCalendar();
        c.setTime(d);
        int yy = c.get(Calendar.YEAR);
        int mm = c.get(Calendar.MONTH) + 1;
        int dd = c.get(Calendar.DATE);
        int m = c.get(Calendar.MINUTE);
        int s = c.get(Calendar.SECOND);
        int hour = c.get(Calendar.HOUR_OF_DAY);
        String timeStamp = yy + "-" + mm + "-" + dd + " " + hour + ":" + m + ":" + s;
        return timeStamp;
    }

    /**
     * Covert the indian like 12/3/3009 date format into database date fromat lilke yyyy-mm-dd 
     * @param d
     * @return
     */
    public String dateFormat(String d) {
        int i1 = d.indexOf("/");
        int i2 = d.indexOf("/", i1 + 1);
        String dd = d.substring(0, i1).trim();
        String mm = d.substring(i1 + 1, i2).trim();
        String yy = d.substring(i2 + 1).trim();
        return yy + "-" + mm + "-" + dd;
    }

    /**
     * change date like 2008-01-14 15:53:06.000 into 14/1/2008
     * @param d
     * @return
     */
    public String formatDate(String d) {
        //d=d.substring(0,d.indexOf(" "));
        int i = d.indexOf("-");
        String yyyy = d.substring(0, i);
        int j = d.indexOf("-", i + 1);
        String mm = d.substring(+ 1, j);
        String dd = d.substring(+ 1, j + 1 + 2);
        return dd + "/" + mm + "/" + yyyy;
    }

    /**
     * Change the database date format into dd/mm/yyyy format
     * @param d
     * @return
     */
    public static String dbToIn(String d) {
        d = d.substring(0, d.indexOf(" "));
        int i = d.indexOf("-");
        String yyyy = d.substring(0, i);
        int j = d.indexOf("-", i + 1);
        String mm = d.substring(+ 1, j);
        String dd = d.substring(+ 1);
        return dd + "/" + mm + "/" + yyyy;
    }

    /**
     * Change the date format of Date object into indian format(dd/mm/yyyy); 
     * @param date
     * @return
     */
    public String formatDate(java.util.Date date) {
        Calendar c = new java.util.GregorianCalendar();
        c.setTime(date);
        int yy = c.get(Calendar.YEAR);
        int mm = c.get(Calendar.MONTH) + 1;
        int dd = c.get(Calendar.DATE);
        String timeStamp = dd + "/" + mm + "/" + yy;
        return timeStamp;

    }

    public String getDayName(int i) {
        String days[] = {"Mo""Tu""We""Th""Fr""Sa""Su"};
        return days[- 1];
    }

    /**
     * Method to convert string like dd/mm/yyyy into Date object. 
     * E.g 12/02/2004 will be passed as argument at method gives you Date object
     * that contain the above date.
     * @param d
     * @return Date returns the Date object
     */
    public java.util.Date dateObject(String d) throws ParseException {
        int i1 = d.indexOf("/");
        int i2 = d.indexOf("/", i1 + 1);
        String dd = d.substring(0, i1).trim();
        String mm = d.substring(i1 + 1, i2).trim();
        String yy = d.substring(i2 + 1).trim();
        //return yy+"-"+mm+"-"+dd;
        Calendar c = new java.util.GregorianCalendar(Integer.parseInt(yy)Integer.parseInt(mm) - 1Integer.parseInt(dd));
        return c.getTime();
    }

    /**
     * @author Hemraj
     * Calculate the difference between two dates represented by 2 java.util.Date object
     * @param first First Date object to be subtracted
     * @param second second date object from which fisrt date object to be subtracted
     * @return long value. Number of days
     */
    public long dateDiffInDays(java.util.Date first, java.util.Date second) {
        Calendar cFirst = new java.util.GregorianCalendar();
        cFirst.setTime(first);
        Calendar cSecond = new java.util.GregorianCalendar();
        cSecond.setTime(second);

        long milliseconds1 = cFirst.getTimeInMillis();
        long milliseconds2 = cSecond.getTimeInMillis();
        long diff = milliseconds2 - milliseconds1;
        //long diffSeconds = diff / 1000;
        //long diffMinutes = diff / (60 * 1000);
        //long diffHours = diff / (60 * 60 * 1000);
        long diffDays = diff / (24 * 60 * 60 * 1000);
        return diffDays;

    }

    /**
     * 
     * @param first
     * @param second
     * @return
     */
    public int campareDates(java.util.Date first, java.util.Date second) {
//        Calendar cFirst = new java.util.GregorianCalendar();
//        cFirst.setTime(first);
        return first.compareTo(second);

    }

    /**
     * Method to convert string like dd/mm/yyyy into Date object. 
     * E.g 12/02/2004 will be passed as argument at method gives you Date object
     * that contain the above date.
     * @param  d java.sql.Date object from resultset
     * @return Date returns the Date object
     */
    public java.util.Date dateObject(java.sql.Date d) {
        return (java.util.Date) d;
    }

    /**
     * get the next date from specified date for specified number of days
     * @param cd
     * @param days
     * @return
     */
    public java.util.Date nextDate(java.util.Date cd, int days) {
        Calendar c = new java.util.GregorianCalendar();
        c.setTime(cd);
        c.add(Calendar.DAY_OF_MONTH, days);
        return c.getTime();
    }

    /**
     * get previous date from specified date for specified number of days.
     * @param cd
     * @param days
     * @return
     */
    public java.util.Date previousDate(java.util.Date cd, int days) {
        Calendar c = new java.util.GregorianCalendar();
        c.setTime(cd);
        c.add(Calendar.DAY_OF_MONTH, -days);
        return c.getTime();
    }

    /**
     * get the name of day of date like dd/mm/yyyy
     * @param d
     * @return
     */
    public String getDayName(String d) throws Exception {
        java.util.Date date = dateObject(d);
        Calendar c = new java.util.GregorianCalendar();
        c.setTime(date);
        return getDayName(date);
    }

    /**
     * Get name of the day represented by specified date object
     * @param d
     * @return
     */
    public String getDayName(Date d) {
        DateFormat f = new SimpleDateFormat("EEEE");
        try {
            return f.format(d);
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }
    public String getDaysName(int day,int month)
    {
         Calendar c1 = Calendar.getInstance();
         Calendar c2 = Calendar.getInstance()// new GregorianCalendar();
         c2.setTime(new Date());
         int year = c2.get(Calendar.YEAR);
         c1.set(year, month, day);
         String name=getDayName(c1.getTime());
         return name.substring(0,2);
    }
    public static int daysInMonth(int month) {

        System.out.println("4. No of Days in a month for a given date\n");
        Calendar c1 = Calendar.getInstance()// new GregorianCalendar();
        //c1.setTime(cd);
        Calendar c2 = Calendar.getInstance()// new GregorianCalendar();
        c2.setTime(new Date());
        int year = c2.get(Calendar.YEAR);
        //int month = c1.get(Calendar.MONTH);
        c1.set(year, month, 1);
        // int days = c1.get(Calendar.DATE);
        int[] daysInMonths = {312831303130313130313031};
        daysInMonths[1] += isLeapYear(year) ? 1 : 0;
        System.out.println("Days in " + month + "th month for year" + year + "is " + daysInMonths[c1.get(Calendar.MONTH)]);
        System.out.println();
        System.out.println("-------------------------------------");
        return daysInMonths[c1.get(Calendar.MONTH)];
    }

    public static boolean isLeapYear(int year) {

        if ((year % 100 != 0) || (year % 400 == 0)) {
            return true;
        }
        return false;
    }

    public static void main(String ar[]) throws Exception {
        //System.out.println(new DateTime().getDayName("13/4/2008"));
        //System.out.println(new DateTime().getDayName(new Date()));
        //System.out.println("Days = "+daysInMonth(7));
        int days=daysInMonth(3);
        for(int i=1;i<=days;i++)
        {
            System.out.println(i+"="+new DateTime().getDaysName(i, 3));
        }
    }
}


Popular Posts