Tuesday, 31 March 2015

Convert StringBuilder To String

 In this example firstly create a string builder and then convert it to string using toString() method.


package com.javapro.string;

public class StringBuilderDemo {
   
  public static void main(String[] args) {
      StringBuilder data=new StringBuilder("Hi");
      data.append(" How Are");
      data.append(" You");
      System.out.println("data="+data);
    
      String str=data.toString();
    
      System.out.println("str="+str);
  }
 
 
}

Sunday, 29 March 2015

Convert String To Integer

 Convert string to a number in java

public class ConvertStringToInteger {
  
           public static void main(String[] args) {
                      String number="123";
                      int num = Integer.parseInt(number);
                     System.out.println("Number="+num);

                     }
}

Saturday, 21 March 2015

Push A File Using Git


You follow these steps
 
Step 1:

create a file in any location

Step 2:

Go to file path using git.

Step 3: Now  run these command

1. git init.
2. git remote add origin https://raja38@bitbucket.org/anujdhiman38/test.git
( I have used bitbucket for remote you can also it bitbucket)

 Note : step 1 and step 2 follow only when you create new repository.
  Step 1 and 2 only follow once to add remote . In other exercise i consider that you have add remote.
 
3. git add first_file.txt or git add -A
4. git commit -m"my first commit"
5. git status[for checking that all changes add and commit or not].
6. git push -u origin master


Now your local file have uploaded on remote.

reference :

bitbucket





Friday, 20 March 2015

Expand a given array


 Write A program to expand a given array

input-{'A','3','B','2','C','1'}
 

output-{A,A,A,B,B,C}


public class CountArray {
    char[] arr = new char[100];
    int index = 0;

    public static void main(String[] args) {
        CountArray ca = new CountArray();
        char[] brr = { 'A', '2', 'B', '1', 'C', '5', 'D', '4' ,'E','6'};
        for (int j = 0; j < brr.length; j++) {
            boolean flag = ca.getNumber(brr[j]);
            if (!flag) {
                int n = ca.getNum(brr[j + 1]);
                ca.makeList(brr[j], n);
            }
        }

        ca.print();

    }

    public void print() {
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i]);
        }
    }

    public int getNum(char c) {

        int zeroAscii = (int) '0';
        int charAscii = (int) c;
        int num = (charAscii - zeroAscii);
        return (num);
    }

    public void makeList(char ch, int n) {
        int j = index;
        for (int i = j; i < j + n; i++) {
            arr[index++] = ch;
        }
    }

    public boolean getNumber(char c) {

        int zeroAscii = (int) '0';
        int charAscii = (int) c;
        int num = (charAscii - zeroAscii);
        return (num <= 9 && num >= 0);
    }

}







Output:

A  A  B  C  C  C  C  C  D  D  D  D  E  E  E  E  E  E  
 

Thursday, 19 March 2015

Expand String


 Write A Function

String expnadString(String x);

string x="1,2,3,6";

output : 1,2,3,4,5,6

x=1,....,4....,10

output:

1,2,3,4,5,6,7,8,9,10


public class ExpandMyString {

    public static void main(String[] args) {
        TestData obj = new TestData();
        String x = "1,2,3,15,......,20,....,30";
        System.out.println("out put=" + obj.expnadString(x));
    }

    public String expnadString(String x) {
        String[] namesOfArray = x.split(",");
        char[] arr = namesOfArray[namesOfArray.length - 1].toCharArray();
        int i = 0;
        int num = 0;
        int zeroAscii = (int) '0';
        while (i < arr.length) {
            int charAscii = (int) arr[i];
            num = num * 10 + (charAscii - zeroAscii);
            i++;
        }

        String y = "";
        for (int j = 1; j < num; j++) {
            y += j + ",";
        }
        y += num;

        return y;
    }

}






 Related Posts:


Check a string value is Integer or not in java. (Solution).

Check ia string is hexadecimal number or not (Solution).

Generate Combination in java (Solution).

Generate permutation of string(Solution).

Reverse string in java (Solution).

Find duplicate characters with occurrences in a string(Solution).

Permutation of a number(Soluion).

Split the String in java(Solution).

