Search This Blog

Wednesday 30 November 2016

What is static class loading and dynamic class loading in Java

Static Loading
Classes are statically loaded in Java using new operator.

For Example :
class MyClass {
public static void main(String args[]) {
Car c = new Car();
}
}

A NoClassDefFoundException is thrown if a class is referenced with Java’s new operator but the runtime system cannot find the referenced class.


Dynamic loading is a technique for programmatically invoking the functions of a class loader at run time.
The following specifies how classes are loaded dynamically in Java

Class.forName (String className); //static method which returns a Class
The above static method returns the class object associated with the class name. The string className can be supplied dynamically at run time.
Unlike the static loading, the dynamic loading will decide whether to load the class ClassXXX  or the class ClassYYY at runtime. Once the class is dynamically loaded the following method returns an instance of the loaded class.


class.newInstance (); //A non-static method, which creates an instance of a class
Creates a new instance of the class represented by this Class object. The class is instantiated as if by a new expression with an empty argument list.

. . . read more

Monday 28 November 2016

Packages in Java

Use of packages in Java

Packages in Java helps resolve naming conflicts,  when your project have classes with the same names.
Java Packages helps you organize class files within your project.
If we to put all .java files into a single package,then it become a nightmare to manage all your files as the project gets bigger.
You can create a package with package keyword, which is the first keyword in any Java program
followed by import statements.
The java.lang package is imported implicitly by default and all the other packages must be explicitly imported.
package com.package01.util ;
java.io.BufferedReader;
import java.util.Date;

A package in Java is an encapsulation mechanism that can be used to group related classes, interfaces, and subpackages.
The dot (.) notation is used to uniquely identify package members in the package hierarchy. 
The class java.sql.Date is different from the class java.util.Date. The MyClass class can be easily identified by the name com.mypackage.MyClass. This is called the fully qualified name of the package member. 
It is not surprising that most Java programming environments map the fully qualified name of packages on the underlying (hierarchical) file system.
Defining Packages: A class or interface can indicate that its Java byte code be placed in a particular package, using a package declaration. 
The package statement has the following syntax: 
package <fully qualified package name>;
At most one package declaration can appear in a source file, and it must be the first statement in the unit.
If a package declaration is omitted in a compilation unit, the Java byte code for the declarations in the compilation unit will belong to an unnamed package, which is typically synonymous with the current working directory on the host system.

Using Packages
Given a reference type that is accessible from outside a package, the reference type can be accessed in two ways. 
  • The first form uses the fully qualified name of the type. However, writing long names can become tedious. 
  • The second form uses the import declaration to provide a shorthand notation for specifying the name of the type. 
The import declarations must be the first statement after any package declaration in a source file. The simple form of the import declaration has the following syntax: 
import <fully qualified type name>; or 
import <fully qualified package name>.*;
An import declaration does not recursively import subpackages. 


Thursday 24 November 2016

AngularJS 2 - Whats there ??


Angular 2 is not a version upgrade, but a complete REWRITE.
Features of Angular 2 are as below
Ø  Mobile development – Angular 2 is mobile oriented & better in performance.  The rationale is desktop development is much easier when mobile performance issues are handled first
Ø  Modularity – Various modules are removed from Angular’s core, resulting in better performance. These will find their way into Angular’s ever-growing ecosystem of modules, meaning you’ll be able to pick and choose the parts you need.
Ø  Modern browsers – Suggested to work with modern browsers thus, reducing the need for browser compatibility workarounds
Ø  Angular 2 recommends the use of Microsoft's TypeScript language, which introduces the following improvements:
o   Class-based Object Oriented Programming
o   Static Typing
o   Generics
o   Lambdas
Ø  TypeScript is a superset of ECMAScript 6, and is backwards compatible with ECMAScript 5 (i.e.: JavaScript). Angular 2 also includes the benefits of ECMAScript 6:
o   Iterators
o   For/Of loops
o   Python-style generators
o   Reflection
Ø  Improved dependency injection – Angular 2.0 will address the challenges faced in Angular 1.x , as well as adding missing features such as child injectors and lifetime/scope control.
Ø  Dynamic loading : This will enable the developers to add new directives or controllers on the fly.
Ø  Asynchronous template compilation : The template compilation process will be asynchronous
Ø  Simpler Routing : The router in Angular 2.0 has been reworked to be simple, yet extensible
Ø  Diary.js logging – Angular 2.0 will contain a logging service called diary.js—a super useful feature which measures where time is spent in your application
Ø  Replacing controllers and $scope - $scope will be removed in Angular 2.0 in favor of ES6 classes.

