Wednesday, July 8, 2020

Java Agents

Java Agents, Oracle Java Tutorial and Material, Oracle Java Exam Prep, Oracle Java Certification

1. Introduction


We are going to talk about Java agents, a real black magic for regular Java developers out there. Java agents are able to “intrude” into the execution of Java applications running on the JVM at runtime by performing the direct modifications of the bytecode. Java agents are extremely as powerful as dangerous: they can do mostly everything however if something goes wrong, they can easily crash the JVM.

The goal of this part is to demystify Java agents by explaining how they work, how to run them and showing off some simple examples where Java agents come as a clear advantage.

2. Java Agent Basics


In its essence, a Java agent is a regular Java class which follows a set of strict conventions. The agent class must implement a public static void premain(String agentArgs, Instrumentation inst) method which becomes an agent entry point (similar to the main method for regular Java applications).

Once the Java Virtual Machine (JVM) has initialized, each such premain(String agentArgs, Instrumentation inst) method of every agent will be called in the order the agents were specified on JVM start. When this initialization step is done, the real Java application main method will be called.

However, if the class does not implement public static void premain(String agentArgs, Instrumentation inst) method, the JVM will try to look up and invoke another, overloaded version, public static void premain(String agentArgs). Please notice that each premain method must return in order for the startup phase to proceed.

Last but not least, the Java agent class may also have a public static void agentmain(String agentArgs, Instrumentation inst) or public static void agentmain(String agentArgs) methods which are used when the agent is started after JVM startup.

It looks simple on the first glance but there is one more thing which Java agent implementation should provide as part of its packaging: manifest. Manifest files, usually located in the META-INF folder and named MANIFEST.MF, contain a various metadata related to package distribution.

We have not talked about manifests along this tutorial because most of the time they are not required, however this is not the case with Java agents. The following attributes are defined for Java agents who are packaged as a Java archive (or simply JAR) files:

Manifest Attribute Description 
Premain-Class   When an agent is specified at JVM launch time this attribute defines the Java agent class: the class containing the premain method. When an agent is specified at JVM launch time this attribute is required. If the attribute is not present the JVM will abort.
Agent-Class   If an implementation supports a mechanism to start Java agents sometime after the JVM has started then this attribute specifies the agent class: the class containing the agentmain method. This attribute is required and the agent will not be started if this attribute is not present. 
Boot-Class-Path   A list of paths to be searched by the bootstrap class loader. Paths represent directories or libraries. 
Can-Redefine-Classes   A value of true or false, case-insensitive and defines if the ability to redefine classes needed by this agent. This attribute is optional, the default is false. 
Can-Retransform-Classes   A value of true or false, case-insensitive and defines if the ability to retransform classes needed by this agent. This attribute is optional, the default is false. 
Can-Set-Native-Method-Prefix   A value of true or false, case-insensitive and defines if the ability to set native method prefix needed by this agent. This attribute is optional, the default is false. 

3. Java Agent and Instrumentation


The instrumentation capabilities of Java agents are truly unlimited. Most noticeable ones include but are not limited to:

◉ Ability to redefine classes at run-time. The redefinition may change method bodies, the constant pool and attributes. The redefinition must not add, remove or rename fields or methods, change the signatures of methods, or change inheritance.

◉ Ability to retransform classes at run-time. The retransformation may change method bodies, the constant pool and attributes. The retransformation must not add, remove or rename fields or methods, change the signatures of methods, or change inheritance.

◉ Ability to modify the failure handling of native method resolution by allowing retry with a prefix applied to the name.

Please notice that retransformed or redefined class bytecode is not checked, verified and installed just after the transformations or redefinitions have been applied. If the resulting bytecode is erroneous or not correct, the exception will be thrown and that may crash JVM completely.

4. Writing Your First Java Agent


In this section we are going to write a simple Java agent by implementing our own class transformer. With that being said, the only disadvantage working with Java agents is that in order to accomplish any more or less useful transformation, direct bytecode manipulation skills are required. And, unfortunately, theJava standard library does not provide any API (at least, documented ones) to make those bytecode manipulations possible.

