Tuesday, February 26, 2013

Multiple checkbox value using jquery

If you want to get multiple values of checkbox using jquery , Here is the code :


<html>
<head>
<style>
div { color:red; }
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<form>
<p>
<input type="checkbox" name="newsletter" value="Hourly" checked="checked">
<input type="checkbox" name="newsletter" value="Daily">
<input type="checkbox" name="newsletter" value="Weekly">
<input type="checkbox" name="newsletter" value="Monthly">
<input type="checkbox" name="newsletter" value="Yearly">
</p>
</form>
<div></div>
<script>
var checkedSiteValues = ""
var count = 0;

$("input[name ='newsletter']:checked").each(function() {
            var check = $(this).val();
            
            if (check != "true") {
                count++;
                if (count == 1) {
                    checkedSiteValues = $(this).val();
                } else {
                    checkedSiteValues = checkedSiteValues + "," + $(this).val();
                }
            }
            alert(checkedSiteValues);
        });      

</script>
</body>
</html>

Wednesday, January 30, 2013

Disable Copy Paste for publisher article


Hi Everyone,

If you want to sisable copy paste option for any of your published article,
Just use below code :

<!--Disable Copy And Paste-->
<script language='JavaScript1.2'>
function disableselect(e){
return false
}
function reEnable(){
return true
}
document.onselectstart=new Function ("return false")
if (window.sidebar){
document.onmousedown=disableselect
document.onclick=reEnable
}
</script>

Disable Copy Paste for publisher article


Hi Everyone,

If you want to sisable copy paste option for any of your published article,
Just use below code :

<!--Disable Copy And Paste-->
<script language='JavaScript1.2'>
function disableselect(e){
return false
}
function reEnable(){
return true
}
document.onselectstart=new Function ("return false")
if (window.sidebar){
document.onmousedown=disableselect
document.onclick=reEnable
}
</script>

Disable Copy Paste for publisher article


Hi Everyone,

If you want to sisable copy paste option for any of your published article,
Just use below code :

<!--Disable Copy And Paste-->
<script language='JavaScript1.2'>
function disableselect(e){
return false
}
function reEnable(){
return true
}
document.onselectstart=new Function ("return false")
if (window.sidebar){
document.onmousedown=disableselect
document.onclick=reEnable
}
</script>

Thursday, January 24, 2013

Memory management tips for JAVA

1) Minimize scope of variables
2) Initialize When You Actually Need (Variable Or Object)
3) Allocate Only Required Memory
4) Do not Declare in Loops
5) Memory Leaks Possibilities Through Soft References in Collections
6) Mutating Operations on String
7) Clean up Heavy Objects
8) Simply Use finally Block
9) ‘finalize’ Method Call Has Advantages and Disadvantages
10) Design and Architecture requiring more Memory       

Encapsulation in Java

Encapsulation is very useful feature of OOP concept when we are talking about security in java.

As you aware that, if we declare any varibale or method as a private then it can't be accessible in  other class or packages.
But here java provides this features to get those values, you would be thinking how ?
Yes it can be achieved by declaring getter setter methods of those particulate private members.

Like ,

package com.jignesh.brainbench;

public class EncapTest {
    private String name;
    private String idNum;
    private int age;

public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getIdNum() {
        return idNum;
    }
    public void setIdNum(String idNum) {
        this.idNum = idNum;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }

}

Now you can access all the public getter methods to read the value of those private variables.
Here you would be clear that how it can be useful for security purpose.
you would not knowing that where exact it will be stored but you can achieve this values.

Benefits :
  • The fields of a class can be made read-only or write-only.
  • A class can have total control over what is stored in its fields.
  • The users of a class do not know how the class stores its data. A class can change the data type of a field, and users of the class do not need to change any of their code.

Abstraction in java

Abstraction is ability to make the class abstract in OOP.
As you know  abstract class we can not be instantiates so we can not instantiate object of that that class.
So her if class is not instantiated then its not much useful but to make it worth we must have to create subclass which makes this abstract class useful and where abstraction concepts comes into picture.

Lets say,

public abstract class Employee
{
      public String name = "Jignesh";
      private String salary = "1000";
}

So here we can instantiate object of this class like ,

Employee e = new Employee();

But we can create subclass like,

public class Salary extends Employee {

}

And can access particular variables and methods from abstract class.


 Abstract Method :

We can also declare abstract method which means we can put simply signature entry of that method in abstract class and can put real implementation in subclass which cause the abstraction concepts become true in programming world.

To make method abstract, you must have to declare that method as abstract in abstract class.

like,
public abstract class Employee
{
 public abstract int mySal(); 
}
 
and in subclass you can implement that method :
 
public class Salary extends Employee
{
   int salary =  1000;
  
   public double myPay()
   {
      System.out.println("Computing salary pay for " + salary);
     
   }

} 
 

Tuesday, January 15, 2013

Know About Java Modifiers

As we all know java has below modifiers :

  • public
  • private
  • protected
  • no modifiers (package private)

