Shared info of IoT & Cloud, Banking, Angular Wicket, Spring Reactive, AI, Flutter, E-comm, Java Telecomm and More.

Showing posts with label Java Permanent. Show all posts
Showing posts with label Java Permanent. Show all posts

Monday, September 3, 2018

Java Concurrency

1. Java Concurrency from docs.oracle.com
Computer users take it for granted that their systems can do more than one thing at a time. They assume that they can continue to work in a word processor, while other applications download files, manage the print queue, and stream audio. Even a single application is often expected to do more than one thing at a time. For example, that streaming audio application must simultaneously read the digital audio off the network, decompress it, manage playback, and update its display. Even the word processor should always be ready to respond to keyboard and mouse events, no matter how busy it is reformatting text or updating the display. Software that can do such things is known as concurrent software.
The Java platform is designed from the ground up to support concurrent programming, with basic concurrency support in the Java programming language and the Java class libraries. Since version 5.0, the Java platform has also included high-level concurrency APIs. This lesson introduces the platform's basic concurrency support and summarizes some of the high-level APIs in the java.util.concurrent packages.

Friday, May 12, 2017

Gioi thieu Java 8 - Lambda Expressions

Lambda expressions duoc gioi thieu trong Java 8 va duoc coi la mot trong nhung dac diem lon nhat cua Java 8. Lambda expression tang cuong ho tro functional programming, va lam don gian hoa viec viet code.

Syntax

Mot lambda expression duoc dac ta boi cu phap sau −
parameter -> expression body
Following are the important 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.

Lambda Expressions Example

Create the following Java program using editor and save in some folder like C:\>JAVA.

Java8Tester.java

public class Java8Tester {
   public static void main(String args[]){
      Java8Tester tester = new Java8Tester();
  
      //with type declaration
      MathOperation addition = (int a, int b) -> a + b;
  
      //with out type declaration
      MathOperation subtraction = (a, b) -> a - b;
  
      //with return statement along with curly braces
      MathOperation multiplication = (int a, int b) -> { return a * b; };
  
      //without return statement and without curly braces
      MathOperation division = (int a, int b) -> a / b;
  
      System.out.println("10 + 5 = " + tester.operate(10, 5, addition));
      System.out.println("10 - 5 = " + tester.operate(10, 5, subtraction));
      System.out.println("10 x 5 = " + tester.operate(10, 5, multiplication));
      System.out.println("10 / 5 = " + tester.operate(10, 5, division));
  
      //without parenthesis
      GreetingService greetService1 = message ->
      System.out.println("Hello " + message);
  
      //with parenthesis
      GreetingService greetService2 = (message) ->
      System.out.println("Hello " + message);
  
      greetService1.sayMessage("Mahesh");
      greetService2.sayMessage("Suresh");
   }
 
   interface MathOperation {
      int operation(int a, int b);
   }
 
   interface GreetingService {
      void sayMessage(String message);
   }
 
   private int operate(int a, int b, MathOperation mathOperation){
      return mathOperation.operation(a, b);
   }
}

Verify the Result

Compile the class using javac compiler as follows −
$javac Java8Tester.java
Now run the Java8Tester as follows −
$java Java8Tester
It should produce the following output −
10 + 5 = 15
10 - 5 = 5
10 x 5 = 50
10 / 5 = 2
Hello Mahesh
Hello Suresh
Following are the important points to be considered in the above example.
  • Lambda expressions are used primarily to define inline implementation of a functional interface, i.e., an interface with a single method only. In the above example, we've used various types of lambda expressions to define the operation method of MathOperation interface. Then we have defined the implementation of sayMessage of GreetingService.
  • Lambda expression eliminates the need of anonymous class and gives a very simple yet powerful functional programming capability to Java.

Scope

Using lambda expression, you can refer to final variable or effectively final variable (which is assigned only once). Lambda expression throws a compilation error, if a variable is assigned a value the second time.