To fill this gap, creative Java community came up with a several excellent and at this moment very mature libraries, such as Javassist and ASM, just to name a few. Of those two, Javassist is much simpler to use and that is why it became the one we are going to employ as a bytecode manipulation solution. So far this is a first time we were not able to find the appropriate API in Java standard library and had no choice other than to use the one provided by the community.

The example we are going to work on is rather simple but it is taken from real-world use case. Let us say we would like to capture URL of every HTTP connection opened by the Java applications. There are many ways to do that by directly modifying the Java source code but let us assume that the source code is not available due to license policies or whatnot. The typical example of the class which opens the HTTP connection may look like that:

public class SampleClass {
    public static void main( String[] args ) throws IOException {
        fetch("http://www.google.com");
        fetch("http://www.yahoo.com");
    }
 
    private static void fetch(final String address) 
            throws MalformedURLException, IOException {
 
        final URL url = new URL(address);                
        final URLConnection connection = url.openConnection();
         
        try( final BufferedReader in = new BufferedReader(
                new InputStreamReader( connection.getInputStream() ) ) ) {
             
            String inputLine = null;
            final StringBuffer sb = new StringBuffer();
            while ( ( inputLine = in.readLine() ) != null) {
                sb.append(inputLine);
            }       
             
            System.out.println("Content size: " + sb.length());
        }
    }
}

Java agents fit very well into solving such kind of challenges. We just need to define the transformer which will slightly modify sun.net.www.protocol.http.HttpURLConnection constructors by injecting the code to produce output to the console. Sounds scary but with ClassFileTransformer and Javassist it is very simple. Let us take a look on such transformer implementation:

public class SimpleClassTransformer implements ClassFileTransformer {
  @Override
  public byte[] transform( 
      final ClassLoader loader, 
      final String className,
      final Class<?> classBeingRedefined, 
      final ProtectionDomain protectionDomain,
      final byte[] classfileBuffer ) throws IllegalClassFormatException {
         
    if (className.endsWith("sun/net/www/protocol/http/HttpURLConnection")) {
      try {
        final ClassPool classPool = ClassPool.getDefault();
        final CtClass clazz = 
          classPool.get("sun.net.www.protocol.http.HttpURLConnection");
                 
        for (final CtConstructor constructor: clazz.getConstructors()) {
          constructor.insertAfter("System.out.println(this.getURL());");
        }
     
        byte[] byteCode = clazz.toBytecode();
        clazz.detach();
               
        return byteCode;
      } catch (final NotFoundException | CannotCompileException | IOException ex) {
        ex.printStackTrace();
      }
    }
         
    return null;
  }
}

The ClassPool and all CtXxx classes (CtClass, CtConstructor) came from Javassist library. The transformation we have done is quite naïve but it is here for demonstrational purposes. Firstly, because we were interested in HTTP communications only, the sun.net.www.protocol.http.HttpURLConnection is the class from standard Java library being responsible for that.

Please notice that instead of ‘.’ separator, the className has the ‘/’ one. Secondly, we looked for HttpURLConnection class and modified all its constructors by injecting the System.out.println(this.getURL()); statement at the end. And lastly, we returned the new bytecode of the transformed version of the class so it is going to be used by JVM instead of original one.

With that, the role of Java agent premain method would be just to add the instance of SimpleClassTransformer class to the instrumentation context:

public class SimpleAgent {
    public static void premain(String agentArgs, Instrumentation inst) {
        final SimpleClassTransformer transformer = new SimpleClassTransformer();
        inst.addTransformer(transformer);
    }
}

That’s it. It looks quite easy and somewhat frightening at the same time. To finish up with Java agent, we have to supply the proper MANIFEST.MF so the JVM will be able to pick the right class.

Manifest-Version: 1.0
Premain-Class: com.oraclejavacertified.advanced.agent.SimpleAgent

With that, out first Java agents is ready for a real battle. In the next section of the tutorial we are going to cover one of the ways to run Java agent along with your Java applications.

5. Running Java Agents


When running from the command line, the Java agent could be passed to JVM instance using -javaagent argument which has following semantic:

-javaagent:<path-to-jar>[=options]

