lambda expressions – java version 8

About lambda Expressions:

Lambda Expression been introduced by java 8 , its  a functional programming to make java 8 more faster, clearer coding.
1) A lambda expression Syntax :

parameter -> expression body
or 
(parameters) ->{ statements; }

2.) Lambda Expressions Example:

2.1) First we try traditional approaches :

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7);
for(Integer n: list) {
System.out.println(n);
}

2.2) Then we try the lambda Expressions:

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7);
list.forEach(n -> System.out.println(n));

2.3) Math Operations:

//with type declaration
MathOperation addition = (int a, int b) -> a + b;

//with out type declaration
MathOperation subtraction = (a, b) -> a – b;

 

3. characteristics of a lambda expression: 

  • Optional type declaration − No need to declare the type of a parameter. The compiler can inference the same from the value of the parameter.
  • Optional parenthesis around parameter − No need to declare a single parameter in parenthesis. For multiple parameters, parentheses are required.
  • Optional curly braces − No need to use curly braces in expression body if the body contains a single statement.
  • Optional return keyword − The compiler automatically returns the value if the body has a single expression to return the value. Curly braces are required to indicate that expression returns a value.



 

Java Servlet Annotation – Servlet API 3.0 and Above

Java Servlet Annotation

1.) The javax.servlet.annotation package contains a number of annotations that allow users to use annotations to declare servlets, filters, listeners and specify the metadata for the declared component.

2.)Servlet API 3.0 introduces a new package javax. servlet.annotation.

3.) Servlet API 3.0 provides annotation types used to annotating a servlet class.

4.) Annotation in Servlet API 3.0 replace xml configuration – web deployment descriptor file (web.xml) for servlet declaration and Servlet mapping.

5.) Servlet API 3.0 Annotation Types:

i.) @HandlesTypes

Description : Annotation type is used to declare the class types that a ServletContainerInitializer can handle. It has one attribute, value, that is used to declare the class types. For example, the following ServletContainerInitializer is annotated with @HandleTypes that declares that the initializer can handle UsefulServlet.

 

ii.) @HttpConstraint

Description :  This annotation is used within the ServletSecurity annotation to represent the security constraints to be applied to all HTTP protocol methods for which a corresponding HttpMethodConstraint element does NOT occur within the ServletSecurity annotation.

iii.) @HttpMethodConstraint

Description : This annotation is used within the ServletSecurity annotation to represent security constraints on specific HTTP protocol messages.

iv.) @MultipartConfig

Description : Annotation that may be specified on a Servlet class, indicating that instances of the Servlet expect requests that conform to the multipart/form-data MIME type.Servlets annotated with MultipartConfig may retrieve the Part components of a given multipart/form-data request by calling getPart or getParts.

v.) @ServletSecurity

Description : This annotation is used on a Servlet implementation class to specify security constraints to be enforced by a Servlet container on HTTP protocol messages. The Servlet container will enforce these constraints on the url-patterns mapped to the servlets mapped to the annotated class.

vi.)@WebFilter

Description : This annotation is processed by the container at deployment time, and the corresponding filter applied to the specified URL patterns, servlets, and dispatcher types.

vii.) @WebInitParam

Description : This annotation is used on a Servlet or Filter implementation class to specify an initialization parameter.

viii.) @WebListener

Description This annotation is used to declare a WebListener. Any class annotated with WebListener must implement one or more of the ServletContextListener, ServletContextAttributeListener,ServletRequestListener, ServletRequestAttributeListener, HttpSessionListener, or HttpSessionAttributeListener interfaces.

x.) @WebServlet

Description : This annotation is processed by the container at deployment time, and the corresponding servlet made available at the specified URL patterns.

How Annotation work in java framework

How Annotation work in java framework

Before i begin further, i’ll start some ice breaking question, I’ll understand more by questioning to the referring Subject. 

