Java tutorials

[ad_1]

Java tutorials are the best if you are a beginner or even an experienced programmer. The good thing with Java tutorials is that they are free on the internet what you only need is an internet connection to access them and get what you want regarding Java programming.Instead of going around shopping for books you can try Java tutorials, you will be amazed by the information you will find available online about java.Java tutorials is one of the easiest and fastest means to get information about Java tips with no cost and much hassle as many think.

Internet Java tutorials are the best even to those who are total beginners who may be wishing to learn about Java than attending to class courses. Beginners can find anything by getting started with some basic skills in the Java language, essential classes and get into more specialized tutorials such as graphics, security in Java, how to work with databases and many more. There are so many websites online today that are specialized in giving Java tutorials and tips to all those who may need them. They were written by experts and then placed in different categories where they fall at for easy access. The best thing to do to understand is reading more tutorials that you come across and than combine them with the useful and short Java tips you find.
For the experienced programmers, you should share your knowledge with the newbies by writing Java tips and tutorials to help those who may need them.
All you should ensure at large when writing Java tutorials are making yourself clear and understood. You should also ensure you cover all the aspects of the problem you are writing. There are some rules you should also follow if you need people to find and understand all information you are delivering efficiently. Some of the rules are such like choosing an interesting title for your Java tip. The title should capture what you are exactly presenting. Your writing should also be accompanied by the best subtitle which will expand a little bit on what you are writing about. You can also if you wish a short and precise comment or summary to describe what your Java tips do. After completing all these, you go directly to the introduction, code listing of your Java tip, write an explanation for your tip and finally end with a conclusion. You can also add a link to direct your readers to more detailed Java tutorials on the particular subject you are writing. Java tips and tutorials are the best learning resources and improving skills in Java.

[ad_2]

StringBuffer Reset Java Example

[ad_1]

/*

StringBuffer Reset Java Example

This example shows how to reset StringBuffer object to null or empty vale using delete

method.

*/

 

public class StrinBufferResetExample {

public static void main(String[] args) {

//create StringBuffer object

StringBuffer sbf = new StringBuffer(“Hello World!”);

System.out.println(“StringBuffer content: “ + sbf) ;

/*

* To reset StringBuffer to empty value, user

* StringBuffer delete() method of StringBuffer class.

*/

sbf.delete(0, sbf.length());

System.out.println(“StringBuffer content after reset:” + sbf);

}

}

 

/*

Output of above given Java StringBuffer Reset example would be

StringBuffer content: Hello World!

StringBuffer content after reset:

*/

[ad_2]

Java StringBuffer to InputStream Example

[ad_1]

/*

Java StringBuffer to InputStream Example

This example shows how to convert StringBuffer to InputStream in Java using

ByteInputStream class.

*/

 

 

import java.io.ByteArrayInputStream;

import java.io.InputStream;

 

public class StringBufferToInputStreamExample {

public static void main(String args[]){

//create StringBuffer object

StringBuffer sbf = new StringBuffer(“StringBuffer to InputStream Example”);

/*

* To convert StringBuffer to InputStream in Java, first get bytes

* from StringBuffer after converting it into String object.

*/

byte[] bytes = sbf.toString().getBytes();

/*

* Get ByteArrayInputStream from byte array.

*/

InputStream inputStream = new ByteArrayInputStream(bytes);

System.out.println(“StringBuffer converted to InputStream”);

}

}

[ad_2]

Java Lambda : Beginners Guide

[ad_1]

This article explains Java Lambda expressions in Java 8. You can find complete code here.

Java Lambda Expressions

Java Lambda Expression is a new and important feature of Java, introduced in Java 8. A Lambda Expression is an anonymous function (a function without name) which doesn’t belong to any class, means a function which doesn’t have a name and doesn’t have a class. Lambda Expression simplified the development a lot by facilitating functional programming in Java. It is used to provide implementation of functional interface (functional interface is an interface that contains only one method. For example, Java standard Runnable interface is a functional interface). It also helps to iterate, filter and extract data from collection libraries. Lambda Expressions enable you to treat code as data and functionality as a method argument.

Syntax of Lambda Expression

Let’s discuss syntax of Lambda Expression.

A Lambda Expression consist of three components, a set of parameters, a Lambda operator and a function body. Here are the three components

  • Parameter List: Here comes argument which can be empty or non empty as well.
  • Lambda Expression: Lambda Expression or arrow(->) is used to separate parameter list and function body.
  • Function body: It contains function statement for Lambda Expression.

Input parameters are on the left side of lambda operator and function body on the right side of lambda operator. This Lambda Expression syntax reduces bulkiness of code that is five lines of code into one line.

parameter list -> function_body

