azizkhani.net

I know that I know nothing

What is difference between Abstract classes and interface in JAVA 8?

clock February 27, 2016 20:57 by author Administrator
  • Interesting to know that now with Java 8 is possible to use a method body of an interface.So in Java 8, the only difference between an interface or an abstract class depends if we want all the methods to be public or not? (Or to implement multiple interfaces in a class like said by Piotr )
  • ,jQuery15206033902112394571_1456594024402??


get Locale in java

clock April 9, 2015 20:24 by author Administrator

   System.out.println(Locale.getDefault());

   en-us



Unsupported major.minor version 51.0

clock November 9, 2014 10:40 by author Administrator

The version number shown describes the version of the JRE the class file is compatible with.

 

J2SE 8=52,
J2SE 7=51,
J2SE 6.0=50,
J2SE 5.0=49,
JDK 1.4=48,
JDK 1.3=47,
JDK 1.2=46,
JDK 1.1=45


javac -target 1.4HelloWorld.java



Checked or Unchecked Exceptions?

clock June 3, 2014 22:58 by author Administrator

Some Java books(*) covering exceptions advice you to use checked exceptions for all errors the application can recover from, and unchecked exceptions for the errors the application cannot recover from. In reality most applications will have to recover from pretty much all exceptions including NullPointerException, IllegalArgumentExceptions and many other unchecked exceptions.



The differences between checked and unchecked exceptions are:

  1. Checked exceptions must be explicitly caught or propagated as described in . Unchecked exceptions do not have this requirement. They don't have to be caught or declared thrown. Basic try-catch-finally Exception Handling

  2. Checked exceptions in Java extend the java.lang.Exception class. Unchecked exceptions extend the java.lang.RuntimeException.

 Checked

public class BadUrlException extends Exception {
        public BadUrlException(String s) {
            super(s);
        }
    }


