Tuesday, March 31, 2015

Split String to array with whitespace

Example to split String to String array, by whitespace. And also join String array to String.


package javasplitestring;

import java.util.Scanner;

/**
 * @web http://java-buddy.blogspot.com/
 */
public class JavaSpliteString {

    public static void main(String[] args) {
        String original;
        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter a string:");
        original = scanner.nextLine();
        
        //split String to array splited with whitespace regex
        String[] splittedStringArray = original.split("\\s+");
        System.out.println("length = " + splittedStringArray.length);
        
        for(String s : splittedStringArray){
            System.out.println(s);
        }
        
        //Join the String array to a String using StringBuilder
        StringBuilder stringBuilder = new StringBuilder();
        for(String s : splittedStringArray){
            stringBuilder.append(s);
        }
        System.out.println(stringBuilder);
    }
    
}

Saturday, March 28, 2015

JavaFX example: save TextArea to file, using FileChooser

JavaFX example show how to get content from TextArea, and save it as txt file using FileChooser.


package javafxsavetext;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;

/**
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFXSaveText extends Application {
    
    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("java-buddy.blogspot.com");
        Group root = new Group();
        
        TextArea textArea = new TextArea();

        Button buttonSave = new Button("Save");
                
        buttonSave.setOnAction((ActionEvent event) -> {
            FileChooser fileChooser = new FileChooser();
            
            //Set extension filter
            FileChooser.ExtensionFilter extFilter = 
                new FileChooser.ExtensionFilter("TXT files (*.txt)", "*.txt");
            fileChooser.getExtensionFilters().add(extFilter);
            
            //Show save file dialog
            File file = fileChooser.showSaveDialog(primaryStage);
            
            if(file != null){
                SaveFile(textArea.getText(), file);
            }
        });
        
        VBox vBox = new VBox();
        vBox.getChildren().addAll(textArea, buttonSave);
        
        root.getChildren().add(vBox);
        
        primaryStage.setScene(new Scene(root, 500, 400));
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }

    private void SaveFile(String content, File file){
        try {
            FileWriter fileWriter;
             
            fileWriter = new FileWriter(file);
            fileWriter.write(content);
            fileWriter.close();
        } catch (IOException ex) {
            Logger.getLogger(JavaFXSaveText.class
                .getName()).log(Level.SEVERE, null, ex);
        }
         
    }
    
}


Related:
- Read text file with JavaFX FileChooser

Friday, March 27, 2015

Reverse String, reverse words order, reverse chars in words

This example show various methods to reverse chars in String, reverse words order, and reverse chars in words but keep words in order.


package javareversestring;

import java.util.List;
import java.util.Scanner;
import java.util.Stack;
import java.util.StringTokenizer;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaReverseString {

    public static void main(String[] args) {
        String original;
        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter a string:");
        original = scanner.nextLine();
        
        String reverseString = "";
        for(int i=original.length()-1; i>=0; i--){
            reverseString= reverseString + original.charAt(i);
        }
        System.out.println(reverseString);
        
        System.out.println(new StringBuffer(original).reverse().toString());
        System.out.println(reverseWords(original));
        System.out.println(reverseCharsInWords(original));
    }

    //reverse words
    static private String reverseWords(String src){
        String reversed = "";
        
        Stack<String> stackString = new Stack<>();
        StringTokenizer stringTokenizer = new StringTokenizer(src);
        
        while(stringTokenizer.hasMoreTokens()){
            stackString.push(stringTokenizer.nextToken());
        }
        
        while(!stackString.empty()){
            reversed += stackString.pop() + " ";
        }
        
        return reversed;
    }
    
    //reverse chars in words
    static private String reverseCharsInWords(String src){
        String reversed = "";
        
        List<String> listString = new Stack<>();
        StringTokenizer stringTokenizer = new StringTokenizer(src);
        
        while(stringTokenizer.hasMoreTokens()){
            listString.add(stringTokenizer.nextToken());
        }
        
        while(!listString.isEmpty()){
            String s = listString.remove(0);
            reversed += new StringBuffer(s).reverse().toString() + " ";
        }
        
        return reversed;
    }
}

Thursday, March 26, 2015

Professional Java EE Design Patterns

Professional Java EE Design Patterns

Master JavaEE Design Pattern implementation to improve your coding efficiency Professional JavaEE Design Patterns is the ultimate guide to working more efficiently with JavaEE, and the only resource that covers both the theory and application of design patterns in solving real-world problems. The authors guide readers through both the fundamentals and little-known secrets of JavaEE6/7, presenting patterns throughout, and demonstrating how they are used in day-to-day programming. As the standard computing platform in community-driven enterprise software, JavaEE provides an API and runtime environment above and beyond JavaSE. Written for the experienced JavaEE developer hoping to improve code quality and efficiency, the book contains time saving patterns, including: Implementation and problem-solving with design patterns Connection between existing non-JavaEE design patterns and new JavaEE concepts Unique organization that prioritizes the most relevant patterns before expanding into advanced techniques Individually-based focus that fully explores each pattern Unlike most JavaEE books that simply offer descriptions or recipes, this book drives home the actual implementation and application to keep square pegs away from round holes. For the programmer looking for a comprehensive guide that is actually useful in the everyday workflow, Professional JavaEE Design Patterns is the definitive resource on the market.

Tuesday, March 24, 2015

Print Unicode in Java

Example to print unicode on Java:

package javaunicode;

public class JavaUniCode {

    public static void main(String[] args) {
        String unicode = "\u01FC";
        System.out.println(unicode);
        System.out.println("Ǽ");
        System.out.println("\u03A9");
        System.out.println("Ω");
    }
}


Pragmatic Unit Testing in Java 8 with JUnit

Pragmatic Unit Testing in Java 8 with JUnit

The Pragmatic Programmers classic is back! Freshly updated for modern software development, Pragmatic Unit Testing in Java 8 With JUnit teaches you how to write and run easily maintained unit tests in JUnit with confidence. You'll learn mnemonics to help you know what tests to write, how to remember all the boundary conditions, and what the qualities of a good test are. You'll see how unit tests can pay off by allowing you to keep your system code clean, and you'll learn how to handle the stuff that seems too tough to test.

Pragmatic Unit Testing in Java 8 With JUnit steps you through all the important unit testing topics. If you've never written a unit test, you'll see screen shots from Eclipse, IntelliJ IDEA, and NetBeans that will help you get past the hard part--getting set up and started.

Once past the basics, you'll learn why you want to write unit tests and how to effectively use JUnit. But the meaty part of the book is its collected unit testing wisdom from people who've been there, done that on production systems for at least 15 years: veteran author and developer Jeff Langr, building on the wisdom of Pragmatic Programmers Andy Hunt and Dave Thomas. You'll learn:
  • How to craft your unit tests to minimize your effort in maintaining them.
  • How to use unit tests to help keep your system clean.
  • How to test the tough stuff.
  • Memorable mnemonics to help you remember what's important when writing unit tests.
  • How to help your team reap and sustain the benefits of unit testing.
You won't just learn about unit testing in theory--you'll work through numerous code examples. When it comes to programming, hands-on is the only way to learn!

Monday, March 23, 2015

Beginning Java Programming: The Object-Oriented Approach

Beginning Java Programming: The Object-Oriented Approach

A comprehensive Java guide, with samples, exercises, casestudies, and step-by-step instruction

Beginning Java Programming: The Object Oriented Approachis a straightforward resource for getting started with one of theworld's most enduringly popular programming languages. Based onclasses taught by the authors, the book starts with the basics andgradually builds into more advanced concepts. The approach utilizesan integrated development environment that allows readers toimmediately apply what they learn, and includes step-by-stepinstruction with plenty of sample programs. Each chapter containsexercises based on real-world business and educational scenarios,and the final chapter uses case studies to combine several conceptsand put readers' new skills to the test.

Beginning Java Programming: The Object Oriented Approachprovides both the information and the tools beginners need todevelop Java skills, from the general concepts of object-orientedprogramming. Learn to: * Understand the Java language and object-oriented conceptimplementation * Use Java to access and manipulate external data * Make applications accessible to users with GUIs * Streamline workflow with object-oriented patterns

The book is geared for those who want to use Java in an appliedenvironment while learning at the same time. Useful as either acourse text or a stand-alone self-study program, Beginning JavaProgramming is a thorough, comprehensive guide.

Install NetBeans on Raspberry Pi/Raspbian for Java and C/C++ development

The blog "Hello Raspberry Pi" have posts to show how to Install NetBeans on Raspberry Pi/Raspbian for Java and C/C++ development.

Install NetBeans IDE on Raspberry Pi 2/Raspbian, to program using Java


Install C/C++ plugins for NetBeans on Raspberry Pi 2/Raspbian


Wednesday, March 18, 2015

Get System Java Compiler and check sourceVersion

Example to get System Java Compiler by calling ToolProvider.getSystemJavaCompiler(), and check sourceVersion with getSourceVersions().



package java_javacompiler;

import java.util.Set;
import javax.lang.model.SourceVersion;
import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;

public class Java_JavaCompiler {

    public static void main(String[] args) {
        JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
        System.out.print(javaCompiler.toString());
        
        Set<SourceVersion> sourceVersion;
        sourceVersion = javaCompiler.getSourceVersions();
        
        for (SourceVersion version : sourceVersion) {
            System.out.print(version.name() + "\n");
        }
        
    }
    
}


Tuesday, March 17, 2015

Java code to get number of processors available

Every Java application has a single instance of class Runtime that allows the application to interface with the environment in which the application is running. The current runtime can be obtained from the getRuntime() method.

availableProcessors() method of Runtime returns the number of processors available to the Java virtual machine.

This value may change during a particular invocation of the virtual machine. Applications that are sensitive to the number of available processors should therefore occasionally poll this property and adjust their resource usage appropriately.

Example:
package java_availableprocessors;

public class Java_availableProcessors {

    public static void main(String[] args) {
        System.out.print("availableProcessors = " 
            + Runtime.getRuntime().availableProcessors() + "\n");
    }
    
}


Wednesday, March 4, 2015

OpenJDK Cookbook

OpenJDK cookbook

Over 80 recipes to build and extend your very own version of Java platform using OpenJDK project

About This Book
  • Gain the skills required to harness the power of OpenJDK's Java implementation
  • Extend and adapt Java Platform to develop various types of applications
  • A practical guide to learn how to benefit from AdoptOpenJDK programme, a part of the OpenJDK community
Who This Book Is For
If you are an experienced Java developer using Java 7 platform and want to get your grips on OpenJDK for Java development, this is the book for you. JDK users who wish to migrate to OpenJDK will find this book very useful.

In Detail
OpenJDK is one of the most widely used open source implementations of the Java platform. It is used to change, customize, and tune core application internals and provide a way to extend the application internals according to your requirements.

OpenJDK Cookbook begins by introducing you to OpenJDK and IcedTea builds for various virtual machine implementations and how to deploy OpenJDK on multiple platforms. Furthermore, the book digs deeper into the development concepts, JVM internals, and techniques to make robust improvements or customizations to OpenJDK. Essentially, the book covers the best practices for accessing and using the core features of OpenJDK to build advanced Java solutions by utilizing the more complex and nuanced parts of OpenJDK.

Java Cookbook, 3rd edition

Java Cookbook

From lambda expressions and JavaFX 8 to new support for network programming and mobile development, Java 8 brings a wealth of changes. This cookbook helps you get up to speed right away with hundreds of hands-on recipes across a broad range of Java topics. You’ll learn useful techniques for everything from debugging and data structures to GUI development and functional programming.

Each recipe includes self-contained code solutions that you can freely use, along with a discussion of how and why they work. If you are familiar with Java basics, this cookbook will bolster your knowledge of the language in general and Java 8’s main APIs in particular.

Recipes include:
  • Methods for compiling, running, and debugging
  • Manipulating, comparing, and rearranging text
  • Regular expressions for string- and pattern-matching
  • Handling numbers, dates, and times
  • Structuring data with collections, arrays, and other types
  • Object-oriented and functional programming techniques
  • Directory and filesystem operations
  • Working with graphics, audio, and video
  • GUI development, including JavaFX and handlers
  • Network programming on both client and server
  • Database access, using JPA, Hibernate, and JDBC
  • Processing JSON and XML for data storage
  • Multithreading and concurrency