Tuesday, 10 January 2017

Wrapper class in Java

Wrapper class in java provides the mechanism to convert primitive into object and object into primitive. Since J2SE 5.0, autoboxing and unboxing feature converts primitive into object and object into primitive automatically. The automatic conversion of primitive into object is known and autoboxing and vice-versa unboxing.
============================
primitive ||   Wrapper Class
============================
boolean  --> Boolean
char        --> Character
int           --> Integer
long        --> Long
double    --> Double
=============================
eg-1.Wrapper class Example: Primitive to Wrapper

    public class WrapperExample1{  
    public static void main(String args[]){  
    //Converting int into Integer  
    int a=20;  
    Integer i=Integer.valueOf(a);//converting int into Integer  
    Integer j=a;//autoboxing, now compiler will write Integer.valueOf(a) internally  
      
    System.out.println(a+" "+i+" "+j);  
    }}  

Output:

20 20 20

eg-2. Wrapper class Example: Wrapper to Primitive

    public class WrapperExample2{    
    public static void main(String args[]){    
    //Converting Integer to int    
    Integer a=new Integer(3);    
    int i=a.intValue();//converting Integer to int  
    int j=a;//unboxing, now compiler will write a.intValue() internally    
        
    System.out.println(a+" "+i+" "+j);    
    }}    

Output:

3 3 3
---------

That's okay? But why wrapper classes necessary in java. 

The Java designers kept the two separate to keep things simple. You use the wrappers when you need types that fit in the object oriented world - like polymorphism, collections etc. You use the primitives when you need efficiency.

Marker interfaces - Java


Marker interface in Java e.g. Serializable, Clonnable and Remote it looks they are used to indicate something to compiler or JVM. So if JVM sees a Class is Serializable it done some special operation on it, similar way if JVM sees one Class is implement Clonnable it performs some operation to support cloning. 
Same is true for RMI and Remote interface. So in short Marker interface indicate, signal or a command to Compiler or JVM.

"Why this indication can not be done using a flag inside a class?” this make sense right?  
Yes this can be done by using a boolean flag or a String but doesn't marking a class like Serializable or Clonnable makes it more readable and it also allows to take advantage of Polymorphism in Java.

How to check browser version?

