Monday, September 30, 2013

James Gosling at NetBeans Day 2013

James Gosling (father of the Java) celebrates NetBeans' 15th birthday at JavaOne 2013 and describes the fun he is having with Java.

Run TimerTask in scheduled, repeated fixed-rate.

Example to trigger scheduled, repeated fixed-rate TimerTask, by calling timer.scheduleAtFixedRate().

Run TimerTask in scheduled, repeated fixed-rate.
Run TimerTask in scheduled, repeated fixed-rate.


package java_time;

import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

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

    public static void main(String[] args) {

        Calendar calendar = Calendar.getInstance();
        Date calendarDate = calendar.getTime();
        System.out.println("Now: " + calendarDate);

        Calendar cal_1min = Calendar.getInstance();
        cal_1min.add(Calendar.MINUTE, 1);
        Date date_1min = cal_1min.getTime();
        System.out.println("1 min later: " + date_1min);
        
        
        TimerTask timeTask = new TimerTask(){

            @Override
            public void run() {
                Calendar timerNow = Calendar.getInstance();
                Date timerNowDate = timerNow.getTime();
                System.out.println("Timer reached: " + timerNowDate);
            }
            
        };
        
        Timer timer = new Timer();
        
        //One time only
        //timer.schedule(timeTask, date_1min);
        
        //Trigger scheduled, repeated fixed-rate TimerTask
        timer.scheduleAtFixedRate(
                timeTask,   //task to be scheduled
                date_1min,  //First time at which task is to be executed    
                5000);    //repeat period, in milliseconds
    }
}


Sunday, September 29, 2013

Timer and TimerTask example, execute code in a specified time.

This example implement a TimerTask object. It's run() method will be called in 1 minute later, set with Timer.schedule() method.

Timer and TimerTask example
Timer and TimerTask example

package java_time;

import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

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

    public static void main(String[] args) {

        Calendar calendar = Calendar.getInstance();
        Date calendarDate = calendar.getTime();
        System.out.println("Now: " + calendarDate);

        Calendar cal_1min = Calendar.getInstance();
        cal_1min.add(Calendar.MINUTE, 1);
        Date date_1min = cal_1min.getTime();
        System.out.println("1 min later: " + date_1min);
        
        TimerTask timeTask = new TimerTask(){

            @Override
            public void run() {
                
                Calendar timerNow = Calendar.getInstance();
                Date timerNowDate = timerNow.getTime();
                System.out.println("1 min Timer reached: " + timerNowDate);
            }
            
        };
        
        Timer timer = new Timer();
        timer.schedule(timeTask, date_1min);
        
    }
}


Next: Run TimerTask in scheduled, repeated fixed-rate.

Saturday, September 28, 2013

Add Date to Calendar

Example to add/minus one Day in Calendar, to get tomorrow and yesterday.

Add/Minus Date to Calendar


package java_time;

import java.util.Calendar;
import java.util.Date;

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

    public static void main(String[] args) {

        Calendar calendar = Calendar.getInstance();
        Date calendarDate = calendar.getTime();
        System.out.println("Now: " + calendarDate);
        
        Calendar cal_Tomorrow = Calendar.getInstance();
        cal_Tomorrow.add(Calendar.DATE, 1);
        Date date_Tomorrow = cal_Tomorrow.getTime();
        System.out.println("Tomorrow: " + date_Tomorrow);
        
        Calendar cal_Yesterday = Calendar.getInstance();
        cal_Yesterday.add(Calendar.DATE, -1);
        Date date_Yesterday = cal_Yesterday.getTime();
        System.out.println("Yesterday: " + date_Yesterday);

    }
}


Friday, September 27, 2013

Example of using SimpleDateFormat

SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner. It allows for formatting (date -> text), parsing (text -> date), and normalization. It allows you to start by choosing any user-defined patterns for date-time formatting.

Example:
Example of using SimpleDateFormat
Example of using SimpleDateFormat

