Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Monday, November 21, 2016

++ operator on variable used multiple times in single line

Write the output of this code:
        long l = 10;
        System.out.println( "l " + l++ + "; " + l );


Result:
l 10; 11


Tuesday, May 10, 2016

Java: Variables in interfaces

Concept of variables in interfaces is allowed in Java, but the concept is different. Variables defined in interfaces are always static and final.

Check this for more details.

Wednesday, May 4, 2016

Java syntax hack

These are equivalent code segments:

Hacky syntax:

Map map = new HashMap() {{
   put("key", "value");
}};

Normal syntax:

Map map = new HashMap();
map.put("key", "value");

Decryption of encrypted syntax

First set of braces is the anonymous inner class (subclassing HashMap). The second set of braces is an instance initializer (rather than a static one) which then sets the values on your HashMap.

Usages

This hacky syntax could be used gracefully when initializing a class member. This way you will avoid adding code to constructor(s) or in static initializer of the class.

Anonymous class that “extends” other class or “implements” some interface in Java?

Anonymous classes in Java are defined in this way:

Syntax for implementing some interface:
Runnable r = new Runnable() {
   public void run() { ... }
};

Syntax for extending other class (is the same):
SomeClass x = new SomeClass() {
   ...
};


Thursday, January 14, 2016

Brief view in JAX-RS (Java API for RESTful Web Services)

What is JAX-RS

Java API for RESTful Web Services (JAX-RS) is a Java programming language API that provides support in creating web services according to the Representational State Transfer (REST) architectural pattern.

JAX-RS is an official part of Java EE 6.

Annotations in JAX-RS 

JAX-RS uses these annotations:
 In addition, it provides further annotations to method parameters:
  • @PathParam binds the method parameter to a path segment.
  • @QueryParam binds the method parameter to the value of an HTTP query parameter.
  • @MatrixParam binds the method parameter to the value of an HTTP matrix parameter.
  • @HeaderParam binds the method parameter to an HTTP header value.
  • @CookieParam binds the method parameter to a cookie value.
  • @FormParam binds the method parameter to a form value.
  • @DefaultValue specifies a default value for the above bindings when the key is not found.
  • @Context returns the entire context of the object (for example @Context HttpServletRequest request).
 Source: wikipedia

Monday, December 31, 2012

Inner classes and static nested classes

Terminology
Nested classes are divided into two categories:
  • static. They are simply called static nested classes.
  • non-static. They are called inner classes. 
Ideology
Reasons for using nested classes:
  • It is a way of logically grouping classes that are only used in one place.
  • It increases encapsulation.
  • Nested classes can lead to more readable and maintainable code.

Notes
  1. Access modifiers (private/public/protected) have no effect on inner classes - independant of the modifier, the classes are public.
  2. Inner classes could access members of outer class, no meter of their access modifier.
Usage out of the outer class

Sunday, December 30, 2012

Passing method arguments - by value or by reference. Theory and examples

When Java passes method arguments (parameters) by value and when by reference?
Here we put the major cases and below you will get an working example of it.

Rules:
  • primitive types are passed by value (example in swapPrimitives function);
  • arrays data is passed by reference (example in swapInArray function);
  • reassigning the argument inside the method does not affect the variable in the caller function;
  • all methods called on the arguments are called on the real object (argument variable could be changed);
We will describe the rules with swap function. Some of the methods are wrong and do not swap its arguments. After the code is the output of the program.

Code example:

Thursday, December 20, 2012

Java tests

Question 1: You are planning to do an indexed search in a list of objects. Which of the two Java collections should you use:
  1. ArrayList
  2. LinkedList
   
Question 2: Inner classes can be defined within methods.

Thursday, December 13, 2012

Singleton design pattern in examples

The singleton is a design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system.

There are different ways of implementation.

Lazy Singleton aka Singleton with double-checked locking

Wednesday, December 12, 2012

Kickstarting WebServices with REST

Here is an another nice tutorial for web services in Java. This time, the protocol used is REST, so we get RESTful services. There is a how-to to create server application for webservice. The build system is Maven.

TODO - to be tested!

hashCode() and equals()

Rule 1: The connection between hashCode() and equals():
If x.equals(y), then x.hashCode() must be same as y.hashCode().

Rule 2: Overwriting hashCode() or equals():
If you overwrite one of these functions, you have to overwrite the second too.

When you need to overwrite equals?

Friday, December 7, 2012

Could we have memory leaks in Java?

Yes, here it is explained why.

Unused references

Code that keep useless references to objects that will never use again, and at the same time never drop those references; one may say those cases are not "true" memory leaks because there are still references to those objects around, but if the program never use those references again and also never drop them, it is completely equivalent to (and as bad as) a "true memory leak".

Java Native Interface

While implementing JNI functionality, you could

Tuesday, December 4, 2012

Defining dependency projects in Maven

The problem: You have 2 projects and one relies on the second. How to realize that with maven?

Solution: Make the inner one. And define it as dependency in the another. Use the same groupId and artifactId. Easy one!

But if project Z depends on projects A and project B. And A and B use different versions of a library. Which version will be used in calling project?

Here is the code of this situation:

Friday, November 30, 2012

Uncategorized questions

Which two method you need to implement for key Object in HashMap?
In order to use any object as Key in HashMap, it must implements equals and hashcode method in Java. Read How HashMap works in Java for detailed explanation on how equals and hashcode method is used to put and get object from HashMap. You can also see my post 5 tips to correctly override equals in Java to learn more about equals.

What are the ways in Java for indication an error in a method?
Return value;
Throwing an exception.
Changing the object state in a parameter of the method. The method has t o be passed by reference;


Other sources of Java information


http://javarevisited.blogspot.com

Strings in Java

Differences between creating String as new() and literal assigning?
Described as code, the question transforms in this:
String a = "abc";
String c = new String("abc");


Just a note, which is basic for all comments below – String in Java is immutable.
When we create string with new() Operator, it’s created in heap and not added into string pool while String created using literal are created in String pool itself which exists in PermGen area of heap.

Lets look some functionality differences:

Thursday, November 29, 2012

Immutable objects

Immutable objects
Immutable objects are objects whose state cannot change after construction. Examples of immutable objects from the JDK include String and Integer. (String methods, such as String.replace do not change the instance, but create new Strings)

Requirements for immutable classes:
•    ensure the class cannot be overridden - make the class final, or use static factories and keep constructors private;
•    make fields private and final;
•    force callers to construct an object completely in a single step, instead of using a no-argument constructor combined with subsequent calls to setter methods
•    do not provide any methods which can change the state of the object in any way;

Threads in java

Problem 1:
You have thread T1, T2 and T3, how will you ensure that thread T2 start after the end of T1 and thread T3 will start after T2 end?
Solution:
By using Thread.join();
     t1.start(); 
     t1.join(); 
     t2.start(); 
     t2.join(); 
     t3.start(); 
//     t3.join();  - not needed


Problem 2:
"You have T1, T2, and T3. T1 and T2 can execute concurrently, but T3 has to wait for both of them before it can run."
Solution:
     t1.start(); 
     t2.start(); 
     t1.join(); 
     t2.join(); 
     t3.start();
 

Compare wait and sleep methods in java
Wait release the lock or monitor while sleep doesn't release any lock or monitor while waiting. Wait is used for inter-thread communication while sleep is used to introduce pause on execution.

Wait is defined in Object class, where sleep methods are defined in Thread class.

Both could throw InterruptedException.