Monday 21 November 2016

Handling Weeks in Java 7

Some applications in their business logic deals with the number of weeks in a year and the current week of the year. There are 52 weeks in a year, but 52 weeks multiplied by 7 days per week equals 364 days per year, not the actual 365 days. A week number is used to refer to the week of the year.

Java 7 has introduced several methods to support determining the week of the year.

Some implementations of the abstract java.util.Calendar class do not support week calculations. To determine if the Calendar implementation supports week calculations, we need to execute the isWeekDateSupported method. It returns true if the support is provided. To return the number of weeks for the current calendar year, use the getWeeksInWeekYear method. To determine the week for the current date, use the get method with the WEEK_OF_YEAR as its argument.

Below is the code to get total number of weeks and current week.
import java.util.Calendar;

public class WeeksInYear {
      public static void main(String[] args) {
            Calendar calendar = Calendar.getInstance();
            if(calendar.isWeekDateSupported()) {
                  System.out.println("Number of weeks in this year: " +
                              calendar.getWeeksInWeekYear());
                  System.out.println("Current week number: " + calendar.
                              get(Calendar.WEEK_OF_YEAR));
            }
      }
}


The above code will give the following out put
Number of weeks in this year: 53
Current week number: 47

Explanation of Code
An instance of the Calendar class is created, which is an instance of the

GregorianCalendar class. An if statement was controlled by the isWeekDateSupported method. It returned true, which resulted in the execution of the getWeeksInWeekYear and get methods. The get method was passed in the field WEEK_OF_YEAR, which returned the current week number.

Wednesday 16 November 2016

Catching multiple exception types in Java 7

In Java 7 and later, a single catch block can handle more than one type of exception. This feature helps reduce code duplication.
Consider the following example which we use prior to Java 7, which contains duplicate code in each of the catch blocks:
try{
// do some thing
}
catch (IOException ex) {
     ex.printStackTrace();
}
catch (SQLException ex) {
     ex.printStackTrace();
}

The following example, which is valid in Java  7 and later, eliminates the duplicated code:
try{
// do some thing
}
catch (IOException | SQLException ex) {
    ex.printStackTrace();
}


The catch clause specifies the types of exceptions that the block can handle, and each exception type is separated with a vertical bar (|).

Friday 11 November 2016

Using the try-with-resources block

The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.

This approach enables a better programming style as it avoids nested and excessive try-catch blocks. It also ensures accurate resource management, which is referred to as
Automated Resource Management (ARM).

The following example illustrates the use of try-with-resource

    try (BufferedReader br = new BufferedReader(new FileReader(path))) 


In this example, the resource declared in the try-with-resources statement is a BufferedReader. The declaration statement appears within parentheses immediately after the try keyword. The class BufferedReader, in Java  7 and later, implements the interface java.lang.AutoCloseable. Because the BufferedReader instance is declared in a try-with-resource statement, it will be closed regardless of whether the try statement completes normally or abruptly.


Prior to Java  7, you can use a finally block to ensure that a resource is closed regardless of whether the try statement completes normally or abruptly.

You may declare one or more resources in a try-with-resources statement. 
The following code snippet illustrates one or more resources in a try-with-resources statement. 
try (
        ZipFile zf = new java.ZipFile(zipFileName);
       BufferedWriter writer = Files.newBufferedWriter(outputFilePath, charset)
    ) {
               // To – Do
               }


In the above example, the try-with-resources statement contains two declarations that are separated by a semicolon