Scope Example

Create the following Java program using editor and save in some folder like C:\>JAVA.
Java8Tester.java
public class Java8Tester {

   final static String salutation = "Hello! ";
   
   public static void main(String args[]){
      GreetingService greetService1 = message -> 
      System.out.println(salutation + message);
      greetService1.sayMessage("Mahesh");
   }
 
   interface GreetingService {
      void sayMessage(String message);
   }
}

Verify the Result

Compile the class using javac compiler as follows −
$javac Java8Tester.java
Now run the Java8Tester as follows −
$java Java8Tester
It should produce the following output −
Hello! Mahesh

Saturday, April 16, 2016

Install Android Studio & Java8

Install Java JDK 1.8

  • Download jdk-8uversion-linux-x64.tar.gz file from http://www.oracle.com/technetwork/java/javase/downloads/index.html
  • Unpack the tarball and install the JDK.
    % tar zxvf jdk-8uversion-linux-x64.tar.gz
  • Set up the JAVA_HOME and ANDROID_HOME
    For example, ANDROID_HOME=/home/demo/java/exo-dependencies/Android/AndroidStudio_Latest/SDK
    JAVA_HOME=/home/demo/java/jdk1.8.0_77
    PATH=/usr/local/bin:$PATH:$JAVA_HOME/bin:$M2_HOME/bin:$GRADLE_HOME/bin:$ANDROID_HOME/platform-tools:$ANDROID_HOME/tools
Install Android Studio on Ubuntu
Setting up Android Studio takes just a few clicks.
While the Android Studio download completes, verify which version of the JDK you have: open a command line and type javac -version. If the JDK is not available or the version is lower than 1.8, download the Java SE Development Kit 8.
To install Android Studio on Linux, proceed as follows:
  1. Unpack the .zip file you downloaded to an appropriate location for your applications, such as within /usr/local/for your user profile, or /opt/ for shared users.
  2. To launch Android Studio, open a terminal, navigate to the android-studio/bin/ directory, and executestudio.sh.
    Tip: Add android-studio/bin/ to your PATH environment variable so you can start Android Studio from any directory.
  3. Select whether you want to import previous Android Studio settings or not, then click OK.
  4. The Android Studio Setup Wizard guides you though the rest of the setup, which includes downloading Android SDK components that are required for development.
Note: If you are running a 64-bit version of Ubuntu, you need to install some 32-bit libraries with the following command:
sudo apt-get install lib32z1 lib32ncurses5 lib32bz2-1.0 lib32stdc++6
If you are running 64-bit Fedora, the command is:
sudo yum install zlib.i686 ncurses-libs.i686 bzip2-libs.i686
That's it! The following video shows each step of the recommended setup procedure.


Wednesday, April 15, 2015

Number literals in Java

Numbers

Numbers in Java can be written in many different forms. Depending on the prefix or suffix we use, we can declare it’s base (binaryhexoctal), and even it’s type (intlongfloat).

Alterations in the base:

With literal prefixes we can define 4 different numeric bases, and they are: OctalHexadecimalDecimal and Binary.

Tuesday, March 13, 2012

Java 2D: Composition Rules

In the standard RGB color model, every color is described by its red, green, and blue components. However, it is also convenient to be able to describe areas of an image that are transparent or partially transparent. When you superimpose an image onto an existing drawing, the transparent pixels do not obscure the pixels under them at all, whereas partially transparent pixels are mixed with the pixels under them. Figure 7-23 shows the effect of overlaying a partially transparent rectangle on an image. You can still see the details of the image shine through from under the rectangle.

Figure 7-23. Overlaying a partially transparent rectangle on an image

 

In the Java 2D API, transparency is described by an alpha channel. Each pixel has, in addition to its red, green, and blue color components, an alpha value between 0 (fully transparent) and 1 (fully opaque). For example, the rectangle in Figure 7-23 was filled with a pale yellow color with 50% transparency:
new Color(0.7F, 0.7F, 0.0F, 0.5F);