package java_time;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

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

    public static void main(String[] args) {

        Calendar now = Calendar.getInstance();
        Date nowDate = now.getTime();
        System.out.println(nowDate);
        
        SimpleDateFormat format;
        String formattedString;
        
        format = new SimpleDateFormat("yyyy-MM-dd kk:mm:ss");
        formattedString = format.format(nowDate);
        System.out.println(formattedString);
        
        format = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss(a)");
        formattedString = format.format(nowDate);
        System.out.println(formattedString);

    }
}


Monday, September 23, 2013

Print formated Date

The example show various format to printf() Date object.

Print formated Date
Print formated Date

package java_time;

import java.util.Date;

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

    public static void main(String[] args) {
        Date now = new Date();

        System.out.println("default: " + now);
        System.out.printf("c: %tc\n", now);
        System.out.printf("D: %tD\n", now);
        System.out.printf("F: %tF\n", now);
        System.out.printf("r: %tr\n", now);
        System.out.printf("R: %tR\n", now);
        System.out.printf("T: %tT\n", now);
    }
}


Sunday, September 22, 2013

Getting Started with JavaFX 3D Graphics

The tutorial, Getting Started with JavaFX 3D Graphics, contains information about the JavaFX 3D graphics functionality available in JavaFX 8.

- Overview
- 3D Shapes
- Camera
- Subscene
- Lights
- Materials
- Picking
- Building a 3D Sample Application

It is assumed that you have an intermediate level of Java and JavaFX knowledge. Download JDK 8 Developer Preview release from http://jdk8.java.net/download.html.

Java Web Services: Up and Running, 2nd edition

Java Web Services: Up and Running

Learn how to develop REST-style and SOAP-based web services and clients with this quick and thorough introduction. This hands-on book delivers a clear, pragmatic approach to web services by providing an architectural overview, complete working code examples, and short yet precise instructions for compiling, deploying, and executing them. You’ll learn how to write services from scratch and integrate existing services into your Java applications.

With greater emphasis on REST-style services, this second edition covers HttpServlet, Restlet, and JAX-RS APIs; jQuery clients against REST-style services; and JAX-WS for SOAP-based services. Code samples include an Apache Ant script that compiles, packages, and deploys web services.
  • Learn differences and similarities between REST-style and SOAP-based services
  • Program and deliver RESTful web services, using Java APIs and implementations
  • Explore RESTful web service clients written in Java, JavaScript, and Perl
  • Write SOAP-based web services with an emphasis on the application level
  • Examine the handler and transport levels in SOAP-based messaging
  • Learn wire-level security in HTTP(S), users/roles security, and WS-Security
  • Use a Java Application Server (JAS) as an alternative to a standalone web server

Saturday, September 21, 2013

Get current time in different TimeZone

This example call setTimeZone() method of GregorianCalendar object to switch to different TimeZone, and get the current time in the target timezone.

Get current time in different TimeZone


package java_timezone;

import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.TimeZone;

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

    public static void main(String[] args) {
        System.out.println("Default TimeZone: " + 
                TimeZone.getDefault().getDisplayName());
        
        GregorianCalendar now = new GregorianCalendar();
        
        String AMPM;
        if(now.get(Calendar.AM_PM) == Calendar.AM){
            AMPM = "AM";
        }else{
            AMPM = "PM";
        }
        
        System.out.println(
                now.get(Calendar.YEAR) + "-" +
                now.get(Calendar.MONTH) + "-" +
                now.get(Calendar.DAY_OF_MONTH) + " " +
                AMPM + ":" +
                now.get(Calendar.HOUR) + ":" +
                now.get(Calendar.HOUR_OF_DAY) + ":" +
                now.get(Calendar.MINUTE));
        
        String[] availableIDs = TimeZone.getAvailableIDs();
        System.out.println("number of available TimeZone IDs: " + 
                availableIDs.length);
        
        for (String id : availableIDs){
            System.out.print(
                    "ID: " + id + 
                    " | " + TimeZone.getTimeZone(id).getDisplayName());
            
            System.out.print("@");
            
            now.setTimeZone(TimeZone.getTimeZone(id));
            String idAMPM;
            if(now.get(Calendar.AM_PM) == Calendar.AM){
                idAMPM = "AM";
            }else{
                idAMPM = "PM";
            }
            System.out.println(
                now.get(Calendar.YEAR) + "-" +
                now.get(Calendar.MONTH) + "-" +
                now.get(Calendar.DAY_OF_MONTH) + " " +
                idAMPM + ":" +
                now.get(Calendar.HOUR) + ":" +
                now.get(Calendar.HOUR_OF_DAY) + ":" +
                now.get(Calendar.MINUTE));
        }
    }
}