Convert string into number in java(Solution).

Swap two strings without using any variable(Solution).

Get a number from a string in java(Solution).

Add Two Big Number In Java(Solution).

Expand String(Solution).

Reverse String (Solution).

Tuesday, 17 March 2015

Interview Question


Core Java Interview Question

jsp interview questions

spring interview questions

interview question on collection in java

java thread interview questions

java j2ee interview questions

advanced java interview questions 

java programming interview question

interview tips and questions

jersey interview question.

Spring Interview Questions


Monday, 16 March 2015

Git Tutorial

What Is Git.
Advantage of git.

List of importance command


Excercise

1. make a file and push on remote.
             


click
hi click me

Friday, 13 March 2015

Reverse a string


public class reverse_string {
   
    public static void main(String[] args) {
        String str="nit is a good college in india";
        char arr[]=str.toCharArray();
        int j=arr.length-1;
        int i=0;
        while(i<j){
            char ch=arr[i];
            arr[i]=arr[j];
            arr[j]=ch;
        i++;
        j--;
        }
     for (int k = 0; k < arr.length; k++) {
        System.out.print(arr[k]);   
    }  
       
    }

}

Output:

 aidni ni egelloc doog a si tin




 Related Posts:


Check a string value is Integer or not in java. (Solution).

Check ia string is hexadecimal number or not (Solution).

Generate Combination in java (Solution).

Generate permutation of string(Solution).

Reverse string in java (Solution).

Find duplicate characters with occurrences in a string(Solution).

Permutation of a number(Soluion).

Split the String in java(Solution).

Convert string into number in java(Solution).

Swap two strings without using any variable(Solution).

Get a number from a string in java(Solution).

Add Two Big Number In Java(Solution).

Expand String(Solution).

Reverse String (Solution).






Tuesday, 10 March 2015

Spring Tutorial

1. Spring MVC Example

2. Spring Autowired
3. Spring Web services
4. @pathvariable
5. Return Json
6. PUT JSON
7. DELETE
8. Interceptor
9. upload image
10.

Thursday, 5 March 2015

Java Code For Mysql Database Connection


Java code to connect database

Step 1:
          Download   mysql-connector-java-5.1.6-bin.jar and add in your project.

step 2:

Write this code to connect mysql

import java.sql.DriverManager;
import com.mysql.jdbc.Connection;

    Connection con = null;
        try {
             Class.forName("com.mysql.jdbc.Driver");
            String JDBC_DRIVER = "com.mysql.jdbc.Driver"; 
            String DB_URL = "jdbc:mysql://localhost:3306/DB_NAME";
            String USER = "root";
             String PASS = "root";
          con =(Connection) DriverManager.getConnection(DB_URL,USER,PASS);
           return  con;
        } catch (Exception e) {
                   System.out.println(e);
        }

Create XLS File In Java


Here is video tutorial  : Generate XLS In java
 
Step 1:
download poi jar

step 2:
 add jar in  your project

step 3:

import  java.io.*;
import org.apache.poi.*;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
public class CreateExlFile{
    public static void main(String[]args){
   try{
   String filename="/home/shivam/java/mydb.xls";

   HSSFWorkbook workbook=new HSSFWorkbook();
   HSSFSheet sheet =  workbook.createSheet("FirstSheet"); 
   HSSFRow rowhead=   sheet.createRow((short)0);
   rowhead.createCell((short) 0).setCellValue("No.");
   rowhead.createCell((short) 1).setCellValue("Name");
   rowhead.createCell((short) 2).setCellValue("Address");
   rowhead.createCell((short)3).setCellValue("Email");

   HSSFRow row=   sheet.createRow((short)1);
   row.createCell((short) 0).setCellValue("1");
   row.createCell((short) 1).setCellValue("shivam dhiman");
   row.createCell((short) 2).setCellValue("India");
   row.createCell((short) 3).setCellValue("xyz@gmail.com");

   FileOutputStream fileOut =  new FileOutputStream(filename);
   workbook.write(fileOut);
   fileOut.close();
   System.out.println("Your excel file has been generated!");

   } catch ( Exception ex ) {
       System.out.println(ex);

   }
      }
  }