Monday, March 12, 2012

Java 2D: clipping

1. What isclipping
Clipping is the process of confining paint operations to a limited area or shape.

2. Clipping the Drawing Region
Any Shape object can be used as a clipping path that restricts the portion of the drawing area that will be rendered. The clipping path is part of the Graphics2Dcontext; to set the clip attribute, you call Graphics2D.setClip and pass in the Shape that defines the clipping path you want to use. You can shrink the clipping path by calling the clip method and passing in another Shape; the clip is set to the intersection of the current clip and the specified Shape.

Friday, March 9, 2012

Java 2D: Areas, Strokes, Paint

Areas
An Area object stores and manipulates a resolution-independent description of an enclosed area of 2-dimensional space. Area objects can be transformed and can perform various Constructive Area Geometry (CAG) operations when combined with other Area objects. The CAG operations include area additionsubtractionintersection, and exclusive or. See the linked method documentation for examples of the various operations.
The Area class implements the Shape interface and provides full support for all of its hit-testing and path iteration facilities, but an Area is more specific than a generalized path in a number of ways..

With the Area class, you can perform boolean operations, such as union, intersection, and subtraction, on any two Shape objects. This technique, often referred to as constructive area geometry, enables you to quickly create complex Shape objects without having to describe each line segment or curve.

Area - Core Java™ 2 Volume II - Advanced Features, Seventh Edition

Sunday, March 4, 2012

Java 2D: Shapes

Here are some of the methods in the Graphics class to draw shapes:
drawLine
drawRectangle
drawRoundRect
draw3DRect
drawPolygon
drawPolyline
drawOval
drawArc
There are also corresponding fill methods. These methods have been in the Graphics class ever since JDK 1.0. The Java 2D API uses a completely different, object-oriented approach. Instead of methods, there are classes:
Line2D
Rectangle2D
RoundRectangle2D
Ellipse2D
Arc2D
QuadCurve2D
CubicCurve2D
GeneralPath
These classes all implement the Shape interface.
Finally, the Point2D class describes a point with an x- and a y-coordinate. Points are useful to define shapes, but they aren't themselves shapes.

Java 2D: Ví dụ ShapesDemo2D.java

GeneralPath class implements the Shape interface and represents a geometric path constructed from lines, and quadratic and cubic curves. The three constructors in this class can create the GeneralPath object with the default winding rule (WIND_NON_ZERO), the given winding rule (WIND_NON_ZERO or WIND_EVEN_ODD), or the specified initial coordinate capacity. The winding rule specifies how the interior of a path is determined.
public void Paint (Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    ...
} 

Saturday, February 25, 2012

Java 2D: Coordinate Transformations

Coordinates

The Java 2D™ API maintains two coordinate spaces:
  • User space – The space in which graphics primitives are specified
  • Device space – The coordinate system of an output device such as a screen, window, or a printer
User space is a device-independent logical coordinate system, the coordinate space that your program uses. All geometries passed into Java 2D rendering routines are specified in user-space coordinates.
When the default transformation from user space to device space is used, the origin of user space is the upper-left corner of the component’s drawing area. The xcoordinate increases to the right, and the y coordinate increases downward, as shown in the following figure. The top-left corner of a window is 0,0. All coordinates are specified using integers, which is usually sufficient. However, some cases require floating point or even double precision which are also supported.

Friday, February 24, 2012

ImageProcessing: Working with Images

As you have already learned from the Images lesson, Images are described by a width and a height, measured in pixels, and have a coordinate system that is independent of the drawing surface.
There are a number of common tasks when working with images.
  • Loading an external GIF, PNG JPEG image format file into Java 2D™'s internal image representation.
  • Directly creating a Java 2D image and rendering to it.
  • Drawing the contents of a Java 2D image on to a drawing surface.
  • Saving the contents of a Java 2D image to an external GIF, PNG, or JPEG image file.