<script>

    function myFunction() { 
     if((navigator.userAgent.indexOf("Opera") || navigator.userAgent.indexOf('OPR')) != -1 ) 
    {
        alert('Opera');
    }
    else if(navigator.userAgent.indexOf("Chrome") != -1 )
    {
        alert('Chrome');
    } else{
 
 }
</script>

<SCRIPT LANGUAGE="JavaScript">
var browsername;
var browserVersion;
function checkBrowser() {
  browsername = navigator.appName;
  // Sets the version number (e.g., 4.03)
  browserVersion = parseFloat(navigator.appVersion);
  if(browsername.indexOf("Netscape")!= -1) {
    browsername="NS";
  } else {
    if(browsername.indexOf("Microsoft")!=-1) {
      browsername="MSIE";
    } else {
      browsername="N/A";
      alert("Unknown browser: " + browsername);
    }
  }
  //-- code goes here........
  alert("Your Browser Name : " + browsername + " Version : " + browserVersion);
}
</SCRIPT>

Call the above functions on the body onload event. 

How to handle multiple submission in web page?

The simplest way to handle the multiple submit problem is to prevent it from happening. Below is a form, which includes a small amount of JavaScript. The embedded JavaScript remembers if the submit button was previously pressed. On a resubmit, an alert pops up and the form is not submitted again.

 <html>
 <input type="button" name="btnSubmit"
 value="Do Submit"
 onClick="checksubmitcount();">
 </td>
 </tr>
 </table>
 </form>

 <script language="javascript">
 var submitcount = 0;
 function checksubmitcount()
 {
  submitcount++;
  if (1 == submitcount )
  {
   document.Order.submit();
  }
  else
  {
   if ( 2 == submitcount)
    alert("You have already submitted  this form");
   else
    alert("You have submitted this form"
    + submitcount.toString()
    + " times already");
  }
 }
 </script>
 </body>
 </html>

Friday, 20 November 2015

How to remove line numbers from the copy pasted code in Notepad++

Hope many of us faced this issue while copy pasting the code. Along with the code, the line numbers will also be pasted. There are many ways to remove this line numbers from the code. In Notepad++, We can use regex ^\d+ in the Find and Replace option. But there is another handy way which is explained below.

Let's say we have a html code as below: 

1: <html>
2: <body>
3: <h1> HELLO PROGRAMMER </h1>
4: </body>
5: </html>

If We wish to remove the line numbers from 1 to 5, there is a handy way for this. Press the <Alt> key and Drag the mouse on the numbers with the left mouse button pressed. This will select the numbers alone. Thus we can delete the numbers easily with this feature in Notepad++.

Tuesday, 11 February 2014

resultSet.next() always returns “false”!!

You might be executing some query in your application and even though that you verified all the connection parameters like connection URL to the database, username and password, and the SQL statement that you fired, and that data also resides in the database in proper table. Yet resultSet.next() is always returning false. 

The retrieved resultSet actually points initially to a location before the actual data index, so with first resultSet.next() call, the resultSet pointer now points to the first fetched record in the database. This is ridiculous and had wasted more time. Actually I failed tocommit the data after inserting into the table. Without committing, that data never is written to the database schema. So check, did you really do a 
SQL> commit;
After scorching my head for over hours for these 7 characters of wisdom ( c-o-m-m-i-t-; ), I unleashed the forgotten thing: DML commands need to be committed/rolled-back for changes to take effect.

Thursday, 9 January 2014

Autofill Date in Excel Sheet columns

Hope everyone aware of filling Numeric values and filling Numeric series in Excel sheet(Microsoft). We can achieve filling Numeric values by just dragging the particular cell and filling Numeric Series by dragging the particular cell along pressing 'Ctrl' Key.

Filling Numeric value '1' from cells B2 to B11
Filling Numeric value '1' from cells B2 to B11


Filling Numeric series - '1 to 10' from cells B2 to B11
But what shall we do to fill Date values in excel columns.This can be achieved by dragging the cell by right clicking. You can choose either Day,Week,Month and Year.


Step-1

Step-2






Wednesday, 24 July 2013

Why should Main method in Java carry public static and void in its syntax always?

public static void main(String args[])

Every java programmer wondered to follow the syntax for main method as mentioned above. This is the reason behind the syntax. 

Why public - The access specifier of Main method is said to be public so that main method can be called outside of the class . This makes sure that JVM can easily access and execute the main method.

Why static - Main method is declared static so that JVM can call the main method with out creating instance for it. [While JVM tries to execute java program, it does not know how to create instance as there is no standard constructor defined for Main class].

Why void  - This is to make sure that Main method is not returning any values.

Cheers! Happy coding!


Thursday, 14 February 2013

Shortcut Keys - saves your time

     Most of us know that "Print Scrn" button in our keyboard will help us to take snapshots of the  screen. It will be more useful in case of developers and people who are working from different places to share their outputs, issues and bugs they are facing. But the 'Print Scrn' button will provide you with the entire screen's snap. What if we want to have the specific screen alone leaving the rest of screens behind. In windows, we can make use of 'Alt' key along with 'Print Scrn' to take screen shot of our own specific window.


Good to know :- Alt+0169 will help you to type copyright symbol. Alt+0169 ==>> ©. We have to keep on pressing 'Alt' while entering 0169 to do this. 



Thursday, 30 August 2012

Bigdecimal not exporting properly

When i was in need of generating my table's data into a report in excel format, i came across this issue.  I was using Spreadsheet gem for this purpose. The value of a particular cell contained lot of decimal places when i wanted it to be only 2 decimal place. After a lot of search, i found a good solution from rubyspreadsheet forum.


 amount = BigDecimal.new(".510283891298392")  
 sheet[0,4]= ("%7.2f" %amount).to_f         /*Converts the Big decimal to a value with 2 Floating points and write it to the (0,4)th cell */ 


If you want to know more, visit this link.

Friday, 24 August 2012

What happens when you hit a URL in your Browser !!

Hello all,

     In the link provided below you will find an article which would be useful to all. Many of us don't know the process that going behind the Browser when we hit an URL. This article will give some basic knowledge on that process. 

Monday, 9 July 2012

Finished my First year in the Corporate world !! 

 


Friday, 30 March 2012

Shortcut keys to play with Firefox tabs:


There are some Firefox-specific shortcut keys that will save you more time. Lets check them out: 

Ctrl+TOpen a new tab
Ctrl+WClose the current window or tab
Ctrl+Shift+TUndo close tab (re-open the last closed tab)
Ctrl+TabSwitch to the next tab
Ctrl+Shift+TabSwitch to the previous tab
Ctrl+[0-9]Switch to the 1st, 2nd, 3rd, 4th, etc. tab
/ Open the "Find Text As You Type" widget (bottom of screen)
Ctrl+GFind the next occurrence of a search phrase
Ctrl+Shift+GFind the previous occurrence of a search phrase
Ctrl+KMove cursor to the Web Search widget (top right of screen)

Hope these shortcut keys will be helpful to all. Happy Surfing :-)

