Tuesday, September 12, 2017

Java Nested Classes

* Nested classes are divided into two categories: static and non-static. Nested classes that are declared static are simply called static nested classes. Non-static nested classes are called inner classes.

* Static nested classesare accessed using the enclosing class name :                               OuterClass.StaticNestedClass

 For example, to create an object for the static nested class, use this syntax:


OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();

* Inner Classes : Objects that are instances of an inner class exist within an instance of the outer class. Consider the following classes:

class OuterClass {
    ...
    class InnerClass {
        ...
    }
}
An instance of InnerClass can exist only within an instance of OuterClass and has direct access to the methods and fields of its enclosing instance.

To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax:


OuterClass.InnerClass innerObject = outerObject.new InnerClass();

there is also such a thing as an inner class without an enclosing instance:
class A {
  int t() { return 1; }
  static A a =  new A() { int t() { return 2; } };
}
* Local Inner ClassesA local inner class is a class declared in the body of a method. Such a class is only known within its containing method, so it can only be instantiated and have its members accessed within its containing method. The gain is that a local inner class instance is tied to and can access the final local variables of its containing method. When the instance uses a final local of its containing method, the variable retains the value it held at the time of the instance's creation, even if the variable has gone out of scope (this is effectively Java's crude, limited version of closures).


* Anonymous classes : Before Java had lambda expressions, anonymous inner classes were the most concise syntax available for providing runnables, comparators, and other functional
objects.

Reference : StackOverflow Discussion 

Book - Core Java for Impatiens - Chapter 2 - Object Oriented Programming

* It is a good idea to run javac with the -d option. Then the class files are generated in a separate directory, without cluttering up the source tree, and they have the correct subdirectory structure

*By default, JAR files use the ZIP format. There is also an option for another compression scheme, called “pack200,” that is designed to compress class files more efficiently

*You can use JAR files to package a program, not just a library. Generate
the JAR file with jar cvfe program.jar com.mycompany.MainClass com/mycompany/*.class
Then run the program as  java -jar program.jar

*The javac and java programs have an option -classpath, which you can abbreviate
to -cp. For example,
java -classpath .:../libs/lib1.jar:../libs/lib2.jar com.mycompany.MainClass
This class path has three elements: the current directory (.), and two JAR files in
the directory ../libs.

*In Windows, use semicolons instead of colons to separate the path elements:
java -classpath .;..\libs\lib1.jar;..\libs\lib2.jar com.mycompany.MainClass

*If you have many JAR files, put them all in a directory and use a wildcard to
include them all:
java -classpath .:../libs/\* com.mycompany.MainClass

*Since the warningString variable is not private, the methods of all classes in the java.awt package can access it. Actually, no method other than those of the Window class itself does that, so it seems likely that the programmer simply forgot the private modifier.
This can be a security issue because packages are open ended. Any class can add itself to a package by providing the appropriate package statement.
The Java implementors protect themselves from such an attack by rigging the ClassLoader class so it will not load any class whose fully qualified name starts with java.
If you want to have a similar protection for your own packages, you need place them into a sealed JAR file. Provide a manifest, a plain text file containing entries
Name: com/mycompany/util/
Sealed: true
Name: com/mycompany/misc/
Sealed: true
Then run the jar command like this:
jar cvfm library.jar manifest.txt com/mycompany/*/*.class

* Static Import : A form of the import statement permits the importing of static methods and
variables. For example, if you add the directive
import static java.lang.Math.*;

*You cannot import static methods or fields from a class in the default package.

In order to buy book : Core Java for Impatiens



Tuesday, September 5, 2017

Book - Core Java for Impatiens - Chapter 1 - Fundamental Programming Structure


* Integer Types
















* You write long integer literals with a suffix L (for example, 4000000000L). There is
no syntax for literals of type byte or short.

* Hexadecimal literals have a prefix 0x (for example, 0xCAFEBABE).

*Binary values have a prefix 0b. For example, 0b1001 is 9.

*Octal numbers have a prefix 0. For example, 011 is 9. This can be confusing, so it seems best to stay away from octal literals and leading zeroes.

*You can add underscores to number literals, such as 1_000_000(or 0b1111_0100_0010_0100_0000) to denote one million. The underscores are for human eyes only, the Java compiler simply removes them.

*Integer types in Java are signed. However, if you work with values that can never be negative and you really need an additional bit, you can use methods that interpret values as unsigned. For example, instead of having a byte value b represent the range from –128 to 127, you may want a range
from 0 to 255.You can store it in a byte, and, due to the nature of binary arithmetic, certain operations such as addition and subtraction will work. For other operations, call Byte.toUnsignedInt(b) and get an int value between 0 and 255.


Floating-Point Types













* Numbers of type float have a suffix F (for example, 3.14F). Floating-point literals without an F suffix (such as 3.14) have type double. You can optionally supply the D suffix (for example, 3.14D).