This lesson teaches you the basics of loading, displaying, and saving images.
The are two main classes that you must learn about to work with images:
  • The java.awt.Image class is the superclass that represents graphical images as rectangular arrays of pixels.
  • The java.awt.image.BufferedImage class, which extends the Image class to allow the application to operate directly with image data (for example, retrieving or setting up the pixel color). Applications can directly construct instances of this class.
The BufferedImage class is a cornerstone of the Java 2D immediate-mode imaging API. It manages the image in memory and provides methods for storing, interpreting, and obtaining pixel data. Since BufferedImage is a subclass of Image it can be rendered by the Graphics and Graphics2D methods that accept an Image parameter.
BufferedImage is essentially an Image with an accessible data buffer. It is therefore more efficient to work directly with BufferedImage. A BufferedImage has aColorModel and a Raster of image data. The ColorModel provides a color interpretation of the image's pixel data.
The Raster performs the following functions:
  • Represents the rectangular coordinates of the image
  • Maintains image data in memory
  • Provides a mechanism for creating multiple subimages from a single image data buffer
  • Provides methods for accessing specific pixels within the image
The basic operations with images are represented in the following sections:

Reading/Loading an image

This section explains how to load an image from an external image format into a Java application using the Image I/O API

Drawing an image

This section teaches how to display images using the drawImage method of the Graphics and Graphics2D classes.

Creating and drawing To an image

This section describes how to create an image and how to use the image itself as a drawing surface.

Writing/saving an image

This section explains how to save created images in an appropriate format.

ImageProcessing: Mở đầu với Java Images

In the Java 2D™ API an image is typically a rectangular two-dimensional array of pixels, where each pixel represents the color at that position of the image and where the dimensions represent the horizontal extent (width) and vertical extent (height) of the image as it is displayed.
There are bitmap and vector images. Bitmap images (also known as raster images) are made up of pixels in a grid.  Vector images are made up of many individual, scalable objects such as points, lines, curves or polygons. These objects are defined by mathematical equations rather than pixels.

Friday, April 22, 2011

Getting Started With the NetBeans IDE Tutorial

By Dana Nourie, May 22, 2005, Updated July 2008
Content
Using an Integrated Development Environment (IDE) for developing applications saves you time by managing windows, settings, and data. In addition, an IDE can store repetitive tasks through macros and abbreviations. Drag-and-drop features make creating graphical user interface (GUI) components or accessing databases easy, and highlighted code and debugging features alert you to errors in your code.
The NetBeans IDE is open source and is written in the Java programming language. It provides the services common to creating desktop applications -- such as window and menu management, settings storage -- and is also the first IDE to fully support JDK 6.0 features. The NetBeans platform and IDE are free for commercial and noncommercial use, and they are supported by Sun Microsystems.

Wednesday, April 20, 2011

Building a Java Desktop Database Application

This tutorial shows how to create a desktop Java application through which you can access and update a database. The tutorial takes advantage of support in NetBeans IDE for the following technologies:
  • The Java Persistence API (JPA), which helps you use Java code to interact with databases.
  • Beans Binding (JSR-295), which provides a way for different JavaBeans components to have property values that are synchronized with each other. For example, you can use beans binding to keep the values of cells in a JTable visual component in synch with the values of fields in an entity class. (In turn, the entity class represents the database table.)
  • The Swing Application Framework (JSR-296), which provides some useful building blocks for quickly creating desktop applications.
We will create a database CRUD (create, read, update, delete) application with a custom component used for visualizing the data (car design preview).
This tutorial is largely based on a screencast that was based on a development build of a previous version of the IDE. Some of the user interface has changed since that demo was made, so you might notice some differences between this tutorial and the demo. You can view the demo (about 9 minutes) now or download a zip of the demo.

Using Hibernate in a Java Swing Application