Class level Modifiers (only class) :

  • If a class is ‘public’, then it CAN be accessed from ANYWHERE.
  • If a class has ‘no modifer’, then it CAN ONLY be accessed from ‘same package’.
Member Level Modifiers (variables & methods):
  • public and no modifier – the same way as used in class level.
  • private – members CAN ONLY access.
  • protected – CAN be accessed from ‘same package’ and a subclass existing in any package can access.
Please see below table :


Access Modifiers

Same Class Same Package Subclass Other packages
public Y Y Y Y
protected Y Y Y N
no access modifier Y Y N N
private Y N N N


Thursday, November 1, 2012

Best Practices for JAVA Programming

If you are a java programmer and not following java best practices, you are not java professional in real world because only programming doesn't important but how you write optimized code is more important.

So here are some of the points which i thought to be publish which can help help to java beginners.

1) Don't create objects unnecessarily

 Creation of object is one of the most expensive operation if we talk about memory utilization and performance as well.

Look @ the below code :

public class States{

 private List states;
 
 public List getStates() {
  
  //initialize only when required
  if(null == states) {
   States= new ArrayList();
  }
  return states;
 }
}

2) Never declare class instance as a public

To declaring a class instance public, there might be security problem with your application.
Let say we are creating a array of some months which is fixed and if we declare as a public, it could be easily access by someone and can change those values which cause security problem.

So instead of declaring public you can use private modifier and can access by defining getter method but again this array can be accessible so what you can do is, you can return a clone of array.

Look @ the below code:

Bad practice :
public String[] months={"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul","Aug", "Sep", "Oct", "Nov", "Dec"};
Good Practice :
private String[] months={"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul","Aug", "Sep", "Oct", "Nov", "Dec"};
 public String[] getMonths() 
 {
 return months.clone(); 
 }

Tuesday, October 16, 2012

Extract img using regex

Hi All

If you want to extract image from HTML code and want to separate text with html ,
I am sure below code help you a lot :

 
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ImgTest {

    public static void main(String[] args) {

            String s = "This is a jignesh<img src=\"test.html\" /> text";

            Pattern p = Pattern.compile("[<](/)?img[^>]*[>]");

            Matcher m = p.matcher(s);

            if (m.find()) {

              String src = m.group();

              System.out.println(src);

            }

            s = s.replaceAll("[<](/)?img[^>]*[>]", "");

            System.out.println(s);

    }

} 
OUTPUT :

<img src="test.html" />

This is a jignesh text  



Cheers !!!!

Tuesday, July 31, 2012

JDBC - MS SQL possible problem

Here in this post I am writing about some possible solutions of JDBC – MS SQL server connection problem. During my work I had faced this problem and tried a little hard to findout the solution. In our project when we tried to connect to MSSQL Server, through its default port 1433 it thrown an exception as follows. Hope this will be helpful to you.
com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection to the host localhost, port 1433 has failed. Error: “Connection refused: connect. Verify the connection properties, check that an instance of SQL Server is running on the host and accepting TCP/IP connections at the port, and that no firewall is blocking TCP connections to the port.”.
  1. Enable SQL Server Network Configuration
    • For this, go to Start Menu => Microsoft SQL Server 2008 => Configuration Tools => SQL Server Configuration Manager
    • Go to SQL Server Network Configuration => Protocols for [Instance Name] => TCP/IP
    • Instance name is the one in which you have created your database. By default it will be SQLEXPRESS
    • Make it enable (if disabled)
  2. Check the port on which SQL server is running
    • For this, go to Start Menu => Microsoft SQL Server 2008 => Configuration Tools => SQL Server Configuration Manager
    • Go to SQL Server Network Configuration => Protocols for [Instance Name] => TCP/IP
    • Instance name is the one in which you have created your database. By default it will be SQLEXPRESS
    • Right click on that and Go to Properties => IP Addresses tab => IP All section
    • There you will find TCP Dynamic Ports property and we have to consider that port number instead of default port 1433
  3. If you still facing the issue then please check Registry
    • Go to Start Menu => run => regedit
    • Go to HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL10.[Instance Name]\MSSQLServer\SuperSocketNetLib\Tcp\IPAll and check the value of key TcpDynamicPorts. we have to consider that port number instead of default port 1433

Friday, May 18, 2012

Some basics about java

  1. Real-world objects contain state and behavior.
  2. A software object's state is stored in fields.
  3. A software object's behavior is exposed through methods.
  4. Hiding internal data from the outside world, and accessing it only through publicly exposed methods is known as data encapsulation.
  5. A blueprint for a software object is called a class.
  6. Common behavior can be defined in a superclass and inherited into a subclass using the extends keyword.
  7. A collection of methods with no implementation is called an interface.
  8. A namespace that organizes classes and interfaces by functionality is called a package.
  9. The term API stands for Application Programming Interface.

Reverse string in java

Simplest Example of making reverse string using java