Friday, September 20, 2013

Get available TimeZone with java.util.TimeZone

Example to get available TimeZone with java.util.TimeZone class.

Get available TimeZone
Get available TimeZone


package java_timezone;

import java.util.TimeZone;

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

    public static void main(String[] args) {
        System.out.println("Default TimeZone: " + 
                TimeZone.getDefault().getDisplayName());
        
        String[] availableIDs = TimeZone.getAvailableIDs();
        System.out.println("number of available TimeZone IDs: " + 
                availableIDs.length);
        
        for (String id : availableIDs){
            System.out.println(
                    "ID: " + id + 
                    " | " + TimeZone.getTimeZone(id).getDisplayName());
        }
    }
}

Wednesday, September 18, 2013

JAVA EE 7 ESSENTIALS

JAVA EE 7 ESSENTIALS

Get up to speed on the principal technologies in the Java Platform, Enterprise Edition 7, and learn how the latest version embraces HTML5, focuses on higher productivity, and provides functionality to meet enterprise demands. Written by Arun Gupta, a key member of the Java EE team, this book provides a chapter-by-chapter survey of several Java EE 7 specifications, including WebSockets, Batch Processing, RESTful Web Services, and Java Message Service.
You’ll also get self-paced instructions for building an end-to-end application with many of the technologies described in the book, which will help you understand the design patterns vital to Java EE development.
  • Understand the key components of the Java EE platform, with easy-to-understand explanations and extensive code samples
  • Examine all the new components that have been added to Java EE 7 platform, such as WebSockets, JSON, Batch, and Concurrency
  • Learn about RESTful Web Services, SOAP XML-based messaging protocol, and Java Message Service
  • Explore Enterprise JavaBeans, Contexts and Dependency Injection, and the Java Persistence API
  • Discover how different components were updated from Java EE 6 to Java EE 7

JavaFX BoxBlur effect

javafx.scene.effect.BoxBlur using a simple box filter kernel, with separately configurable sizes in both dimensions. And also an iteration parameter that controls the quality of the resulting blur.

BoxBlur effect
BoxBlur effect

package javafx_boxblur;