Example :
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class Java7TryResource {

public static void main(String[] args) {
 try (BufferedReader br = new BufferedReader(new FileReader(
    "C:\\myfile.txt"))) {
   System.out.println(br.readLine());
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
}

Wednesday 9 November 2016

Difference between String, StringBuffer and StringBuilder

String

The String class represents character strings. All string literals in Java programs, such as "xyz", are implemented as instances of String class.
Strings are constant, i.e. their values cannot be changed after they are created.
String objects are immutable and they can be shared.

For example:

     String str = "xyz";

is equivalent to:

     char data[] = {'x', 'y', 'z'};
     String str = new String(data);

The class String includes methods for
  • Examining individual characters of the sequence
  • Comparing strings
  • Searching strings
  • Extracting substrings
  • Creating a copy of a string with all characters translated to uppercase or to lowercase.



The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings.
String concatenation is implemented through the StringBuilder(or StringBuffer) class and its append method.

String conversions are implemented through  toString method, which is defined in  Object class.

StringBuffer

StringBuffer is a thread-safe, mutable sequence of characters. A string buffer is like a String, but can be modified.
String buffers are safe for use by multiple threads. The methods of StringBuffer are synchronized.

The principal operations on a StringBuffer are the append and insert methods, which are overloaded so as to accept data of any type.
Each effectively converts a given datum to a string and then appends or inserts the characters of that string to the string buffer.
The append method always adds these characters at the end of the buffer
The insert method adds the characters at a specified point.

For example,
if str refers to a string buffer object whose current contents are "pot",
then the method call z.append("s") would cause the string buffer to contain "pots",
whereas z.insert(2, "s") would alter the string buffer to contain "post".


If sb refers to an instance of a StringBuffer, then sb.append(x) has the same effect as sb.insert(sb.length(), x).

StringBuilder


Since Java 1.5
StringBuilder is a  mutable sequence of characters. This class provides an API compatible with StringBuffer, but with no guarantee of synchronization.
This class is designed for use as a drop-in replacement for StringBuffer in places where the string buffer was being used by a single thread
Where possible, it is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations.


Instances of StringBuilder are not safe for use by multiple threads. If such synchronization is required then it is recommended that StringBuffer be used.




Sunday 6 November 2016

Using underscores in literals

Using underscores in literals to improve code readability

In Java SE 7 and later, any number of underscore characters (_) can appear anywhere between digits in a numerical literal. This feature enables you, to separate groups of digits in numeric literals, which can improve the readability of your code.

This is intended to improve the readability of code by separating digits of a literal into significant groups at almost any arbitrary place that meets the needs of the developer. The underscore can be applied to primitive data types in any supported base (binary, octal, hexadecimal, or decimal), and to
both integer and floating-point literals.

Example to show ways you can use the underscore in numeric literals:

            long creditCardNumber = 1234_5678_9012_3456L;
            long socialSecurityNumber = 999_99_9999L;
            float pi = 3.14_15F;
            long hexBytes = 0xFF_EC_DE_5E;
            long hexWords = 0xCAFE_BABE;
            long maxLong = 0x7fff_ffff_ffff_ffffL;
            byte nybbles = 0b0010_0101;
            long bytes = 0b11010010_01101001_10010100_10010010;

You can place underscores only between digits; you cannot place underscores in the following places:
·         At the beginning or end of a number
·         Adjacent to a decimal point in a floating point literal
·         Prior to an F or L suffix
·         In positions where a string of digits is expected

The following are the examples of invalid underscore usages:
            long creditCardNumber = _12345_67890_09876_54321L;
            float pi = 3._14_15F;
long licenseNumber = 123_456_789_L;

Friday 4 November 2016

What is JVM, JRE and JDK

Java Virtual Machine (JVM)
The Java Virtual machine (JVM) is the virtual machine that run the Java bytecodes. The JVM doesn't understand Java source code.
You compile your *.java files to obtain *.class files that contain the bytecodes understandable by the JVM.
JVM makes Java to be a "portable language" (write once, run anywhere).
There are specific implementations of the JVM for different systems (Windows, Linux, MacOS) the aim is that with the same bytecodes they all give the same results.

Java Runtime Environment (JRE)
The Java Runtime Environment (JRE) provides the libraries, the Java Virtual Machine, and other components to run applets and applications written in the Java programming language. The JRE does not contain tools and utilities such as compilers or debuggers for developing applets and applications. If we want only to execute the programs written by others, then JRE alone will be sufficient.

Java Development Kit (JDK)
The JDK is a superset of the JRE, and contains everything that is in the JRE, plus tools such as the compilers and debuggers necessary for developing applets and applications.


String literals in switch statements

Prior to Java 7, only integer values were the valid arguments in a switch statement. It is very common to make a decision based on a string value, up till now developers have been using if statements whenever there is a need to make a decision based on String values, use of String in switch statement result in more readable and efficient code.


Code Snippet to display the use of String in Switch Statement

String day;
            day= "";
            switch(day){
            case "Monday" :
                  System.out.println("1st Day");
                  break;
            case "Tuesday" :
                  System.out.println("2nd Day ");
                  break;
                  default:
                        System.out.println("Holiday ");
            }

When using strings, you need to be careful about the following two issues:
ü  Null values for strings : Using a string reference variable that is assigned a null value will result in a java.lang.NullPointerException.
ü  The case of the string : The evaluation of a case expression is case sensitive in a switch statement.

 . . . read more