Visit Video Here : Generate Excel In Java

Tuesday, 3 March 2015

Batch Processing In Java(JDBC)

Batch Processing  help us to make a group of related  SQl statement into batch and commit them with  one call.

Step 1:

Firstly make connection 

Connection con = null;
        try {
             Class.forName("com.mysql.jdbc.Driver");
            String JDBC_DRIVER = "com.mysql.jdbc.Driver"; 
            String DB_URL = "jdbc:mysql://localhost:3306/DATABASENAME";
            String USER = "root";
             String PASS = "root";
              con=(ConnectionDriverManager.getConnection(DB_URL,USER,PASS);
           System.out.println("connectoin estblish");
          } catch (Exception e) {

        System.out.println("e"+e);
        }
   

Step 2:
         Make auto commit  false
         con.setAutoCommit(false);
Step 3:
  • The addBatch() method of Statement, PreparedStatement, and CallableStatement is used to add individual statements to the batch. The executeBatch() is used to start the execution of all the statements grouped together.
  • at  last commit use for save data in db.


    Example : Make a batch processing program in which we have 10 query and make batch of 2 query group and commit each group. and you hit a wrong query and see that the batch group of wrong query group  can not effect in db.But all other batch groups effected in database.

    Database Table:
     emailid Cloumn in table is primary key.


    package com.craterzone.login;

    import java.sql.SQLException;
    import java.util.*;
    import com.craterzone.utility.Connect;
    import com.craterzone.utility.Utility;
    import com.mysql.jdbc.Connection;
    import com.mysql.jdbc.Statement;

    public class Batch {
    public static void main(String[] args) throws SQLException {
        Connection con=Connect.getConnect();
        con.setAutoCommit(false);
        Statement st = (Statement) con.createStatement();
        ArrayList<String> query=new ArrayList<String>();
    //group 1

    query.add("insert into student(tokenid,name,emailid,password,city,country)values('yxz16','shivame','sh@gmai1l1.com','123','sre','india')");
        query.add("insert into student(tokenid,name,emailid,password,city,country)values('yxz17','shivame','sh@gmai1l2.com','123','sre','india')");
        //group 2
        query.add("insert into student(tokenid,name,emailid,password,city,country)values('yxz18','hari','father@gmail.com','123','sre','india')");
        query.add("insert into student(tokenid,name,emailid,password,city,country)values('yxz19','shivame','sh@gmai4l.com','123','sre','india')");
        //group 3
        query.add("insert into student(tokenid,name,emailid,password,city,country)values('yxz20','shivame','sh@gmai5l.com','123','sre','india')");
        query.add("insert into student(tokenid,name,emailid,password,city,country)values('yxz21','shivame','sh@gmai6l.com','123','sre','india')");
        //group 4
        query.add("insert into student(tokenid,name,emailid,password,city,country)values('yxz22','shivame','sh@gmai7l.com','123','sre','india')");
        query.add("insert into student(tokenid,name,emailid,password,city,country)values('yxz23','shivame','sh@gmai8l.com','123','sre','india')");
        //group 5
        query.add("insert into student(tokenid,name,emailid,password,city,country)values('yxz24','sre','father@gmail.com','123','sre','india')");
        query.add("insert into student(tokenid,name,emailid,password,city,country)values('yxz25','shivame','sh@gmai12l.com','123','sre','india')");

     int count=0;
        Iterator< String> itr=query.iterator();
         while (itr.hasNext()) {
            String query1 = (String) itr.next();
            st.addBatch(query1);
            count++;
            if (count%Utility.BATCH_SIZE==0) {
                st.executeBatch();
                System.out.println("Commited "+count);
                con.commit();
                con.setAutoCommit(false);
            }
        }
        //con.commit();
        System.out.println("Commited all");
        st.close();
        con.close();
    }
    }

    Output:

    As   emailid Cloumn in table is primary key.So
    query.add("insert into student(tokenid,name,emailid,password,city,country)values('yxz24','sre','father@gmail.com','123','sre','india')"); this command is not right because father@gmail.com id we have already use and batch group 5 can not commit  in db.