1.) What is annotation in java (Explanation) ?

  • Annotation is code about the code, that is metadata about the program itself.
  • Annotations were introduced in Java 5 SE.
  • Annotations processing tools generally use Reflection API (of Java 5 SE) to process the code at source level on Java code or bytecode level to process the class files into which the compiler has placed the annotations.
  • Frameworks like Hibernate, Spring make heavy use of annotations.
  • Before annotation been introduced, XML were extensively used for metadata. Annotation bring  coupled closely with code instead of XML which is very loosely coupled (in some cases almost separate) from code. 
  • @interface tells Java this is a custom annotation
  • For more info , go here : http://docs.oracle.com/javase/1.5.0/docs/guide/language/annotations.html

2.) How annotation work ?

— to be continued…

3.) How to create our own custom annotation?

— to be continued…

String type

1.) Java – Strings
– The String type is a class, not a primitive type.
String literals contain a string of letters including escape sequences that can appear as char literals.
– In java, string objects are immutable. Immutable simply means unmodified or unchangeable.
– Once string object is created its data or state can’t be changed but a new string object is created.

– Since String is final there is no way anyone can extend String or override any of String functionality.

Read more: http://javarevisited.blogspot.com/2013/07/java-string-tutorial-and-examples-beginners-programming.html#ixzz43gyY8TrV

Best site to study about immutable of Stringhttp://www.javatpoint.com/immutable-string

My Example on Immutable:

public class TestStringImmuatable {

public static void main(String args[]){
              String st=”Test”;
              st=st.concat(” one”);
              System.out.println(st);
       }
}

The result :

Test One

why?

  • we can Observe that first declaration of st value does not changed, The object not modified.

2.) String Comparison.

It is used in authentication (by equals() method), sorting (by compareTo() method), reference matching (by == operator) etc.

There are three ways to compare string in java:

  1. By equals() method
  2. By = = operator
  3. By compareTo() method

good site for references: http://www.javatpoint.com/string-comparison-in-java

String java methods : http://beginnersbook.com/2013/12/java-strings/

http://javarevisited.blogspot.my/2013/07/java-string-tutorial-and-examples-beginners-programming.html

How java takes out the Garbage?

  1. Each time an object is created in java, it goes into an area of memory known as The Heap. ( Heap –  heap is an area of pre-reserved computer main storage ( memory ) that a program process can use to store data in some variable amount that won’t be known until the program is running.)
  2. All Objects – no matter when , where, or how they’re created – live on the the Heap.
  3. But its not just any old memory heap; the Java heap is actually called the Garbage-Collectible heap.
  4. When you create an Object, Java Allocates memory space on the heap according how much that particular object needs.
  5. An Object with say , 15 instance variables, will probably need more space than an Object with only two instance variables.
  6. But what happens when you need to reclaim the space ? How do you get an object out of the heap when you’re done with it ? Java manages that memory for you! when the JVM can ‘see’ that an Object can never be used again, that object become eligible for garbage Collection.
  7. And if you’re running low on memory, the Garbage Collector will run, throw out the unreachable objects, and free up the space, so that the space can be reused.

Basic java – Instance Variable and Local Variable

  1. Question : When will we use the instance Variable ? How to declaring and how initializing instance variable?

With These Question , we will know how to differentiate it.

2. Firstly, lets look example class with Instance variable.
2.1. Instance Variables are declared inside a class.
2.2. Instance Variables are not declare inside a method.
2.3. We declared Instance Variable to make sure it get a default value.

2.3.1. Example How we Declare Instance Variable.

package unit.test.basic.variable;
public class EmployeeInstVariables {
// Employee Instance Variable – basic java
// declared three instance varables
private String id;
private String name;
private int age;

// in the method it will call the variables.
public void getAge(){
age = 30;
System.out.println(” My Age : “+ age);
}
public static void main(String[] args) {
         EmployeeInstVariables empAge = new EmployeeInstVariables();
        empAge.getAge();

}

Output  :  My Age : 30

3. The purpose of declaring instance variables is to assign default value. Below is the data types primitive.

3.1. integer  = 0
3.2. Floating points = 0.0
3.3. boolean = false
3.4. references null

4. The error will occurred when we are not declared the Instance Variable, and declared as a local variable inside the method.

4.1. The Correct way to solved the Error by add in instance Variable.

package unit.test.basic.variable;

public class NoInstVariable {
// Add the Instance variable.
private int anotherYears;

// in the method declared local variable + with .
public void getTwoYearAge(){
int ageNow = 30;
// int anotherYears; // commented
int totalAge;
totalAge = ageNow + anotherYears;
System.out.println(” My Age : “+ totalAge);
}

public static void main(String[] args) {
// TODO Auto-generated method stub
NoInstVariable empAge = new NoInstVariable();
empAge.getTwoYearAge();

}

Output :  My Age : 30

Variable & Datatypes – Java

Variable and Datatypes – Java

1.) Variable