*You can specify floating-point literals in hexadecimal. For example, 0.0009765625 = 2–10 can be written as 0x1.0p-10. In hexadecimal notation, you use a p, not an e, to denote the exponent. (An e is a hexadecimal digit.) Note that, even though the digits are written in hexadecimal, the exponent
(that is, the power of 2) is written in decimal.

*There are special floating-point values Double.POSITIVE_INFINITY for , Double.
NEGATIVE_INFINITY for – , and Double.NaN for “not a number.” For example, the result of computing 1.0 / 0.0 is positive infinity. Computing 0.0 / 0.0 or the square root of a negative number yields NaN.

*All “not a number” values are considered to be distinct from each other.Therefore, you cannot use the test if (x == Double.NaN) to check whether x is a NaN. Instead, call if (Double.isNaN(x)). There are also methods Double. isInfinite to test for ± , and Double.isFinite to check that a floating-point
number is neither infinite nor a NaN.

*All “not a number” values are considered to be distinct from each other.Therefore, you cannot use the test if (x == Double.NaN) to check whether x is a NaN. Instead, call if (Double.isNaN(x)). There are also methods Double. isInfinite to test for ± , and Double.isFinite to check that a floating-point
number is neither infinite nor a NaN.

* Floating-point numbers are not suitable for financial calculations in which roundoff errors cannot be tolerated. For example, the command System.out.println(2.0 - 1.1) prints 0.8999999999999999, not 0.9 as you would expect. Such roundoff errors are caused by the fact that floating-point numbers are represented in the binary number system. There is no precise binary representation of the
fraction 1/10, just as there is no accurate representation of the fraction 1/3 in the decimal system. If you need precise numerical computations without roundoff errors, use the BigDecimal class

* An integer division by zero gives rise to an exception which, if not caught, will terminate your program

* A floating-point division by zero yields an infinite value or NaN

* You need to be careful with the / operator. If both operands are integer types, it denotes integer division, discarding the remainder. For example, 17 / 5 is 3, whereas 17.0 / 5 is 3.4

*There is no operator for raising numbers to a power. Instead, call the Math.pow
method: Math.pow(x, y) yields xy. To compute the square root of x, call Math.sqrt(x).

*The Math class provides several methods to make integer arithmetic safer. The mathematical operators quietly return wrong results when a computation overflows. For example, one billion times three (1000000000 * 3) evaluates to -1294967296 because the largest int value is just over two billion. If you call Math.multiplyExact(1000000000, 3) instead, an exception is generated. You can catch that exception or let the program terminate rather than quietly continue with a wrong result. There are also methods addExact, subtractExact, incrementExact, decrementExact, negateExact, all with int and long parameters.

*When an operator combines operands of different number types, the numbers are converted to a common type before they are combined. Conversion occurs in this order:

1. If either of the operands is of type double, the other one is converted to double.
2. If either of the operands is of type float, the other one is converted to float.
3. If either of the operands is of type long, the other one is converted to long.
4. Otherwise, both operands are converted to int

*Logical AND operator, If the first condition is false, the second condition is not evaluated. This “short circuit” . Same for logical OR operator. If first condition is true then second is not evaluated. It is also called "short circuit"

*you saw that the result of the floating-point subtraction 2.0 - 1.1 is 0.8999999999999999. The BigDecimal class can compute the result accurately. The call BigDecimal.valueOf(n, e) returns a BigDecimal instance with value n × 10–e. The result of BigDecimal.valueOf(2,0).subtract(BigDecimal.valueOf(11, 1)) is exactly 0.9.

*It is somewhat inefficient to concatenate a large number of strings if all you need is the final result. In that case, use a StringBuilder instead

* To compare two strings without regard to case, use the equalsIgnoreCase method.

*When you call System.out.println, output is sent to the “standard output stream” and shows up in a terminal window. Reading from the “standard input stream” isn’t quite as simple because the corresponding System.in object only has methods to read individual bytes. To read strings and numbers, construct a Scanner that is attached to System.in

*To read a password, you do not want to use the Scanner class since the
input is visible in the terminal. Instead, use the Console class:
Console terminal = System.console();
String username = terminal.readLine("User name: ");
char[] passwd = terminal.readPassword("Password: ");
The password is returned in an array of characters. This is marginally more
secure than storing the password in a String because you can overwrite the
array when you are done

*Each of the format specifiers that start with a % character is replaced with the corresponding
argument. The conversion character that ends a format specifier indicates the type of the value to be formatted: f is a floating-point number, s a string, and d a decimal integer. Table 1–5 shows all conversion characters







































* In addition, you can specify flags to control the appearance of the formatted output. Table 1–6 shows all flags. For example, the comma flag adds grouping separators, and + yields a sign for positive numbers. The statement
System.out.printf("%,+.2f", 100000.0 / 3.0);
        prints
          +33,333.33