Friday, 13 January 2012

English To Tamil Conversion

Type in English and press space(add space) to get converted to tamil. An useful documentation tool available in this website for typing tamil words in English.  

http://tamil.changathi.com/

Wednesday, 28 September 2011

Database Connectivity


Connecting a Database usually involves 2 important steps which are
  •      Establishing a connection.
  •      Connecting with the URL.

Establishing a connection:
      Inorder to establish a connection, we must load the driver that is going to act as an interface between your java code and the database. For this, we can use Class.forName() method that is defined in Class. This method will return the object of the interface by loading  the specifed driver which can be JDBC or ODBC or Sun depending on the Database going to be used. If for example, jdbc driver is specified, it will load the jdbc driver as the interface between your code and the database. 

Connecting with the URL:
     The Connection object must be created before connecting to the URL. This can be done as follows : 
     Connection con=DriverManager.getConnection(url,username,password); 
      DriverManager class provides a static method, getConnection() for connecting the host system with the database server. Here "url" is the path of the db server and "username" and "password" are the host system's username and password respectively. The "url" part consists of type of the driver followed by ip address or name of the system which inturn followed by port id. For mysql the default port is 3306. 

Example program for Database connectivity: 

import java.sql.*;
public class DBConnect
{
    public static void main(String args[]) throws SQLException, ClassNotFoundException
    {
        Connection con=null;

        try
        {
            Class.forName("com.mysql.jdbc.Driver");
            con=DriverManager.getConnection("jdbc:mysql:// 172.220.26.5 : 3306/","guest","guest");
           
        }
        catch(SQLException e)
        {
            System.out.println(e.getMessage());
        }
        finally
        {
            if(con!=null)
                con.close();

        }
    }
}
     And its a good practice to close the connection in the finally block, inorder to release the memory that was allocated for the database.     
     

Friday, 2 September 2011

What happens when we clone a object using clone() method???

        clone() method is available in the Object class. This clone method can be used to make an exact copy of the object. It copies the entire fields i.e. state of the object. For an example consider an employee details wrapped up in an object named empObj.
        Lets assume that it has fields such empID, empDesignation, empDept, empSalary, etc. When we clone this object, using clone() method, it returns a local object say empObj1. This object contains all the fields that the empObj has, and when you make change in empObj1, it won't reflect in empObj. This is something like saving a word document in another name using Save as option. The further changes made will be reflected in newly saved document and the older one remains unchanged. Thus clone() method comes into picture, when we need a local object with few changes.