public class StringReverse
{
  public static void main(String[] args)
  {
  String string=args[0];
  String reverse = new StringBuffer(string).
reverse
().toString();
  System.out.println("\nString before reverse:
"
+string);
  System.out.println("String after reverse:
"
+reverse);
  
}

Thursday, January 19, 2012

immutability in Java

Summary:  Immutable objects have a number of properties that make working with them easier, including relaxed synchronization requirements and the freedom to share and cache object references without concern for data corruption. While immutability may not necessarily make sense for all classes, most programs have at least a few classes that would benefit from being immutable.

An immutable object is one whose externally visible state cannot change after it is instantiated. The String, Integer, and BigDecimal classes in the Java class library are examples of immutable objects -- they represent a single value that cannot change over the lifetime of the object.

Benefits of immutability
Immutable classes, when used properly, can greatly simplify programming. They can only be in one state, so as long as they are properly constructed, they can never get into an inconsistent state. You can freely share and cache references to immutable objects without having to copy or clone them; you can cache their fields or the results of their methods without worrying about the values becoming stale or inconsistent with the rest of the object's state. Immutable classes generally make the best map keys. And they are inherently thread-safe, so you don't have to synchronize access to them across threads.

Freedom to cache
Because there is no danger of immutable objects changing their value, you can freely cache references to them and be confident that the reference will refer to the same value later. Similarly, because their properties cannot change, you can cache their fields and the results of their methods.
If an object is mutable, you have to exercise some care when storing a reference to it. Consider the code in Listing 1, which queues two tasks for execution by a scheduler. The intent is that the first task would start now and the second task would start in one day.

When to use immutable classes

Immutable classes are ideal for representing values of abstract data types, such as numbers, enumerated types, or colors. The basic numeric classes in the Java class library, such as Integer, Long, and Float, are immutable, as are other standard numeric types such as BigInteger and BigDecimal. Classes for representing complex numbers or arbitrary-precision rational numbers would be good candidates for immutability. Depending on your application, even abstract types that contain many discrete values -- such as vectors or matrices -- might be good candidates for implementing as immutable classes.



Another good example of immutability in the Java class library is java.awt.Color. While colors are generally represented as an ordered set of numeric values in some color representation (such as RGB, HSB, or CMYK), it makes more sense to think of a color as a distinguished value in a color space, rather than an ordered set of individually addressable values, and therefore it makes sense to implement Color as an immutable class.
Should we represent objects that are containers for multiple primitive values, such as points, vectors, matrices, or RGB colors, with mutable or immutable objects? The answer is. . . it depends. How are they going to be used? Are they being used primarily to represent multi-dimensional values (like the color of a pixel), or simply as containers for a collection of related properties of some other object (like the height and width of a window)? How often are these properties going to be changed? If they are changed, do the individual component values have meaning within the application on their own?

Events are another good example of candidates for implementation with immutable classes. Events are short-lived, and are often consumed in a different thread than they were created in, so making them immutable has more advantages than disadvantages. Most AWT event classes are not implemented as being strictly immutable, but could be with small modifications. Similarly, in a system that uses some form of messaging to communicate between components, making the message objects immutable is probably sensible.


Guidelines for writing immutable classes
Writing immutable classes is easy. A class will be immutable if all of the following are true:
  • All of its fields are final
  • The class is declared final
  • The this reference is not allowed to escape during construction
  • Any fields that contain references to mutable objects, such as arrays, collections, or mutable classes like Date:
    • Are private
    • Are never returned or otherwise exposed to callers
    • Are the only reference to the objects that they reference
    • Do not change the state of the referenced objects after construction

Monday, October 10, 2011

Can a method declare multiple return values? Or Is there some way to return more than one value?

Sort of.A method can declare only one return value. BUT... If you want to return, say, three int values,
then the declared return type can be an Int array. Stuff those ints into the array,and passIt on back. It's
a little more involved to return multiple values with different types.

What happens If the argument you want to pass Is an object Instead of II primitive?

You'll learn more about this In later chapters,but you already know the answer.Java passes
everything by value. EverythIng. But...value means bits Inside the vcrtable. And remem ber,you don't
stuff objects Into variables; the variable Is a remote control-a reference to an object. SoIf you pass a
reference to an object into a method, you're passing a copy of the remote control.

Identify who am I ?

I am compiled from a .java file.   : class
My instance variable values can be different from my buddy’s values. : object
I behave like a template. : class
I like to do stuff. : object, method
I can have many methods. : class,object
I represent ‘state’. : instance variable
I have behaviors. : object,class
I am located in objects. : method, instance variable
I live on the heap.  : object
I am used to create object instances. : class
My state can change.: object,instance variable
I declare methods. : class
I can change at runtime. : object, instance variable

What’s the difference between a class and an object?

A class is blueprint for an object .It tell VM how to make an object of that perticular type.
Each object made from that class can have its own values for the instance variables of that class.

What is method and instance variable ?

Things an object knows about itself are called instance variable.
While Things an object can do are called methods.

Why does everything have to be In a class ?

java is an object-oriented(00) language. It's not Iike the old days when you had steam driven
compliers and wrote one monolithic source file with a pile of procedures