Characteristics of Lambda Expression

Here are few important characteristics of Lambda Expression.

  • Type declaration: Type declaration is optional. Its up to you, if you will not declare type of parameter, compiler can guess from the value of parameter. For example you can write
(5,4) -> function body
  • Parenthesis around parameter: Parenthesis around parameter are also optional. You can put parenthesis if you want, else leave it as it is. If there are multiple parameters in a Lambda Expression then parenthesis are required as shown in above example. For one parameter you can write as
5 -> function body
  • Curly braces: Curly braces around function body is also optional if there is only one statement. For multiple statements curly braces around function body are required. For example
(5, 4) -> 5+4;
  • Return statement: Return statement is also optional in Lambda Expressions. Java compiler automatically returns value if the body has a single expression. If function body returns a value then you should enclose it with curly braces.

Examples of Lambda Expression

Here are few examples of Lambda Expressions.

x, y -> x+y;

The above written Lambda Expression means given two integer x, y and return another integer with the sum of x and y.

Another one

( ) -> 42

The above written Lambda Expression means given no integer and returns integer 42.

Prerequisite

To run Java Lambda Expression following are the prerequisites for it.

  • Java Development Kit (JDK8)
  • NetBeans or Eclipse

Java Lambda Expression with No Parameter

In this example I will show how to use Java Lambda Expressions with no parameter. Open your IDE(I would be using Eclipse Neon) and start creating a new project. Name it as Lambda. Create a class called NoParameter.

public class NoParameter {

  public static void main(String[] args) {
    // TODO Auto-generated method stub
     // lambda expression with return type 
    NoParameterInterface message = () -> {
    		return "Hello World with No Parameter";
    	};
        System.out.println( message.HelloWorld( ));
  }

}

@FunctionalInterface
interface NoParameterInterface {

  //Here is a method with no parameter and return type as String
    public String HelloWorld();
}

The above example shows a hello world message by using a Lambda Expression with no parameter.

Lambda Expression with Single Parameter

You have seen example of Lambda Expression with no parameter. Let’s examine an example of Lambda Expression with single parameter. For this create a class named SingleParameter and paste the following code there.

public class SingleParameter {

  public static void main(String[] args) {
    // TODO Auto-generated method stub
     // lambda expression with single parameter num and returns square of num without any return statement 
    SingleParameterInterface Square = (num) -> num*num;
        System.out.println(Square.SquareOfFive(5));
  }

}


@FunctionalInterface
interface SingleParameterInterface {

  //A method with single parameter and return type as int 
    public int SquareOfFive(int s);
}

 

This above example shows Lambda Expression with single parameter. It takes 5 as an input and returns square of 5 without any return statement. As mentioned above if there is only one statement then no need to specify return keyword. Compiler automatically do returns that value.

Java Lambda Expressions with Multiple Parameters

Let’s do an example of Java Lambda Expression with multiple parameters involved. Create a new java class and name it as MulipleParamater. Open it and paste the following code in it.

public class MulipleParamater {

  public static void main(String[] args) {
    // TODO Auto-generated method stub
    //lambda expression which add two number
    MulipleParamaterInterface add = (a, b) -> a + b;
        System.out.println("Sum of 5 and 4 is: "+add.sum(5, 4));
  }

}


interface MulipleParamaterInterface {

  //here is a method with multiple parameter and int as return type 
    public int sum(int a, int b);
}

 

This above example shows Lambda Expression with multiple parameters. It takes 5 and 4 as input and returns sum as 9. Again it works without specifying return keyword.

Event Listener

Let’s explore some more advance examples that is event listener in java. How Lambda Expressions are used to implement event listener. You will see both examples of event listeners with Lambda Expressions and without Lambda Expressions.

Event Listener without Lambda Expressions

First examine event listener without Lambda Expressions. Go to eclipse and create a new class, name it as eListener. Open it and paste the following code.

import java.awt.event.*;		//import for event listener
import javax.swing.JButton;   	//import for JButton class
import javax.swing.JFrame;    	//import for JFrame class
import javax.swing.JTextField;  //import for JTextField 

public class eListener {  
  //event listener class without Lambda Expressions
  static JTextField textfield;
  static JButton button;
  static JFrame frame;
  
    public static void main(String[] args) {  
        textfield=new JTextField(); 
        button=new JButton("click");  
        frame=new JFrame("Event Listener without using Lambda Expression"); 
        
        //set positions of text field and button
        textfield.setBounds(50, 50,150,20);         
        button.setBounds(80,100,70,30);  
        
        //action listener on button 
        button.addActionListener(new ActionListener(){
        	  public void actionPerformed(ActionEvent e){  
        		  textfield.setText("hello world");
        	  }
          });
       
        frame.add(textfield);
        frame.add(button);  
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
        frame.setLayout(null);  
        frame.setSize(300, 200);  
        frame.setVisible(true);  
  
    }  
  
}

 

