Thursday, 12 July 2012

How to override toString() Method in java

 toString () method in java

This article is dedicated to those who are new to java world and not aware much about functionality of toString () method of java .whenever we work in real time application the first thing we do after start the development of code we override the to string method, its not compulsory or mandatory but if we want to provide more concise and informative representation of our object we should override this method. So let’s first discuss what the purpose behind it is.

Syntax is String toString ()

  • As we know it is defined in object class for the purpose of string representation of any object which we created.
  • It helps developer in debugging the application in development process.
  • Its is mostly used for logging the application and provide simple and convenient way to represent  the messages
  • Whenever we deal with exception and errors using this method we can pass informative messages to users.
  • The default tostring method display Class Name, “@”, and the hex version of the object’s hash code concatenated into a string.
  • toString () method is internally called by value Of () method for Object s.
  • Explicitly No need to call this method its  is automatically invoked when  an object is used in a concatenation expression or in a call to print( ).

package parser;

import java.util.Date;

public class StocktoStringTest {
     
            private String symbol;
            private String exchange;
            private long lotSize;
            private int tickSize;
            private Date settlementDate;
            private float price;
           

      public String getSymbol() {
                  return symbol;
            }

            public void setSymbol(String symbol) {
                  this.symbol = symbol;
            }

            public String getExchange() {
                  return exchange;
            }

            public void setExchange(String exchange) {
                  this.exchange = exchange;
            }

            public long getLotSize() {
                  return lotSize;
            }

            public void setLotSize(long lotSize) {
                  this.lotSize = lotSize;
            }

            public int getTickSize() {
                  return tickSize;
            }

            public void setTickSize(int tickSize) {
                  this.tickSize = tickSize;
            }

     

            public Date getSettlementDate() {
                  return settlementDate;
            }

            public void setSettlementDate(Date settlementDate) {
                  this.settlementDate = settlementDate;
            }

            public float getPrice() {
                  return price;
            }

            public void setPrice(float price) {
                  this.price = price;
            }

      /**
       * @param args
       */
      public static void main(String[] args) {
            // TODO Auto-generated method stub
            StocktoStringTest stockTest=new StocktoStringTest();
           
            stockTest.setSymbol("symbolTest");
            stockTest.setExchange("NSE");
            stockTest.setLotSize(1000);
            stockTest.setTickSize(100);
            stockTest.setSettlementDate(new Date());;
            stockTest.setPrice(2000);
            System.out.println(stockTest);
           
      }

      @Override
      public String toString() {
            return "StocktoStringTest [symbol=" + symbol + ", exchange=" + exchange
                        + ", lotSize=" + lotSize + ", tickSize=" + tickSize
                        + ",  settlementDate="
                        + settlementDate + ", price=" + price + ", getSymbol()="
                        + getSymbol() + ", getExchange()=" + getExchange()
                        + ", getLotSize()=" + getLotSize() + ", getTickSize()="
                        + getTickSize() + ", getSettlementDate()=" + getSettlementDate()
                        + ", getPrice()=" + getPrice() + ", getClass()=" + getClass()
                        + ", hashCode()=" + hashCode() + ", toString()="
                        + super.toString() + "]";
      }
     

}

What is Race Condition

Race Condition in java Thread

whenever we talk about java its incomplete without multithreading and when we use multi thread environment lot of concept comes in mind like concurrency,synchronization,deadlock,race condition ,mutual exclusion etc .this are all buzz words in the environment of thread.
Now the Question is “what is Race Condition “in very simple word in multithread Environment if more than one thread wants to access the shared data at the same time and we have not made proper protection of that shared data will cause a improper and inconsistent result only if all the thread wants to modify the data if they are only reading the data then there is no issue but if threads are writing or changing the value then this situation will called as race condition. We can conclude race condition as
·        are performed by two threads
·        At the same location
·        Not the read operation
·        Its not the synchronized operation

What is Load factor and initial capacity in Collection-Java


How  Load factor and initial capacity effects the collection performance

As  who are working in java environment well aware about the collection framework we have vast use of the collections so whenever we taking about Hash Map or Hash Set we heard two parameters that is load factor and initial capacity  let see what are these parameter, then will go how they effect the performance of collection.


What is initial capacity and load factor?

The initial capacity is nothing but the number of buckets when the hash table is created, capacity is automatically increased when hash table get full of element.
 Load factor is a measurement of how full hash table is allowed or number of elements in the hash table. When the hash table gets full of element its capacity automatically gets increased.
Important thing is that hash table is rehashed or in simple words we can say the internal data structures are rebuilt when the number of entries in the hash table exceeds the product of LF and IC this all is performed by calling the rehash method and capacity will increase by twice.

How it effects performance: In collection for basic operation like get ,put implementation is like that it has constant time performance but when we talking about operation like Iteration time is proportional to  capacity of hash map  and the size of the hash map instance. That’s why if we want good performance over this we don’t expect to set initial capacity too high or load factor too low.
The default load factor is 0. 75 if we increase the value of LF it will decrease the space over head but also increase lookup cost.

Performance can be increased if we minimize the rehash operation because every time rebuilt a data structure will cause the performance overhead. so if our initial capacity is greater than maximum number of element or key-value pair divided by load factor rehash operation can be minimized .whenever we set initial capacity always keep load factor and number of key value pair in mind.
.