Where <path-to-jar> is the path to locate Java agent JAR archive, and options holds additional options which could be passed to the Java agent, more precisely through agentArgs argument. For example, the command line for running our Java agent from the section Writing Your First Java Agent (using Java 7 version of it) will look like that (assuming that the agent JAR file is located in the current folder):

java -javaagent:advanced-java-part-15-java7.agents-0.0.1-SNAPSHOT.jar

When running the SampleClass class along with the advanced-java-part-15-java7.agents-0.0.1-SNAPSHOT.jar Java agent, the application is going to print on the console all the URLs (Google and Yahoo! ) which were attempted to be accessed using HTTP protocol (followed by the content size of the Google and Yahoo! search home web pages respectively):

http://www.google.com
Content size: 20349
http://www.yahoo.com
Content size: 1387

Running the same SampleClass class without Java agent specified is going to output on the console only content size, no URLs (please notice the content size may vary):

Content size: 20349
Content size: 1387

JVM makes it simple to run Java agents. However, please be warned, any mistakes or inaccurate bytecode generation may crash JVM, possibly losing important data your applications may hold at this moment.

Monday, July 6, 2020

Java - Polymorphism

Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object.

Java - Polymorphism, Oracle Java Tutorial and Material, Oracle Java Exam Prep, Oracle Java Learn

Any Java object that can pass more than one IS-A test is considered to be polymorphic. In Java, all Java objects are polymorphic since any object will pass the IS-A test for their own type and for the class Object.

It is important to know that the only possible way to access an object is through a reference variable. A reference variable can be of only one type. Once declared, the type of a reference variable cannot be changed.

The reference variable can be reassigned to other objects provided that it is not declared final. The type of the reference variable would determine the methods that it can invoke on the object.

A reference variable can refer to any object of its declared type or any subtype of its declared type. A reference variable can be declared as a class or interface type.

Example

Let us look at an example.

public interface Vegetarian{}
public class Animal{}
public class Deer extends Animal implements Vegetarian{}

Now, the Deer class is considered to be polymorphic since this has multiple inheritance. Following are true for the above examples −

◉ A Deer IS-A Animal
◉ A Deer IS-A Vegetarian
◉ A Deer IS-A Deer
◉ A Deer IS-A Object

When we apply the reference variable facts to a Deer object reference, the following declarations are legal −

Example

Deer d = new Deer();
Animal a = d;
Vegetarian v = d;
Object o = d;

All the reference variables d, a, v, o refer to the same Deer object in the heap.

Virtual Methods


In this section, I will show you how the behavior of overridden methods in Java allows you to take advantage of polymorphism when designing your classes.

We already have discussed method overriding, where a child class can override a method in its parent. An overridden method is essentially hidden in the parent class, and is not invoked unless the child class uses the super keyword within the overriding method.

Example

/* File name : Employee.java */
public class Employee {
   private String name;
   private String address;
   private int number;

   public Employee(String name, String address, int number) {
      System.out.println("Constructing an Employee");
      this.name = name;
      this.address = address;
      this.number = number;
   }

   public void mailCheck() {
      System.out.println("Mailing a check to " + this.name + " " + this.address);
   }

   public String toString() {
      return name + " " + address + " " + number;
   }

   public String getName() {
      return name;
   }

   public String getAddress() {
      return address;
   }

   public void setAddress(String newAddress) {
      address = newAddress;
   }

   public int getNumber() {
      return number;
   }
}

Now suppose we extend Employee class as follows −

/* File name : Salary.java */
public class Salary extends Employee {
   private double salary; // Annual salary
 
   public Salary(String name, String address, int number, double salary) {
      super(name, address, number);
      setSalary(salary);
   }
 
   public void mailCheck() {
      System.out.println("Within mailCheck of Salary class ");
      System.out.println("Mailing check to " + getName()
      + " with salary " + salary);
   }
 
   public double getSalary() {
      return salary;
   }
 
   public void setSalary(double newSalary) {
      if(newSalary >= 0.0) {
         salary = newSalary;
      }
   }
 
   public double computePay() {
      System.out.println("Computing salary pay for " + getName());
      return salary/52;
   }
}

Now, you study the following program carefully and try to determine its output −

/* File name : VirtualDemo.java */
public class VirtualDemo {