The above written code shows an example of event listener in Java without using Lambda Expression. That’s why you must be familiar with the code. Simple JButton, JFrame and JTextFields are used. When user clicks on button text field will show hello world message. Here is the output

 

Event Listener with Lambda Expression

Now examine event listener with Lambda Expression. Go to eclipse and create a new class called eListenerLambda. Open it and paste the following code.

import javax.swing.JButton;   	//import for JButton class
import javax.swing.JFrame;    	//import for JFrame class
import javax.swing.JTextField;  //import for JTextField 

public class eListenerLambda {  
  //event listener class without Lambda Expressions
  static JTextField textfield;
  static JButton button;
  static JFrame frame;
  
    public static void main(String[] args) {  
        textfield=new JTextField(); 
        button=new JButton("click");  
        frame=new JFrame("Event Listener without using Lambda Expression"); 
        
        //set positions of text field and button
        textfield.setBounds(50, 50,150,20);         
        button.setBounds(80,100,70,30);  
          
        // lambda expression implementing here.  
        button.addActionListener(e-> {textfield.setText("hello world");});  
          
         
        frame.add(textfield);
        frame.add(button);  
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
        frame.setLayout(null);  
        frame.setSize(300, 200);  
        frame.setVisible(true);  
  
    }  
  
}

The above written code shows an example of Java event listener with Lambda Expression. If we compare both codes, you will examine the action listener code in first example has three statements while with Lambda Expression it solved the problem in one statement. The output of both codes is same as shown above.

Comparator Example Using Lambda Expression

Let’s examine one more piece of code that is comparator example with using Lambda Expression. Create a new class and name it as Comparatorlambda.java. Open it and paste the following code.

import java.util.ArrayList;  
import java.util.Collections;  
import java.util.List;  

//account class holds the details of a bank account of customers like account number, name and account balance
class Account{  
    int accountNumber;  
    String name;  
    float AccountBalance;  
    public Account(int accountNumber, String name, float AccountBalance) {  
        super();  
        this.accountNumber = accountNumber;  
        this.name = name;  
        this.AccountBalance = AccountBalance;  
    }  
}  

//comparator class using Lambda Expressions
public class Comparatorlambda{  
  
    public static void main(String[] args) {  
        List<Account> list=new ArrayList<Account>();  
          
        //Adding account details in list  
        list.add(new Account(00235,"Harry",25000));  
        list.add(new Account(11687,"Donald",30088));  
        list.add(new Account(27865,"Caristano",15078));  
          
        System.out.println("Sorting on the basis of account name...");  
  
        // implementing lambda expression  
        Collections.sort(list,(p1,p2)->{  
        return p1.name.compareTo(p2.name);  
        
        });  
        System.out.println("Account Number: Account Name: Account Balance:"); 
        for(Account p:list){  
            System.out.println(p.accountNumber+" tt"+p.name+" tt"+p.AccountBalance);  
        }  
  
    }  
}

This example has an account class which holds accounts information like name, number and account balance. Lambda Expressions are used to compare and sort accounts on the basis of account name. Here is Lambda Expression used for this purpose.

Collections.sort(list,(p1,p2)->{return p1.name.compareTo(p2.name); });

Following is the output of this code

Conclusion

Lambda Expressions are used to define inline implementation of functional interface. You have seen in the above examples that Lambda Expressions saved our time and reduced the code statements a lot. It gives powerful capabilities to java by facilitating functional programing. This new feature of java has changed the complete way of coding and simplified development as it takes advantage of parallel capabilities of multicore environment.

[ad_2]

Java StringBuffer append new line example

[ad_1]

/*

Java StringBuffer append new line example

This example shows how to append new line in StringBuffer in Java using

append method.

*/

 

public class JavaStringBufferAppendNewLineExample {

public static void main(String args[]){

//create StringBuffer object

StringBuffer sbf = new StringBuffer(“This is the first line.”);

/*

* To append new line to StringBuffer in Java, use

* append method of StringBuffer class.

*

* Different operating systems uses different escape characters to

* denote new line. For example, in Windows and DOS it is rn, in Unix

* it is n.

*

* In order to write code which works in all OS, use Java System property

* line.separator instead of escape characters.

*/

sbf.append(System.getProperty(“line.separator”));

sbf.append(“This is second line.”);

System.out.println(sbf);

}

}

 

/*

Output of above given StringBuffer append new line Java example would be,

This is the first line.

This is second line.

*/

[ad_2]