Conclusion: so finally we can conclude default load capacity (.75) used by Hash Map is a good value in most situations. set the initial capacity of your Hash Map based on your own knowledge of how many items it will hold - set it so that initial-capacity x .75 = number of items (round up).







SQL Interview Question and Answer for freshers

SQL Interview Question and Answer

Question 1: what is difference between Truncate and delete command.

Ans:Truncate and delete both commands are used to delete all rows from the table but they have some major difference so before using this command we should be aware about the use of command and their result

Truncate command
Delete command
It’s a DDL command (data definition language)
It’s a DML command(data manipulation language)
We can not use trigger with Truncate command
We can use trigger with delete command
It can not be roll back
Roll back is possible in delete command
It is faster than delete because it will not log deleted rows in log space.
Slower than truncate command because this command log all the deleted rows in log space.
We can not use where clause with truncate
We can use where clause with delete command.

Question 2: what is the difference between primary key and unique key?

Ans.Both of the key is used to make the column unique means if we define any column as primary or unique key it will enforce the uniqueness of that column but have some differences
Primary Key
Unique Key
It doesn’t allow Null Values
It allows one Null value
Primary key creates cluster index on that column
It creates Non cluster Index on that column.
A table can have only one primary key
But it can have multiple unique key

Question 3: How you will delete duplicate record from the table.

Ans: Duplicate records come to table if we have not used key concept when we created the table means we have not make any column as primary key or  another source is when we are taking data from some other  source .
Basically by two ways we can delete the duplicate record from our table

  1. Using Temporary table:
·        First of all create temp table from main table
·        Insert the result of Group By query into temporary table
·        Truncate the original table
·        Insert all the values of temporary table to main table
·         
  1. without Temporary Table:

Question 4: write a query to find second highest salary from Employee table.
Ans:
select min(Employ_Sal) from Employee where Employ _Sal in
(select distinct top 2 Employ_Sal from Employee_Test order by Employ_Sal desc)

Note: in Mysql top command can be replaced by limit command
Similarly we can find nth highest salary.
Explanation: First inner Query will give us top 2 max salaries in descending order and outer query will use this result and find the minimum of this and give the second highest salary from employee table.

Question 5: What is Lock Escalation?

Ans: Basically locks are used to maintain Data Concurrency and Consistency in a Multi-user Environment where multiple user can access the data at the same time.


Saturday, 6 August 2011

How Java achieves platform independence


Java is most widely used application programming language because of its platform independence also called as "write once run anywhere" feature which allows java programs to run any kind of platform, operating system or machine. To understand how Java achieves platform independence it’s important to understand how java works and how java codes gets compiled and executed.


First step is writing java code
For writing java code you can use any text editor including notepad, word pad or edit plus. While writing your java program make sure it must have one public class and one public static void main method which allow it to run as java program when invoked in Java Virtual Machine. After completing coding just saves your file with .java extension and you are ready for next step of compiling your Java program.


Compiling Java code
For compiling java code you must need a java compiler which comes along with Java Development Kit also called as JDK. You can download and install JDK from Sun Microsystems now Oracle's site. Once you are ready with your java compiler you can compile your java code by invoking "javac" command from command line and it will compile your java source file into class file which has .class extension. This Class file is actually java's way to achieve platform independence. This class file contains JVM specific byte code instead of machine code unlike the C or C++ which makes it possible to run java program in any platform.


Running Java application
Now we are ready to run our java application and in the process we will understand important link in java platform independence. We know that after compilation java compiler creates .class file which contains JVM specific byte codes and to execute those byte code we need a piece of software called Java Virtual Machine or JVM. JVM is also known as Java Runtime or JRE. Byte codes of java programs executed inside Java Virtual Machine which is platform dependence, you here it correctly JVM are indeed platform dependent and it has different binary for different platform which you can down load from Sun's site. JVM also comes with JDK or you can download it separately.


It’s important to know that JVM or Java Virtual machine doesn't have any information regarding the programming language. It knows only binary format of the byte code and ensures that the class file generated by java compiler is as per Java Byte Code specification thus eliminating dangers of running a malicious and manipulated java byte codes. We can also generate byte code that adheres to this format in any programming language which makes it easy to write java compiler and java virtual machine in ay programming language.


Since every Java program runs within the boundaries defined by Java Virtual machine or JVM it provides inherent Security. The code run inside the JVM can not go beyond the security constraints defined by the Java Virtual Machine. This is why java application are considered as secure applications over internet and Java applets are most widely used programming platform for internet. Apart from Security Java Virtual machine also provides memory management via Garbage collection which enables java programmer or java developer to focus more on business logic rather than worrying about system aspects like allocating and reclaiming memory.


In conclusion with the use of class file, byte code and Java virtual machine, Java achieves its platform independence and makes development easy for products suppose to run in different platforms.


Refrences:

1.  Java Site from Sun

Hello

Wow I just got my blog running, I had a dream to write and share my experience in whatever I know and by which constantly improve myself as well as help others and learn from there experience. this blog is my first baby step towards that's direction. looking forward to have a great time with it.