   public static void main(String [] args) {
      Salary s = new Salary("Mohd Mohtashim", "Ambehta, UP", 3, 3600.00);
      Employee e = new Salary("John Adams", "Boston, MA", 2, 2400.00);
      System.out.println("Call mailCheck using Salary reference --"); 
      s.mailCheck();
      System.out.println("\n Call mailCheck using Employee reference--");
      e.mailCheck();
   }
}

This will produce the following result −

Output

Constructing an Employee
Constructing an Employee

Call mailCheck using Salary reference --
Within mailCheck of Salary class
Mailing check to Mohd Mohtashim with salary 3600.0

Call mailCheck using Employee reference--
Within mailCheck of Salary class
Mailing check to John Adams with salary 2400.0

Here, we instantiate two Salary objects. One using a Salary reference s, and the other using an Employee reference e.

While invoking s.mailCheck(), the compiler sees mailCheck() in the Salary class at compile time, and the JVM invokes mailCheck() in the Salary class at run time.

mailCheck() on e is quite different because e is an Employee reference. When the compiler sees e.mailCheck(), the compiler sees the mailCheck() method in the Employee class.

Here, at compile time, the compiler used mailCheck() in Employee to validate this statement. At run time, however, the JVM invokes mailCheck() in the Salary class.

This behavior is referred to as virtual method invocation, and these methods are referred to as virtual methods. An overridden method is invoked at run time, no matter what data type the reference is that was used in the source code at compile time.

Friday, July 3, 2020

Inheritance in Java

Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a parent object. It is an important part of OOPs (Object Oriented programming system).

The idea behind inheritance in Java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of the parent class. Moreover, you can add new methods and fields in your current class also.

Inheritance represents the IS-A relationship which is also known as a parent-child relationship.

Why use inheritance in java

For Method Overriding (so runtime polymorphism can be achieved).
For Code Reusability.

Terms used in Inheritance

◉ Class: A class is a group of objects which have common properties. It is a template or blueprint from which objects are created.

◉ Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a derived class, extended class, or child class.

◉ Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It is also called a base class or a parent class.

◉ Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the fields and methods of the existing class when you create a new class. You can use the same fields and methods already defined in the previous class.

The syntax of Java Inheritance

class Subclass-name extends Superclass-name 

   //methods and fields 


The extends keyword indicates that you are making a new class that derives from an existing class. The meaning of "extends" is to increase the functionality.

In the terminology of Java, a class which is inherited is called a parent or superclass, and the new class is called child or subclass.

Java Inheritance Example


Java Inheritance, Oracle Java Tutorial and Material, Java Exam Prep, Java Certification

As displayed in the above figure, Programmer is the subclass and Employee is the superclass. The relationship between the two classes is Programmer IS-A Employee. It means that Programmer is a type of Employee.

class Employee{  
 float salary=40000;  
}  
class Programmer extends Employee{  
 int bonus=10000;  
 public static void main(String args[]){  
   Programmer p=new Programmer();  
   System.out.println("Programmer salary is:"+p.salary);  
   System.out.println("Bonus of Programmer is:"+p.bonus);  
}  
}  

Programmer salary is:40000.0
Bonus of programmer is:10000

In the above example, Programmer object can access the field of own class as well as of Employee class i.e. code reusability.

Types of inheritance in java


On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical.

In java programming, multiple and hybrid inheritance is supported through interface only. We will learn about interfaces later.

Java Inheritance, Oracle Java Tutorial and Material, Java Exam Prep, Java Certification

Note: Multiple inheritance is not supported in Java through class.

When one class inherits multiple classes, it is known as multiple inheritance. For Example:

Java Inheritance, Oracle Java Tutorial and Material, Java Exam Prep, Java Certification

Single Inheritance Example


When a class inherits another class, it is known as a single inheritance. In the example given below, Dog class inherits the Animal class, so there is the single inheritance.

File: TestInheritance.java

class Animal{  
void eat(){System.out.println("eating...");}  
}  
class Dog extends Animal{  
void bark(){System.out.println("barking...");}  
}  
class TestInheritance{  
public static void main(String args[]){  
Dog d=new Dog();  
d.bark();  
d.eat();  
}}  