import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.Slider;
import javafx.scene.control.SliderBuilder;
import javafx.scene.control.Tooltip;
import javafx.scene.effect.BoxBlur;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFX_BoxBlur extends Application {
    
    @Override
    public void start(Stage primaryStage) {
        Image image = new Image("http://goo.gl/kYEQl");
        ImageView imageView = new ImageView();
        imageView.setImage(image);
        Label label = new Label("Java-buddy");
        HBox hBox = new HBox();
        hBox.getChildren().addAll(imageView, label);
        
        final BoxBlur boxBlur = new BoxBlur();
        hBox.setEffect(boxBlur);
        
        Slider sliderWidth = SliderBuilder.create()
                .layoutX(50)
                .layoutY(50)
                .prefWidth(400)
                .min(0)
                .max(255)
                .majorTickUnit(20)
                .minorTickCount(3)
                .showTickMarks(true)
                .showTickLabels(true)
                .value(5)
                .tooltip(new Tooltip("BoxBlur.width"))
                .build();
        sliderWidth.valueProperty().addListener(new ChangeListener<Number>() {

            @Override
            public void changed(ObservableValue<? extends Number> ov, 
                    Number t, Number t1) {
                boxBlur.setWidth(t1.doubleValue());
            }
        });
        
        Slider sliderHeight = SliderBuilder.create()
                .layoutX(50)
                .layoutY(50)
                .prefWidth(400)
                .min(0)
                .max(255)
                .majorTickUnit(20)
                .minorTickCount(3)
                .showTickMarks(true)
                .showTickLabels(true)
                .value(5)
                .tooltip(new Tooltip("BoxBlur.height"))
                .build();
        sliderHeight.valueProperty().addListener(new ChangeListener<Number>() {

            @Override
            public void changed(ObservableValue<? extends Number> ov, 
                    Number t, Number t1) {
                boxBlur.setHeight(t1.doubleValue());
            }
        });
        
        VBox vBox = new VBox();
        vBox.getChildren().addAll(hBox, sliderWidth, sliderHeight);
 
        StackPane root = new StackPane();
        root.getChildren().add(vBox);
        Scene scene = new Scene(root, 300, 300);
        primaryStage.setTitle("java-buddy.blogspot.com");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

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

Monday, September 9, 2013

JDK 8 Documentation - Developer Preview Release

Java Development Kit Release 8 (JDK 8) Early Access Documentation, which helps developers explore features in the upcoming JDK 8 release, has been enhanced and updated. It comprises the Developer Guides, The Java Tutorials, and API documentation.

Download JDK 8 Early Access from JDK 8 Project.

(source: https://blogs.oracle.com/thejavatutorials/entry/jdk_8_documentation_developer_preview)


JDK 8 Developer Preview

The JDK 8 Developer Preview (a.k.a. Milestone 8) builds are now available!

(source: http://mreinhold.org/blog/jdk8-preview)

Saturday, September 7, 2013

JavaFX photo application demo

JavaFX photo application created by Felipe Pedroso


Detect mouse events on JavaFX Charts

This example demonstrate how to detect mouse events on JavaFX Charts.

Detect mouse events on JavaFX Charts
Detect mouse events on JavaFX Charts


package javafx_charts;

import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.chart.AreaChart;
import javafx.scene.chart.CategoryAxis;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.scene.input.MouseEvent;
import javafx.stage.Stage;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFX_Charts extends Application {
    
    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("java-buddy.blogspot.com");
        Group root = new Group();
          
        final CategoryAxis xAxis = new CategoryAxis();
        final NumberAxis yAxis = new NumberAxis();
          
        xAxis.setLabel("Month");
        yAxis.setLabel("Value");

        final AreaChart<String,Number> areaChart = new AreaChart<>(xAxis,yAxis);
  
        areaChart.setTitle("AreaChart");
         
        //Series 1
        XYChart.Series series1 = new XYChart.Series();
        series1.setName("XYChart.Series 1");
          
        series1.getData().add(new XYChart.Data("January", 100));
        series1.getData().add(new XYChart.Data("February", 200));
        series1.getData().add(new XYChart.Data("March", 50));
        series1.getData().add(new XYChart.Data("April", 75));
        series1.getData().add(new XYChart.Data("May", 110));
        series1.getData().add(new XYChart.Data("June", 300));
        series1.getData().add(new XYChart.Data("July", 111));
        series1.getData().add(new XYChart.Data("August", 30));
        series1.getData().add(new XYChart.Data("September", 75));
        series1.getData().add(new XYChart.Data("October", 55));
        series1.getData().add(new XYChart.Data("November", 225));
        series1.getData().add(new XYChart.Data("December", 99));
          
        //Series 2
        XYChart.Series series2 = new XYChart.Series();
        series2.setName("XYChart.Series 2");
          
        series2.getData().add(new XYChart.Data("January", 150));
        series2.getData().add(new XYChart.Data("February", 100));
        series2.getData().add(new XYChart.Data("March", 60));
        series2.getData().add(new XYChart.Data("April", 40));
        series2.getData().add(new XYChart.Data("May", 30));
        series2.getData().add(new XYChart.Data("June", 100));
        series2.getData().add(new XYChart.Data("July", 100));
        series2.getData().add(new XYChart.Data("August", 10));
        series2.getData().add(new XYChart.Data("September", 175));
        series2.getData().add(new XYChart.Data("October", 155));
        series2.getData().add(new XYChart.Data("November", 125));
        series2.getData().add(new XYChart.Data("December", 150));
 
        areaChart.getData().addAll(series1, series2);

        setOnMouseEventsOnSeries(series1.getNode(), 
            areaChart, "Series 1 clicked");
        setOnMouseEventsOnSeries(series2.getNode(), 
            areaChart, "Series 2 clicked");
  
        root.getChildren().addAll(areaChart);
        primaryStage.setScene(new Scene(root, 500, 400));
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
    
    private void setOnMouseEventsOnSeries(Node node, 
            final AreaChart chart, final String label) {
        
        node.setOnMouseClicked(new EventHandler<MouseEvent>() {

            @Override
            public void handle(MouseEvent t) {
               chart.setTitle(label);
            }
        });
        
    }

}



Wednesday, September 4, 2013

Apply custom style on AreaChart

The post "Area Chart with two series of data" use default style of AreaChart. By applying CSS, you can define your own style on chart.

AreaChart with custom style
AreaChart with custom style

Create chartStyle.css in the same folder of the main java, define style of the AreaChart.
.default-color0.chart-area-symbol { -fx-background-color: #FFFFFFFF, #FFFFFFFF; }
.default-color1.chart-area-symbol { -fx-background-color: #00000000, #00000000; }
 
.default-color0.chart-series-area-line { -fx-stroke: #FF0000; }
.default-color1.chart-series-area-line { -fx-stroke: #0000FF; }
 
.default-color0.chart-series-area-fill { -fx-fill: #00FF00; }
.default-color1.chart-series-area-fill { -fx-fill: #00000000; }


Main java code.
package javafx_charts;

import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.chart.AreaChart;
import javafx.scene.chart.CategoryAxis;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.stage.Stage;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFX_Charts extends Application {
    
    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("java-buddy.blogspot.com");
        Group root = new Group();
          
        final CategoryAxis xAxis = new CategoryAxis();
        final NumberAxis yAxis = new NumberAxis();
          
        xAxis.setLabel("Month");
        yAxis.setLabel("Value");

        final AreaChart<String,Number> areaChart = new AreaChart<>(xAxis,yAxis);
  
        areaChart.setTitle("AreaChart");
         
        //Series 1
        XYChart.Series series1 = new XYChart.Series();
        series1.setName("XYChart.Series 1");
          
        series1.getData().add(new XYChart.Data("January", 100));
        series1.getData().add(new XYChart.Data("February", 200));
        series1.getData().add(new XYChart.Data("March", 50));
        series1.getData().add(new XYChart.Data("April", 75));
        series1.getData().add(new XYChart.Data("May", 110));
        series1.getData().add(new XYChart.Data("June", 300));
        series1.getData().add(new XYChart.Data("July", 111));
        series1.getData().add(new XYChart.Data("August", 30));
        series1.getData().add(new XYChart.Data("September", 75));
        series1.getData().add(new XYChart.Data("October", 55));
        series1.getData().add(new XYChart.Data("November", 225));
        series1.getData().add(new XYChart.Data("December", 99));
          
        //Series 2
        XYChart.Series series2 = new XYChart.Series();
        series2.setName("XYChart.Series 2");
          
        series2.getData().add(new XYChart.Data("January", 150));
        series2.getData().add(new XYChart.Data("February", 100));
        series2.getData().add(new XYChart.Data("March", 60));
        series2.getData().add(new XYChart.Data("April", 40));
        series2.getData().add(new XYChart.Data("May", 30));
        series2.getData().add(new XYChart.Data("June", 100));
        series2.getData().add(new XYChart.Data("July", 100));
        series2.getData().add(new XYChart.Data("August", 10));
        series2.getData().add(new XYChart.Data("September", 175));
        series2.getData().add(new XYChart.Data("October", 155));
        series2.getData().add(new XYChart.Data("November", 125));
        series2.getData().add(new XYChart.Data("December", 150));
 
        areaChart.getData().addAll(series1, series2);
        
        areaChart.getStylesheets().add(
                getClass().getResource("chartStyle.css").toExternalForm());
              
        root.getChildren().addAll(areaChart);
        primaryStage.setScene(new Scene(root, 500, 400));
        primaryStage.show();
    }

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


Reference: Styling Charts with CSS.

Tuesday, September 3, 2013

SimpleFileVisitor example

java.nio.file.SimpleFileVisitor is a simple visitor of files with default behavior to visit all files and to re-throw I/O errors.

Simple example using SimpleFileVisitor.
package java_simplefilevisitor;

import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class Java_SimpleFileVisitor {
    
    public static class MySimpleFileVisitor extends SimpleFileVisitor<Path> {

        @Override
        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) 
                throws IOException {
            System.out.format("preVisitDirectory: %s\n", dir);
            return super.preVisitDirectory(dir, attrs);
        }

        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) 
                throws IOException {
            System.out.format("visitFile: %s\n", file);
            return super.visitFile(file, attrs);
        }

        @Override
        public FileVisitResult visitFileFailed(Path file, IOException exc) 
                throws IOException {
            System.out.format("visitFileFailed: %s\n", file);
            return super.visitFileFailed(file, exc);
        }

        @Override
        public FileVisitResult postVisitDirectory(Path dir, IOException exc) 
                throws IOException {
            System.out.format("postVisitDirectory: %s\n", dir);
            return super.postVisitDirectory(dir, exc);
        }
        
    }

    public static void main(String[] args) {
        Path path = Paths.get("/home/eric/NetBeansProjects/Java_SimpleFileVisitor");
        MySimpleFileVisitor mySimpleFileVisitor = new MySimpleFileVisitor();
        
        try {
            Files.walkFileTree(path, mySimpleFileVisitor);
        } catch (IOException ex) {
            Logger.getLogger(Java_SimpleFileVisitor.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}


SimpleFileVisitor
SimpleFileVisitor example


Reference:
- Class SimpleFileVisitor
- Walking the File Tree


Monday, September 2, 2013

Set memory option for JVM

The -J-Xmx... option tells the Java virtual machine the maximum amount of memory it should use for the heap. Placing a hard upper limit on this number means that the Java process cannot consume more memory than physical RAM available. This limit can be raised on systems with more memory. Current default value is 128MB. Note: Do not set this value to near or greater than the amount of physical RAM in your system or it will cause severe swapping during runtime.

~ details: https://performance.netbeans.org/howto/jvmswitches/

To set -Xmx option in Netbeans:

- Right click project, select Properties.


- Select Run tab, enter your setting in VM Options.


The option -Xmx1g request 1G of maximum memory for JVM. Run the example code in last post to varify.




Get runtime memory with Java code

To get total memory, maximum memory and free memory in Java Virtual Machine using Java code.

Get runtime memory with Java code
Get runtime memory with Java code


package java_runtimememory;

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

    public static void main(String[] args) {
        System.out.println(Runtime.getRuntime().toString() + "\n");
        
        System.out.println("totalMemory: the total amount of memory in the Java "
                + "virtual machine.\n"
                + Runtime.getRuntime().totalMemory());

        System.out.println("maxMemory: the maximum amount of memory that the "
                + "Java virtual machine will attempt to use.\n" 
                + Runtime.getRuntime().maxMemory());

        System.out.println("freeMemory: the amount of free memory in the Java "
                + "Virtual Machine.\n" 
                + Runtime.getRuntime().freeMemory());
    }
}


Related: Set memory option for JVM