  • Variable is the name of Memory location.
  • Variable provides named to storage that our program can manipulate.

1.2.) Three Types of Variable:

1.2.1) Local Variable :

  • A variable that Declared inside the method.

1.2.2) Instance Variable :

  • A variable that is declared inside the class but outside the method. Its not declared as static.

1.2.3) Static Variable :

  •  Variable that declared as static, and cannot be local.

2.) Two Types of Datatypes :

2.1.) PrimitiveAny data type built into a programming language is called ‘primitive’ data type.

  • Eight Primitive data types in java :
  • 1) Byte
  • 2) Short
  • 3) int
  • 4) Long
  • 5) float
  • 6) Double
  • 7) Char
  • 8) Boolean

2.2) Non-Primitive / A Class Type

  • Array structure or Class.
  • The data types that are derived from primary data types are known as non-primitive data types.
  • Example : Array , structure , links , list , stacks and queue.
  • non-primitive data-types are objects & arrays. 
  • Often called “reference types” – to address of the Object or Array is stored in variable passed to methods.

2.3) String – its also part of non-primitive.

  • note: String is object and also Class, is immutable, that means that you cannot change the object itself, but you can change the reference to the object.
  • The String class is not technically a primitive data type, but considering the special support given to it by  the language.

Java – Basic Syntax

Basic Java Syntax that we should know:

1. Java syntax is case Sensitivity – any variable should same with what we declare. Such variable ” Syntax ” (First letter Uppercase) and ” syntax ” (All lowercase) would have difference meaning.

2. Class name – It should declare with First letter are Uppercase.
Example : JavaClassOne

3. Method name – All methods should declare with Lower case letter.
Example : getFoot()

4. Program File name – The Program File name should exactly name with class name.

5. public static void main(String args[]) – Java Processing, its a main method.

Java BufferedReader (jdk java.io.*)

What is BufferedReader ?
– Class BufferedReader is under java.io package of Java API.
– Its for reads text from a character-input stream, buffering characters so as to provide to the efficient reading of characters, arrays, and lines.

BufferedReader in = new BufferedReader(new FileReader(“foo.in“));

– will buffer the input from the specified file. Without buffering, each invocation of read() or readLine() could cause bytes to be read from the file,
converted into characters, and then returned, which can be very inefficient.

— source article from oracle site : http://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html

My Source Code To Try BufferedReader:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class FileRead {

 public static void main(String args[]) {
     // 1 read the contain from txt file.
    // 1.1. declare the object that use for read – BufferReader
BufferedReader readTheFile = null;
File fileWrite = null;
String inLine;
try {
readTheFile = new BufferedReader(new FileReader(“C:\\Users\\frank\\Desktop\\KERJA\\FileWriter\\fileread.txt“));
// 2. create a writer , write into new text file
fileWrite = new File (“C:\\Users\\frank\\Desktop\\KERJA\\FileWriter\\filewrite.txt“);
while ((inLine = readTheFile.readLine()) != null) {

// 2.1. check the file is exist or not, if not create the file.
if (!fileWrite.exists()) {
fileWrite.createNewFile();
System.out.println(“Create new FIle“);
}
// 2.2. write into filewrite.txt file
FileWriter fw = new FileWriter(fileWrite.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
System.out.println(inLine);
bw.write(inLine);
bw.close();
}

} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (readTheFile != null){
readTheFile.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}

 

OUTPUT :

Image