Output:

barking...
eating...

Multilevel Inheritance Example


When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in the example given below, BabyDog class inherits the Dog class which again inherits the Animal class, so there is a multilevel inheritance.

File: TestInheritance2.java

class Animal{  
void eat(){System.out.println("eating...");}  
}  
class Dog extends Animal{  
void bark(){System.out.println("barking...");}  
}  
class BabyDog extends Dog{  
void weep(){System.out.println("weeping...");}  
}  
class TestInheritance2{  
public static void main(String args[]){  
BabyDog d=new BabyDog();  
d.weep();  
d.bark();  
d.eat();  
}}  

Output:

weeping...
barking...
eating...

Hierarchical Inheritance Example


When two or more classes inherits a single class, it is known as hierarchical inheritance. In the example given below, Dog and Cat classes inherits the Animal class, so there is hierarchical inheritance.

File: TestInheritance3.java

class Animal{  
void eat(){System.out.println("eating...");}  
}  
class Dog extends Animal{  
void bark(){System.out.println("barking...");}  
}  
class Cat extends Animal{  
void meow(){System.out.println("meowing...");}  
}  
class TestInheritance3{  
public static void main(String args[]){  
Cat c=new Cat();  
c.meow();  
c.eat();  
//c.bark();//C.T.Error  
}}  

Output:

meowing...
eating...

Q) Why multiple inheritance is not supported in java?


To reduce the complexity and simplify the language, multiple inheritance is not supported in java.

Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes. If A and B classes have the same method and you call it from child class object, there will be ambiguity to call the method of A or B class.

Since compile-time errors are better than runtime errors, Java renders compile-time error if you inherit 2 classes. So whether you have same method or different, there will be compile time error.

class A{  
void msg(){System.out.println("Hello");}  
}  
class B{  
void msg(){System.out.println("Welcome");}  
}  
class C extends A,B{//suppose if it were  
   
 public static void main(String args[]){  
   C obj=new C();  
   obj.msg();//Now which msg() method would be invoked?  
}  
}  

Compile Time Error

Wednesday, July 1, 2020

Reverse A String Using Recursion

Oracle Java Tutorial and Material, Java Exam Prep, Java Certification, Java Prep

1. Introduction


In this article, You’re going to learn how to reverse a string using recursion approach. The first program is to reverse a string and the second program will read the input from the user.

2. What Is Recursion


Recursion means in computer science is that a method calling the same function with different input.

The recursive method must have at least one argument.

This approach solves many complex programs easily but you have to be very careful otherwise will create StackOverflow or outofmemoryerror.

3. Example Program to Reverse String using Recursion


To understand this program you should know two String class methods and those are charAt() and substring() methods.

package com.javaprogramto.w3schools.programs.string;

public class StringReverseRecursion {

    public static void main(String[] args) {

        String s1 = "Welcome to the javaprogramto.com";

        String reversedS1 = reverseString(s1);
        System.out.println("String s1 before reversing : "+s1);
        System.out.println("Reversed String s1 : "+reversedS1);

        String s2 = "Another String s2";

        String reversedS2 = reverseString(s2);
        System.out.println("String s2 before reversing : "+s2);
        System.out.println("Reversed String s2 : "+reversedS2);
    }


    private static String reverseString(String sentense)
    {
        if (sentense.isEmpty())
            return sentense;

        //Calling method Recursively
        return reverseString(sentense.substring(1)) + sentense.charAt(0);
    }
}

Output:

String s1 before reversing : Welcome to the javaprogramto.com
Reversed String s1 : moc.otmargorpavaj eht ot emocleW
String s2 before reversing : Another String s2
Reversed String s2 : 2s gnirtS rehtonA

4. Another Example to reverse String reading from the user


In this program, the User has to enter the string to be reversed. Scanner class nextLine() method is used to read the input string from the user keyboard and pass the string value to the recursive method reverseString().

package com.javaprogramto.w3schools.programs.string;

import java.util.Scanner;

public class StringReverseRecursionFromUser {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter String One");
        String s1 = scanner.nextLine();

        String reversedS1 = reverseString(s1);
        System.out.println("String s1 before reversing : "+s1);
        System.out.println("Reversed String s1 : "+reversedS1);