* You can use the String.format method to create a formatted string without printing it:
String message = String.format("Hello, %s. Next year, you'll be %d.\n", name, age);








In order to buy book : Core Java for Impatiens









Wednesday, August 30, 2017

Java Bitwise Operators

Java defines several bitwise operators, which can be applied to the integer types, long, int, short, char, and byte.
Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60 and b = 13; now in binary format they will be as follows −
a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a  = 1100 0011
The following table lists the bitwise operators −
Assume integer variable A holds 60 and variable B holds 13 then −
OperatorDescriptionExample
& (bitwise and)Binary AND Operator copies a bit to the result if it exists in both operands.(A & B) will give 12 which is 0000 1100
| (bitwise or)Binary OR Operator copies a bit if it exists in either operand.(A | B) will give 61 which is 0011 1101
^ (bitwise XOR)Binary XOR Operator copies the bit if it is set in one operand but not both.(A ^ B) will give 49 which is 0011 0001
~ (bitwise compliment)Binary Ones Complement Operator is unary and has the effect of 'flipping' bits.(~A ) will give -61 which is 1100 0011 in 2's complement form due to a signed binary number.
<< (left shift)Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand.A << 2 will give 240 which is 1111 0000
>> (right shift)Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand.A >> 2 will give 15 which is 1111
>>> (zero fill right shift)Shift right zero fill operator. The left operands value is moved right by the number of bits specified by the right operand and shifted values are filled up with zeros.A >>>2 will give 15 which is 0000 1111
Reference : Tutorial Point



Sunday, June 18, 2017

Spring Profiles

* Spring provides @Profile annotation using which we create profiles. @Profile is used with @Configuration and spring stereotypes such as @Component, @Service etc.

* Different profile is created for different environment. For example we can have environment such as production, development and testing. In development environment we can enable development profile and in production environment we can enable production profile and so on.

*  A profile can be activated using (spring.profiles.active)
  • property file .properties/.yml
  • command line 
    • an Environment Variable (java -jar abc.jar  spring.profiles.active=prod)
    • a JVM Property (java -jar -Dspring.profiles.active=prod abc.jar)
    • You can set list of profiles like ; java -jar -Dspring.profiles.active="prod,test,x" abc.jar
  • programmatically
  • Context parameter in web.xml
  • @ActiveProfile in test
* When we add active profile using command line then the active profile added in property file is replaced

*We can add active and default profile programmatically by using ConfigurableEnvironment
 
 *You can also configure profile using spring.profiles.include that will be included for every active profile.

*In spring boot testing we can add active profile by using @ActiveProfiles annotation

 *We can create property file using profile name using the convention application-{profile}.properties|yml

* In application.yml file you can define  active profile using spring.profiles.active=dev 

* We can add active profiles using command line with java command. In this case active profile configured in property file will be replaced by active profile passed in command line

* How to set active profile programatically
  public static void main(String[] args) {
      SpringApplication application = new SpringApplication(MyApplication.class);
      ConfigurableEnvironment environment = new StandardEnvironment();
      environment.setActiveProfiles("dev","test");
      application.setEnvironment(environment);
      application.run(args);
  }    

*How to set default profile programatically - 1
  public static void main(String[] args) {
     SpringApplication application = new SpringApplication(MyApplication.class);
     ConfigurableEnvironment environment = new StandardEnvironment();
     environment.setDefaultProfiles("dev","test");
     application.setEnvironment(environment);
     application.run(args);
  }      

 * How to set default profile programatically -2
@Profile({"dev","default"}) 

*You can have negative profile. For example when you are annotating class with @Profile annotation, you can negotiate it. Like @Profile("!dev"). It means
  • if dev profile is active this bean won't be created
  • if dev profile is not active then this bean will be created. And will belong to any other profile than dev.

Reference/Useful links






Thursday, June 15, 2017

Inversion of Control And Dependency Injection

This post is about what is IOC container? And what is DI?

* Inversion of Control (IoC) means that objects do not create other objects on which they rely to do their work. Instead, they get the objects that they need from an outside source (for example, an xml configuration file).
Giving control to the container to get an instance of the object is called Inversion of Control., means instead of you are creating an object using the new operator, let the container do that for you.
The main tasks performed by IoC container are: to instantiate the application class. to configure the object. to assemble the dependencies between the objects.

* DI means the IoC principle of getting dependent object is done without using concrete objects but abstractions (interfaces). This makes all components chain testable, cause higher level component doesn't depend on lower level component, only from the interface. Mocks implement these interfaces.


There are several basic techniques to implement inversion of control. These are:
  • Using a factory pattern
  • Using a service locator pattern
  • Using a dependency injection of any given below type:

    1). A constructor injection
    2). A setter injection
    3). An interface injection
    * Spring supports only Constructor Injection and Setter/Getter Injection.
Useful/Source links:
Stack Overflow Discussion
Martin Fowler Defintions
Short Video Definition of IOC