public void storeDataFromUrl(String url){ try { String data = readDataFromUrl(url); } catch (BadUrlException e) { e.printStackTrace(); } } public String readDataFromUrl(String url) throws BadUrlException{ if(isUrlBad(url)){ throw new BadUrlException("Bad URL: " + url); } String data = null; //read lots of data over HTTP and return //it as a String instance. return data; }

Unchecked:
public class BadUrlException extends RuntimeException { public BadUrlException(String s) { super(s); } }

public void storeDataFromUrl(String url){ String data = readDataFromUrl(url); } public String readDataFromUrl(String url) { if(isUrlBad(url)){ throw new BadUrlException("Bad URL: " + url); } String data = null; //read lots of data over HTTP and //return it as a String instance. return data; }


Fluent Object Creation

clock January 23, 2013 22:02 by author Administrator
Many posts have been written on this subject (overwhelmingly many) but I just wanted to contribute my two-cents and write a short post about how I use the Fluent Object Creation pattern or object builders in Java to instantiate Value Objects.

 Value Objects are abstractions that are defined by their state (value) rather than their address in memory. Examples of value objects are things like money, a number, a coordinate, etc. They are used not to describe Business Objects but rather descriptions of concrete indivisible entities.  Also, they make great candidates for adding them to collections and maps.


In Java, Value Objects should be declared final and provide no setter methods, basically making it's state immutable after creation, this is a very important requirement. Declaring them final makes them unable to serve as parent objects. This is done by design since value objects should model small and concrete entities. The reason being is that we should be able to create and compare multiple copies of these objects, which is always done by state not by reference. In addition, you should declare proper equals() and hashCode() methods to qualify for a proper value object.

In C++, the same principles apply. In C++ you should make use of the Copy Constructor and overload the assignment and comparison operators.  

The Fluent Object Creation pattern makes value object instantiation elegant and clean. There are many benefits that can be gained by using fluent object creation as we will see shortly. 

 

 

 

The end result of applying this pattern from the API user's perspective will look like the following:

 


Money fiveEuros = new Money.Builder()
   .currency(Currency.EURO)
   .value(5.0L)
   .countryOfOrigin("Spain")
   .type("Coin")
   .reverse("Map of Europe")
   .obverse("Map of Spain")
   .addColor("Bronze")
   .addColor("Silver")
   .year("1880")
.build();


I think you would agree that this pattern flows a lot more smoother as opposed to this:


Money fiveEuros = new Money();
fiveEuros.setCurrency(Currency.EURO);
fiveEuros.setValue(5.0L);
fiveEuros.countryOfOrigin("Spain");
fiveEuros.type("Coin");
fiveEuros.reverse("Map of Europe");
fiveEuros.obverse("Map of Spain");
List<String> colors = new ArrayList<String>();
for(String color: new String[] {"Bronze", "Silver"}) {
   colors.add(color);
}
fiveEuros.setColors(colors);
fiveEuros.setYear("1880");


Which seems broken and has lots of typing and repetition. This is an example of building a pretty big  value object in my opinion, most of tend to be very small.

Before we talk about the benefits of creating objects this way, let's have a look at the structure of this pattern:


public final class Money {
   
      private Long value;
      private String countryOfOrigin;     
      private Currency currency;
      private String type; 
      private String reverse;
      private String obverse;    
      private List<String> colors;
     private Date year;    
 
      private Money() {   }

     // -- getters, hashCode, equals -- //

     // Static inner Builder class
   publicstaticclass Builder {
        private Money _temp = new Money();
 
        public Builder countryOfOrigin(String countryOfOrigin) {
_temp.contryOfOrigin = countryOfOrigin;
         returnthis;
}
 
public Builder currency(Currency c) {
_temp.currency = c;
returnthis;
}
 
public Builder type(String t) {
_temp.type = t;
returnthis;
}
 
public Builder reverse(String r) {
_temp.reverse = r;
returnthis;
}


       public Builder obverse(String o) {
_temp.obverse = o;
return this;
}


public Builder addColor(String c) {
if(_temp.colors == null) {
              _temp.colors = new ArrayList<String>(); 
           }
           _temp.colors.add(c);
return this;
}
 
         public Builder year(String y) {
              if(y == null || y.isEmpty()) {
                  _temp.year = new Date();
              }
              else {
                  _temp.year = DateFormat.parse(y);
              }
return this;
}
 
public Money build() {
                // Validate object
               if(Strings.isNullOrEmpty(_temp.name) || _temp.currency == null) {
                  throw new IllegalArgumentException("Coin currency and value required");
               }
return_temp;
}
    } }


This is also a matter of taste, but I prefer the static inner class approach. I like the canonical nature of referring to the builder as Money.Builder. Also making it static is required since the builder instance needs to live independently of the enclosing class.

I like this pattern because it has the following benefits:

  1. Greater object encapsulation: I can easily enforce object construction using builders by making the Money constructor private (this is just stylistic). This completely hides all of the intricacies of creating this object: list creation, date parsing, etc. From the user's perspective, what we end up with is an object that is simple to instantiate. My illustration is a very simple one, but imagine more complex object graphs.
  2. Code readability: Using this pattern to create objects, makes unit tests and code very easy to read and follow. 
  3. Less typing in the long run: Even though you have to add an extra builder method for every added attributes, the amount of typing you save in the long run makes it worth while. 


Conclusion

Using the fluent creation pattern is more work up front, but the benefits of having it pays off at the end. It makes instantiating objects very elegant and clean. You don't have to use it with Value Objects, most of the benefit of using Fluent Object Creation is when you need to build pretty complex object graphs, but I wanted to show that it can also suit small value objects.

 

 

 

refer:http://www.reflectivethought.net/2013/01/fluent-object-creation.html



java.util package

clock August 20, 2012 15:55 by author Administrator



java.io package

clock August 20, 2012 15:54 by author Administrator



Java Language Classes

clock August 20, 2012 15:51 by author Administrator



بدست آوردن ای پی در جاوا

clock August 20, 2012 15:36 by author Administrator

برای بدست آوردن آی پی باید تکه کد زیر را بنویسیم

import java.net.InetAddress; 
import
java.net.UnknownHostException;  
public
class app{  
public
static void main(String[] args){  

InetAddress ip;

try {  

ip = InetAddress.getLocalHost();

System.out.println("Current IP address : " + ip.getHostAddress());
  
}

catch
(UnknownHostException e) {  

e.printStackTrace();  

}  
}  
}




Output

 

Current IP address : 127.0.0.1

 



روش ایجاد کد منحصر در جاوا

clock August 19, 2012 23:47 by author Administrator

 

حتما تا حالا پیش اومده که بخواهید یک کد منحصر درجاوا تولید کنید

برنامه نویسان دات نت این کار را با

System.GUID

انجام میدن ولی برای انجام این کار در جاوا باید از تکه کد زیر استفاده کنید

import java.util.UUID; 
public class UniqueIDTest {

 public static void main(String[] args) {
UUID uniqueKey = UUID.randomUUID();

System.out.println (uniqueKey);

}

}

 

Result

 

0a6a3de7-b974-42d0-af9e-9c23473b09b9

 



About the author

 Welcome to this web site . This page has two purposes: Sharing information about my professional life such as articles, presentations, etc.
This website is also a place where I would like to share content I enjoy with the rest of the world. Feel free to take a look around, read my blog


Java,J2EE,Spring Framework,JQuery,

Hibernate,NoSql,Cloud,SOA,Rest WebService and Web Stack tech...

RecentPosts

Month List

Sign In