        System.out.println("Enter String Two");
        String s2 = scanner.nextLine();

        String reversedS2 = reverseString(s2);
        System.out.println("String s2 before reversing : "+s2);
        System.out.println("Reversed String s2 : "+reversedS2);
    }


    private static String reverseString(String sentense)
    {
        if (sentense.isEmpty())
            return sentense;

        //Calling method Recursively
        return reverseString(sentense.substring(1)) + sentense.charAt(0);
    }
}

Output:

Enter String One
Reading from user
String s1 before reversing : Reading from user
Reversed String s1 : resu morf gnidaeR
Enter String Two
String entered by user
String s2 before reversing : String entered by user
Reversed String s2 : resu yb deretne gnirtS

Monday, June 29, 2020

Java - Constructors

Java - Constructors, Oracle Java Tutorial and Materials, Oracle Java Exam Prep, Oracle Java Certifications

A constructor initializes an object when it is created. It has the same name as its class and is syntactically similar to a method. However, constructors have no explicit return type.

Typically, you will use a constructor to give initial values to the instance variables defined by the class, or to perform any other start-up procedures required to create a fully formed object.

All classes have constructors, whether you define one or not, because Java automatically provides a default constructor that initializes all member variables to zero. However, once you define your own constructor, the default constructor is no longer used.

Syntax


Following is the syntax of a constructor −

class ClassName {
   ClassName() {
   }
}

Java allows two types of constructors namely −

- No argument Constructors
- Parameterized Constructors

No argument Constructors


As the name specifies the no argument constructors of Java does not accept any parameters instead, using these constructors the instance variables of a method will be initialized with fixed values for all objects.

Example


Public class MyClass {
   Int num;
   MyClass() {
      num = 100;
   }
}

You would call constructor to initialize objects as follows

public class ConsDemo {
   public static void main(String args[]) {
      MyClass t1 = new MyClass();
      MyClass t2 = new MyClass();
      System.out.println(t1.num + " " + t2.num);
   }
}

This would produce the following result

100 100

Parameterized Constructors


Most often, you will need a constructor that accepts one or more parameters. Parameters are added to a constructor in the same way that they are added to a method, just declare them inside the parentheses after the constructor's name.

Example


Here is a simple example that uses a constructor −

// A simple constructor.
class MyClass {
   int x;
 
   // Following is the constructor
   MyClass(int i ) {
      x = i;
   }
}

You would call constructor to initialize objects as follows −

public class ConsDemo {
   public static void main(String args[]) {
      MyClass t1 = new MyClass( 10 );
      MyClass t2 = new MyClass( 20 );
      System.out.println(t1.x + " " + t2.x);
   }
}

This would produce the following result −

10 20

Saturday, June 27, 2020

JavaFX - Transformations

Transformation means changing some graphics into something else by applying rules. We can have various types of transformations such as Translation, Scaling Up or Down, Rotation, Shearing, etc.

Using JavaFX, you can apply transformations on nodes such as rotation, scaling and translation. All these transformations are represented by various classes and these belong to the package javafx.scene.transform.

S.No Transformation & Description 
1 Rotation

In rotation, we rotate the object at a particular angle θ (theta) from its origin. 
Scaling

To change the size of an object, scaling transformation is used. 
Translation

Moves an object to a different position on the screen. 
Shearing

A transformation that slants the shape of an object is called the Shear Transformation. 

Multiple Transformations


You can also apply multiple transformations on nodes in JavaFX. The following program is an example which performs Rotation, Scaling and Translation transformations on a rectangle simultaneously.

Save this code in a file with the name −

MultipleTransformationsExample.java.

import javafx.application.Application; 
import javafx.scene.Group; 
import javafx.scene.Scene; 
import javafx.scene.paint.Color; 
import javafx.scene.shape.Rectangle; 
import javafx.scene.transform.Rotate; 
import javafx.scene.transform.Scale; 
import javafx.scene.transform.Translate; 
import javafx.stage.Stage; 
         