In this tutorial, you use the NetBeans IDE to create and deploy a Java Swing application that displays data from a database. The application uses the Hibernate framework as the persistence layer to retrieve POJOs (plain old Java objects) from a relational database.
Hibernate is framework that provides tools for object relational mapping (ORM). The tutorial demonstrates the support for the Hibernate framework included in the IDE and how to use wizards to create the necessary Hibernate files. After creating the Java objects and configuring the application to use Hibernate, you create a GUI interface for searching and displaying the data.
The application that you build in this tutorial is a companion administration application for the DVD Store web application. This tutorial covers how to create an application that allows you to query an actor's profile based on the match with first name or last name. If you wish you can extend the application to query film details and to add/update/delete items. This tutorial uses MySQL and the Sakila database, but you can use any supported database server with Hibernate applications. The Sakila database is a sample database that you can download from the MySQL site. Information for setting up the Sakila DB is provided in the following sections.

Tuesday, February 8, 2011

Tìm hiểu callback functions trong Java?

1-http://en.wikipedia.org/wiki/Callback_(computer_programming)
In computer programming, a callback is a reference to executable code, or a piece of executable code, that is passed as an argument to other code. This allows a lower-level software layer to call a subroutine (or function) defined in a higher-level layer.

http://www.xyzws.com/Javafaq/how-to-implement-callback-functions-in-java/157
How to implement callback functions in Java?
The callback function is excutable code that is called through a function pointer. You pass a callback function pointer as an argument to other code, or register callback function pointer in somewhere. When something happens, the callback function is invoked.
C/C++ allow function pointers as arguments to other functions but there are no pointers in Java. In Java, only objects and primitive data types can be passed to methods of a class. Java's support of interfaces provides a mechanism by which we can get the equivalent of callbacks. You should declare an interface which declares the function you want to pass.
The collections.sort(List list, Comparator c) is an example of implementing callback function in Java. The c is an instance of a class which implements compare(e1, e2)method in the Comparator interface. It sorts the specified list according to the order induced by the specified comparator. All elements in the list must be mutually comparable using the specified comparator.

Sunday, January 23, 2011

How to Write a Tree Expansion Listener, Tree-Will-Expand Listener

1. How to Write a Tree Expansion Listener

Sometimes when using a tree, you might need to react when a branch becomes expanded or collapsed. For example, you might need to load or save data.
Two kinds of listeners report expansion and collapse occurrences: tree expansion listeners and tree-will-expand listeners. This page discusses tree expansionlisteners. See How to Write a Tree-Will-Expand Listener for a description of Tree-Will-Expand listeners.
A tree expansion listener detects when an expansion or collapse has already occured. In general, you should implement a tree expansion listener unless you need to prevent an expansion or collapse from ocurring .
This example demonstrates a simple tree expansion listener. The text area at the bottom of the window displays a message every time a tree expansion event occurs. It's a straightforward, simple demo. To see a more interesting version that can veto expansions, see How to Write a Tree-Will-Expand Listener.

How to Use Trees


With the JTree class, you can display hierarchical data. A JTree object does not actually contain your data; it simply provides a view of the data. Like any non-trivial Swing component, the tree gets data by querying its data model. Here is a picture of a tree:
As the preceding figure shows, JTree displays its data vertically. Each row displayed by the tree contains exactly one item of data, which is called a node. Every tree has a root node from which all nodes descend. By default, the tree displays the root node, but you can decree otherwise. A node can either have children or not. We refer to nodes that can have children — whether or not they currently have children — as branch nodes. Nodes that can not have children are leaf nodes.


Saturday, January 22, 2011

JScrollPane Demo

A JScrollPane provides a scrollable view of a component. When screen real estate is limited, use a scroll pane to display a component that is large or one whose size can change dynamically. Here is a snapshot of an application that uses a customized scroll pane to view a large photograph:
The scroll pane also has two scroll bars, a row header, a column header, and four corners, three of which have been customized.

Popular Posts

Blog Archive