public class MultipleTransformationsExample extends Application { 
   @Override 
   public void start(Stage stage) { 
      //Drawing a Rectangle
      Rectangle rectangle = new Rectangle(50, 50, 100, 75); 
      
      //Setting the color of the rectangle 
      rectangle.setFill(Color.BURLYWOOD); 
      
      //Setting the stroke color of the rectangle 
      rectangle.setStroke(Color.BLACK); 
       
      //creating the rotation transformation 
      Rotate rotate = new Rotate(); 
      
      //Setting the angle for the rotation 
      rotate.setAngle(20); 
      
      //Setting pivot points for the rotation 
      rotate.setPivotX(150); 
      rotate.setPivotY(225); 
       
      //Creating the scale transformation 
      Scale scale = new Scale(); 
      
      //Setting the dimensions for the transformation 
      scale.setX(1.5); 
      scale.setY(1.5); 
      
      //Setting the pivot point for the transformation 
      scale.setPivotX(300); 
      scale.setPivotY(135); 
       
      //Creating the translation transformation 
      Translate translate = new Translate();       
      
      //Setting the X,Y,Z coordinates to apply the translation 
      translate.setX(250); 
      translate.setY(0); 
      translate.setZ(0); 
       
      //Adding all the transformations to the rectangle 
      rectangle.getTransforms().addAll(rotate, scale, translate); 
        
      //Creating a Group object  
      Group root = new Group(rectangle); 
      
      //Creating a scene object 
      Scene scene = new Scene(root, 600, 300);  
      
      //Setting title to the Stage 
      stage.setTitle("Multiple transformations"); 
         
      //Adding scene to the stage 
      stage.setScene(scene); 
         
      //Displaying the contents of the stage 
      stage.show(); 
   }      
   public static void main(String args[]){ 
      launch(args); 
   } 
}

Compile and execute the saved java file from the command prompt using the following commands.

javac MultipleTransformationsExample.java 
java MultipleTransformationsExample

On executing, the above program generates a JavaFX window as shown below.

JavaFX Transformations, Oracle Java Tutorial and Material, Java Exam Prep, Java Certification, Oracle Java Study Material

Transformations on 3D Objects


You can also apply transformations on 3D objects. Following is an example which rotates and translates a 3-Dimensional box.

Save this code in a file with the name RotationExample3D.java.

import javafx.application.Application; 
import javafx.scene.Group; 
import javafx.scene.Scene; 
import javafx.scene.shape.Box; 
import javafx.scene.transform.Rotate; 
import javafx.scene.transform.Translate; 
import javafx.stage.Stage; 
         
public class RotationExample3D extends Application { 
   @Override 
   public void start(Stage stage) { 
      //Drawing a Box 
      Box box = new Box();  
      
      //Setting the properties of the Box 
      box.setWidth(150.0); 
      box.setHeight(150.0);   
      box.setDepth(150.0);       
       
      //Creating the translation transformation 
      Translate translate = new Translate();       
      translate.setX(400); 
      translate.setY(150); 
      translate.setZ(25);  
       
      Rotate rxBox = new Rotate(0, 0, 0, 0, Rotate.X_AXIS); 
      Rotate ryBox = new Rotate(0, 0, 0, 0, Rotate.Y_AXIS); 
      Rotate rzBox = new Rotate(0, 0, 0, 0, Rotate.Z_AXIS); 
      rxBox.setAngle(30); 
      ryBox.setAngle(50); 
      rzBox.setAngle(30); 
      box.getTransforms().addAll(translate,rxBox, ryBox, rzBox); 
        
      //Creating a Group object  
      Group root = new Group(box); 
         
      //Creating a scene object 
      Scene scene = new Scene(root, 600, 300);  
      
      //Setting title to the Stage 
      stage.setTitle("Drawing a cylinder"); 
         
      //Adding scene to the stage 
      stage.setScene(scene); 
         
      //Displaying the contents of the stage 
      stage.show(); 
   }      
   public static void main(String args[]){ 
      launch(args); 
   } 
}

Compile and execute the saved java file from the command prompt using the following commands.

javac RotationExample3D.java 
java RotationExample3D 

On executing, the above program generates a JavaFX window as shown below.

JavaFX Transformations, Oracle Java Tutorial and Material, Java Exam Prep, Java Certification, Oracle Java Study Material