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

Friday, June 26, 2020

Java Program To Insertion Sort

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

Java Program To Insertion Sort With Example. Shown the example simulation along with the time complexity.

1. Introduction


Insertion sort is a simple sorting algorithm that builds the final sorted array (or list) one item at a time. It is much more efficient than Bubble Sort and less efficient on large lists than more advanced algorithms such as quicksort, heapsort, or merge sort.

We can implement  Insertion sort using iterative and recursive approach. We will do in this post using Iterative approach. It is easy to understand when compared to recursive.

The insertion sorts repeatedly scans the list of items, each time inserting the item in the unordered sequence into its correct position.

2. Insertion sort Algorithm:


Algorithm is prepared based array and array index starts from 0.

Iterate from index i –> 1 to length -1

    Assign key = A[i];

    j = i – 1;

    Loop j >= 0 and A[j] > key

        A[j + 1] = A[j];

        j = j – 1;

    End Loop

    A[j + 1] = key;

End Iterate.

This algorithm works based on cards deck. Pick one card put that card in your hand and pick second card. Then compare second number with first number. If it is greater than first then place second card right side. if less than place second card at left side. Please go through the below example simulation for better understanding.

3. Example Simulation:


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

A graphical example of insertion sort.

4. Java Program To Insertion Sort


package com.adeepdrive.data.structures.sorting;

public class InsertionSortProgram {

 public static void main(String[] args) {

  // input array
  int[] inputArray = { 6, 5, 3, 1, 8, 7, 2, 4 };
  int length = inputArray.length;
  int j = 0;

  System.out.print("Before Sorting: ");
  printArray(inputArray);
  System.out.print("\nValues for each Iteration");

  for (int i = 1; i < length; i++) {
   j = i - 1;
   int key = inputArray[i];
   while (j >= 0 && inputArray[j] > key) {
    inputArray[j + 1] = inputArray[j];
    j = j - 1;
   }
   inputArray[j + 1] = key;
   System.out.println();
   printArray(inputArray);
  }

  System.out.print("\nAfter sorting: ");
  printArray(inputArray);

 }

 private static void printArray(int[] inputArray) {
  for (int value : inputArray) {
   System.out.print(value + " ");
  }
 }

}

Output:

Before Sorting: 6 5 3 1 8 7 2 4

Values for each Iteration

5 6 3 1 8 7 2 4

3 5 6 1 8 7 2 4

1 3 5 6 8 7 2 4

1 3 5 6 8 7 2 4

1 3 5 6 7 8 2 4

1 2 3 5 6 7 8 4

1 2 3 4 5 6 7 8

After sorting: 1 2 3 4 5 6 7 8

Oracle Java Tutorial and Material, Java Exam Prep, Oracle Java Study Material
We are storing current iterating index value in key because if we do swapping value on a condition. In swapping activity, we may loss original value at that index. To avoid loss of data, we store in temporary variable.

In code, We are starting from index 1, ignoring index 0 because index o is already sorted.

i = 1, key = 5

Compare key = 5 with left side values. i.e. 5. condition 6 > 5 –> true. Swap them.

5 6 3 1 8 7 2 4

now i = 2, key = 3

compare key with its left side values and swap them

6 > 3 –> true –> swap –> 5 3 6 1 8 7 2 4

5 > 3 –> true –> swap –> 3 5 6 1 8 7 2 4

now i = 3, key  = 1

compare key(1) with its left side values and sort them.

6 > 1 –> true –> swap –> 3 5 1 6 8 7 2 4

5 > 1 –> true –> swap –> 3 1 5 6 8 7 2 4

3 > 1 –> true –> swap –> 1 3 5 6 8 7 2 4

now i = 4, key = 8

compare key(8) with its left side values and sort them.

6 > 8 –> false –> no swap. that means all left side values are already sorted.

now i = 5, key = 7

compare key(7)  with its left side values and sort them.

8 > 7 –> true –> swap –> 1 3 5 6 7 8 2 4

6 > 7 –> false –> no swap. All left side values are already sorted.

now i = 6, key 2

compare key(2)  with its left side values and sort them.

8 > 2 –> true –> swap –> 1 3 5 6 7 2 8 4

7 > 2 –> true –> swap –> 1 3 5 6 2 7 8 4

6 > 2 –> true –> swap –> 1 3 5 2 6 7 8 4

5 > 2 –> true –> swap –> 1 3 2 5 6 7 8 4

3 > 2 –> true –> swap –> 1 2 3 5 6 7 8 4

1 > 2 –> false –> no swap. that means all left side values are already sorted.

now i = 7, key4

compare key(4)  with its left side values and sort them.

8 > 4 –> true –> swap –>  1 2 3 5 6 7 4 8

7 > 4 –> true –> swap –>  1 2 3 5 6 4 7 8

6 > 4 –> true –> swap –>  1 2 3 5 4 6 7 8

5 > 4 –> true –> swap –>  1 2 3 4 5 6 7 8

3 > 4 –> false –> no swap. that means all left side values are already sorted.

Reached end of array and stops processing.

5. Insertion Sort Time complexity:


Worst case Time Complexity: O(n*n)

when all values are not sorted. E.g.  9 8 7 6 5 4 3 2 1

Best case Time Complexity: O(n)

when 
all are already input is sorted E.g. 1 2 3 4 5 6 7 8 9

Auxiliary Space: O(1)

6. Insertion Sort Advantages:


The main advantages of the insertion sort are

1) its simplicity.

2) It also exhibits a good performance when dealing with a small list.

3) The insertion sort is an in-place sorting algorithm so the space requirement is minimal.

7. Insertion Sort Disadvantages:


The disadvantages of the insertion sort are

1) It does not perform as well as other, better sorting algorithms.

2) With n-squared steps required for every n element to be sorted, the insertion sort does not deal well with a huge list.

3) Therefore, the insertion sort is particularly useful only when sorting a list of few items.

Wednesday, June 24, 2020

JavaFX - Application

We will discuss the structure of a JavaFX application in detail and also learn to create a JavaFX application with an example.

JavaFX Application Structure


In general, a JavaFX application will have three major components namely Stage, Scene and Nodes as shown in the following diagram.

JavaFX Application, Oracle Java Tutorial and Material, Oracle Java Guides, Oracle Java Certification

Stage

A stage (a window) contains all the objects of a JavaFX application. It is represented by Stage class of the package javafx.stage. The primary stage is created by the platform itself. The created stage object is passed as an argument to the start() method of the Application class (explained in the next section).

A stage has two parameters determining its position namely Width and Height. It is divided as Content Area and Decorations (Title Bar and Borders).

There are five types of stages available −

◉ Decorated
◉ Undecorated
◉ Transparent
◉ Unified
◉ Utility

You have to call the show() method to display the contents of a stage.

Scene

A scene represents the physical contents of a JavaFX application. It contains all the contents of a scene graph. The class Scene of the package javafx.scene represents the scene object. At an instance, the scene object is added to only one stage.

You can create a scene by instantiating the Scene Class. You can opt for the size of the scene by passing its dimensions (height and width) along with the root node to its constructor.

Scene Graph and Nodes

A scene graph is a tree-like data structure (hierarchical) representing the contents of a scene. In contrast, a node is a visual/graphical object of a scene graph.

A node may include −

◉ Geometrical (Graphical) objects (2D and 3D) such as − Circle, Rectangle, Polygon, etc.

◉ UI Controls such as − Button, Checkbox, Choice Box, Text Area, etc.

◉ Containers (Layout Panes) such as Border Pane, Grid Pane, Flow Pane, etc.

◉ Media elements such as Audio, Video and Image Objects.

The Node Class of the package javafx.scene represents a node in JavaFX, this class is the super class of all the nodes.

As discussed earlier a node is of three types −

◉ Root Node − The first Scene Graph is known as the Root node.

◉ Branch Node/Parent Node − The node with child nodes are known as branch/parent nodes. The abstract class named Parent of the package javafx.scene is the base class of all the parent nodes, and those parent nodes will be of the following types −

     ◉ Group − A group node is a collective node that contains a list of children nodes. Whenever the group node is rendered, all its child nodes are rendered in order. Any transformation, effect state applied on the group will be applied to all the child nodes.

     ◉ Region − It is the base class of all the JavaFX Node based UI Controls, such as Chart, Pane and Control.

     ◉ WebView − This node manages the web engine and displays its contents.

◉ Leaf Node − The node without child nodes is known as the leaf node. For example, Rectangle, Ellipse, Box, ImageView, MediaView are examples of leaf nodes.

It is mandatory to pass the root node to the scene graph. If the Group is passed as root, all the nodes will be clipped to the scene and any alteration in the size of the scene will not affect the layout of the scene.

Creating a JavaFX Application


To create a JavaFX application, you need to instantiate the Application class and implement its abstract method start(). In this method, we will write the code for the JavaFX Application.

Application Class

The Application class of the package javafx.application is the entry point of the application in JavaFX. To create a JavaFX application, you need to inherit this class and implement its abstract method start(). In this method, you need to write the entire code for the JavaFX graphics

In the main method, you have to launch the application using the launch() method. This method internally calls the start() method of the Application class as shown in the following program.

public class JavafxSample extends Application {  
   @Override     
   public void start(Stage primaryStage) throws Exception { 
      /* 
      Code for JavaFX application. 
      (Stage, scene, scene graph) 
      */       
   }         
   public static void main(String args[]){           
      launch(args);      
   } 

Within the start() method, in order to create a typical JavaFX application, you need to follow the steps given below −

◉ Prepare a scene graph with the required nodes.

◉ Prepare a Scene with the required dimensions and add the scene graph (root node of the scene graph) to it.

◉ Prepare a stage and add the scene to the stage and display the contents of the stage.

Preparing the Scene Graph

As per your application, you need to prepare a scene graph with required nodes. Since the root node is the first node, you need to create a root node. As a root node, you can choose from the Group, Region or WebView.

Group − A Group node is represented by the class named Group which belongs to the package javafx.scene, you can create a Group node by instantiating this class as shown below.

Group root = new Group();

The getChildren() method of the Group class gives you an object of the ObservableList class which holds the nodes. We can retrieve this object and add nodes to it as shown below.

//Retrieving the observable list object 
ObservableList list = root.getChildren(); 
       
//Setting the text object as a node  
list.add(NodeObject); 

We can also add Node objects to the group, just by passing them to the Group class and to its constructor at the time of instantiation, as shown below.

Group root = new Group(NodeObject);

Region − It is the Base class of all the JavaFX Node-based UI Controls, such as −

◉ Chart − This class is the base class of all the charts and it belongs to the package javafx.scene.chart.

This class has two sub classes, which are − PieChart and XYChart. These two in turn have subclasses such as AreaChart, BarChart, BubbleChart, etc. used to draw different types of XY-Plane Charts in JavaFX.

You can use these classes to embed charts in your application.

◉ Pane − A Pane is the base class of all the layout panes such as AnchorPane, BorderPane, DialogPane, etc. This class belong to a package that is called as − javafx.scene.layout.

You can use these classes to insert predefined layouts in your application.

◉ Control − It is the base class of the User Interface controls such as Accordion, ButtonBar, ChoiceBox, ComboBoxBase, HTMLEditor, etc. This class belongs to the package javafx.scene.control.

You can use these classes to insert various UI elements in your application.

In a Group, you can instantiate any of the above-mentioned classes and use them as root nodes, as shown in the following program.

//Creating a Stack Pane 
StackPane pane = new StackPane();       
       
//Adding text area to the pane  
ObservableList list = pane.getChildren(); 
list.add(NodeObject);

WebView − This node manages the web engine and displays its contents.

Following is a diagram representing the node class hierarchy of JavaFX.

JavaFX Application, Oracle Java Tutorial and Material, Oracle Java Guides, Oracle Java Certification

Preparing the Scene

A JavaFX scene is represented by the Scene class of the package javafx.scene. You can create a Scene by instantiating this class as shown in the following cod block.

While instantiating, it is mandatory to pass the root object to the constructor of the scene class.

Scene scene = new Scene(root);

You can also pass two parameters of double type representing the height and width of the scene as shown below.

Scene scene = new Scene(root, 600, 300);

Preparing the Stage

This is the container of any JavaFX application and it provides a window for the application. It is represented by the Stage class of the package javafx.stage. An object of this class is passed as a parameter of the start() method of the Application class.

Using this object, you can perform various operations on the stage. Primarily you can perform the following −

◉ Set the title for the stage using the method setTitle().

◉ Attach the scene object to the stage using the setScene() method.

◉ Display the contents of the scene using the show() method as shown below.

//Setting the title to Stage. 
primaryStage.setTitle("Sample application"); 
       
//Setting the scene to Stage 
primaryStage.setScene(scene); 
       
//Displaying the stage 
primaryStage.show();

Lifecycle of JavaFX Application


The JavaFX Application class has three life cycle methods, which are −

◉ start() − The entry point method where the JavaFX graphics code is to be written.

◉ stop() − An empty method which can be overridden, here you can write the logic to stop the application.

◉ init() − An empty method which can be overridden, but you cannot create stage or scene in this method.

In addition to these, it provides a static method named launch() to launch JavaFX application.

Since the launch() method is static, you need to call it from a static context (main generally). Whenever a JavaFX application is launched, the following actions will be carried out (in the same order).

◉ An instance of the application class is created.

◉ Init() method is called.

◉ The start() method is called.

◉ The launcher waits for the application to finish and calls the stop() method.

Terminating the JavaFX Application

When the last window of the application is closed, the JavaFX application is terminated implicitly. You can turn this behavior off by passing the Boolean value “False” to the static method setImplicitExit() (should be called from a static context).

You can terminate a JavaFX application explicitly using the methods Platform.exit() or System.exit(int).

Example 1 – Creating an Empty Window


This section teaches you how to create a JavaFX sample application which displays an empty window. Following are the steps −

Step 1: Creating a Class

Create a Java class and inherit the Application class of the package javafx.application and implement the start() method of this class as follows.

public class JavafxSample extends Application {  
   @Override     
   public void start(Stage primaryStage) throws Exception {      
   }    

Step 2: Creating a Group Object

In the start() method creates a group object by instantiating the class named Group, which belongs to the package javafx.scene, as follows.

Group root = new Group();

Step 3: Creating a Scene Object

Create a Scene by instantiating the class named Scene which belongs to the package javafx.scene. To this class, pass the Group object (root), created in the previous step.

In addition to the root object, you can also pass two double parameters representing height and width of the screen along with the object of the Group class as follows.

Scene scene = new Scene(root,600, 300);

Step 4: Setting the Title of the Stage

You can set the title to the stage using the setTitle() method of the Stage class. The primaryStage is a Stage object which is passed to the start method of the scene class, as a parameter.

Using the primaryStage object, set the title of the scene as Sample Application as shown below.

primaryStage.setTitle("Sample Application");

Step 5: Adding Scene to the Stage

You can add a Scene object to the stage using the method setScene() of the class named Stage. Add the Scene object prepared in the previous steps using this method as shown below.

primaryStage.setScene(scene);

Step 6: Displaying the Contents of the Stage

Display the contents of the scene using the method named show() of the Stage class as follows.

primaryStage.show();

Step 7: Launching the Application

Launch the JavaFX application by calling the static method launch() of the Application class from the main method as follows.

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

Example

The following program generates an empty JavaFX window. Save this code in a file with the name JavafxSample.java

import javafx.application.Application; 
import javafx.scene.Group; 
import javafx.scene.Scene; 
import javafx.scene.paint.Color; 
import javafx.stage.Stage;  

public class JavafxSample extends Application { 
   @Override     
   public void start(Stage primaryStage) throws Exception {            
      //creating a Group object 
      Group group = new Group(); 
       
      //Creating a Scene by passing the group object, height and width   
      Scene scene = new Scene(group ,600, 300); 
      
      //setting color to the scene 
      scene.setFill(Color.BROWN);  
      
      //Setting the title to Stage. 
      primaryStage.setTitle("Sample Application"); 
   
      //Adding the scene to Stage 
      primaryStage.setScene(scene); 
       
      //Displaying the contents of the stage 
      primaryStage.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 JavafxSample.java 
java JavafxSample

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

JavaFX Application, Oracle Java Tutorial and Material, Oracle Java Guides, Oracle Java Certification

Example 2 – Drawing a Straight Line


In the previous example, we have seen how to create an empty stage, now in this example let us try to draw a straight line using the JavaFX library.

Following are the steps −

Step 1: Creating a Class

Create a Java class and inherit the Application class of the package javafx.application and implement the start() method of this class as follows.

public class DrawingLine extends Application {
   @Override     
   public void start(Stage primaryStage) throws Exception {     
   }    

Step 2: Creating a Line

You can create a line in JavaFX by instantiating the class named Line which belongs to a package javafx.scene.shape, instantiate this class as follows.

//Creating a line object         
Line line = new Line();

Step 3: Setting Properties to the Line

Specify the coordinates to draw the line on an X-Y plane by setting the properties startX, startY, endX and endY, using their respective setter methods as shown in the following code block.

line.setStartX(100.0); 
line.setStartY(150.0); 
line.setEndX(500.0); 
line.setEndY(150.0);

Step 4: Creating a Group Object

In the start() method create a group object by instantiating the class named Group, which belongs to the package javafx.scene.

Pass the Line (node) object, created in the previous step, as a parameter to the constructor of the Group class, in order to add it to the group as follows −

Group root = new Group(line);

Step 5: Creating a Scene Object

Create a Scene by instantiating the class named Scene which belongs to the package javafx.scene. To this class, pass the Group object (root) that was created in the previous step.

In addition to the root object, you can also pass two double parameters representing height and width of the screen along with the object of the Group class as follows.

Scene scene = new Scene(group ,600, 300);

Step 6: Setting the Title of the Stage

You can set the title to the stage using the setTitle() method of the Stage class. The primaryStage is a Stage object which is passed to the start method of the scene class, as a parameter.

Using the primaryStage object, set the title of the scene as Sample Application as follows.

primaryStage.setTitle("Sample Application");

Step 7: Adding Scene to the Stage

You can add a Scene object to the stage using the method setScene() of the class named Stage. Add the Scene object prepared in the previous steps using this method as follows.

primaryStage.setScene(scene);

Step 8: Displaying the Contents of the Stage

Display the contents of the scene using the method named show() of the Stage class as follows.

primaryStage.show();

Step 9: Launching the Application

Launch the JavaFX application by calling the static method launch() of the Application class from the main method as follows.

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

Example

The following program shows how to generate a straight line using JavaFX. Save this code in a file with the name JavafxSample.java.

import javafx.application.Application; 
import javafx.scene.Group; 
import javafx.scene.Scene; 
import javafx.scene.shape.Line; 
import javafx.stage.Stage;  

public class DrawingLine extends Application{ 
   @Override 
   public void start(Stage stage) { 
      //Creating a line object 
      Line line = new Line(); 
         
      //Setting the properties to a line 
      line.setStartX(100.0); 
      line.setStartY(150.0); 
      line.setEndX(500.0); 
      line.setEndY(150.0); 
         
      //Creating a Group 
      Group root = new Group(line); 
         
      //Creating a Scene 
      Scene scene = new Scene(root, 600, 300); 
         
      //Setting title to the scene 
      stage.setTitle("Sample application"); 
         
      //Adding the scene to the stage 
      stage.setScene(scene); 
         
      //Displaying the contents of a scene 
      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 DrawingLine.java 
java DrawingLine

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

JavaFX Application, Oracle Java Tutorial and Material, Oracle Java Guides, Oracle Java Certification

Example 3 – Displaying Text


We can also embed text in JavaFX scene. This example shows how to embed text in JavaFX.

Following are the steps −

Step 1: Creating a Class

Create a Java Class and inherit the Application class of the package javafx.application and implement the start() method of this class as follows.

public class DrawingLine extends Application {  
   @Override     
   public void start(Stage primaryStage) throws Exception {     
   } 
}

Step 2: Embedding Text

You can embed text into a JavaFX scene by instantiating the class named Text which belongs to a package javafx.scene.shape, instantiate this class.

You can instantiate this class by passing text to be embedded, in String format Or, you can create text object using the default constructor as shown below.

//Creating a Text object 
Text text = new Text();

Step 3: Setting the Font

You can set font to the text using the setFont() method of the Text class. This method accepts a font object as parameters. Set the font of the given text to 45 as shown below.

//Setting font to the text 
text.setFont(new Font(45)); 

Step 4: Setting the Position of the Text

You can set the position of the text on the X-Y plane by setting the X,Y coordinates using the respective setter methods setX() and setY() as follows.

//setting the position of the text 
text.setX(50); 
text.setY(150); 

Step 5: Setting the text to be added

You can set the text to be added using the setText() method of the Text class. This method accepts a string parameter representing the text to be added.

text.setText("Welcome to OracleJavaCertified");

Step 6: Creating a Group Object

In the start() method, create a group object by instantiating the class named Group, which belongs to the package javafx.scene.

Pass the Text (node) object, created in the previous step, as a parameter to the constructor of the Group class, in order to add it to the group as follows −

Group root = new Group(text)

Step 7: Creating a Scene Object

Create a Scene by instantiating the class named Scene which belongs to the package javafx.scene. To this class, pass the Group object (root), created in the previous step.

In addition to the root object, you can also pass two double parameters representing height and width of the screen along with the object of the Group class as follows.

Scene scene = new Scene(group ,600, 300);

Step 8: Setting the Title of the Stage

You can set the title to the stage using the setTitle() method of the Stage class. The primaryStage is a Stage object which is passed to the start method of the scene class, as a parameter.

Using the primaryStage object, set the title of the scene as Sample Application as shown below.

primaryStage.setTitle("Sample Application");

Step 9: Adding Scene to the Stage

You can add a Scene object to the stage using the method setScene() of the class named Stage. Add the Scene object prepared in the previous steps using this method as follows.

primaryStage.setScene(scene);

Step 10: Displaying the Contents of the Stage

Display the contents of the scene using the method named show() of the Stage class as follows.

primaryStage.show();

Step 11: Launching the Application

Launch the JavaFX application by calling the static method launch() of the Application class from the main method as follows.

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

Example

Following is the program to display text using JavaFX. Save this code in a file with name DisplayingText.java.

import javafx.application.Application; 
import javafx.collections.ObservableList; 
import javafx.scene.Group; 
import javafx.scene.Scene; 
import javafx.stage.Stage; 
import javafx.scene.text.Font; 
import javafx.scene.text.Text; 
         
public class DisplayingText extends Application { 
   @Override 
   public void start(Stage stage) {       
      //Creating a Text object 
      Text text = new Text(); 
       
      //Setting font to the text 
      text.setFont(new Font(45)); 
       
      //setting the position of the text 
      text.setX(50); 
      text.setY(150);          
      
      //Setting the text to be added. 
      text.setText("Welcome to OracleJavaCertified"); 
         
      //Creating a Group object  
      Group root = new Group(); 
       
      //Retrieving the observable list object 
      ObservableList list = root.getChildren(); 
       
      //Setting the text object as a node to the group object 
      list.add(text);       
               
      //Creating a scene object 
      Scene scene = new Scene(root, 600, 300); 
       
      //Setting title to the Stage 
      stage.setTitle("Sample Application"); 
         
      //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 DisplayingText.java 
java DisplayingText

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

Welcome to OracleJavaCertified

Saturday, June 20, 2020

Java - Object and Classes

Java Object and Classes, Oracle Java Study Materials, Oracle Java Exam Prep

Java is an Object-Oriented Language. As a language that has the Object-Oriented feature, Java supports the following fundamental concepts −

◉ Polymorphism
◉ Inheritance
◉ Encapsulation
◉ Abstraction
◉ Classes
◉ Objects
◉ Instance
◉ Method
◉ Message Passing

In this chapter, we will look into the concepts - Classes and Objects.

◉ Object − Objects have states and behaviors. Example: A dog has states - color, name, breed as well as behaviors – wagging the tail, barking, eating. An object is an instance of a class.

◉ Class − A class can be defined as a template/blueprint that describes the behavior/state that the object of its type support.

Objects in Java


Let us now look deep into what are objects. If we consider the real-world, we can find many objects around us, cars, dogs, humans, etc. All these objects have a state and a behavior.

If we consider a dog, then its state is - name, breed, color, and the behavior is - barking, wagging the tail, running.

If you compare the software object with a real-world object, they have very similar characteristics.

Software objects also have a state and a behavior. A software object's state is stored in fields and behavior is shown via methods.

So in software development, methods operate on the internal state of an object and the object-to-object communication is done via methods.

Classes in Java


A class is a blueprint from which individual objects are created.

Following is a sample of a class.

Example

public class Dog {
   String breed;
   int age;
   String color;

   void barking() {
   }

   void hungry() {
   }

   void sleeping() {
   }
}

A class can contain any of the following variable types.

◉ Local variables − Variables defined inside methods, constructors or blocks are called local variables. The variable will be declared and initialized within the method and the variable will be destroyed when the method has completed.

◉ Instance variables − Instance variables are variables within a class but outside any method. These variables are initialized when the class is instantiated. Instance variables can be accessed from inside any method, constructor or blocks of that particular class.

◉ Class variables − Class variables are variables declared within a class, outside any method, with the static keyword.

A class can have any number of methods to access the value of various kinds of methods. In the above example, barking(), hungry() and sleeping() are methods.

Following are some of the important topics that need to be discussed when looking into classes of the Java Language.

Constructors


Java Object and Classes, Oracle Java Study Materials, Oracle Java Exam Prep
When discussing about classes, one of the most important sub topic would be constructors. Every class has a constructor. If we do not explicitly write a constructor for a class, the Java compiler builds a default constructor for that class.

Each time a new object is created, at least one constructor will be invoked. The main rule of constructors is that they should have the same name as the class. A class can have more than one constructor.

Following is an example of a constructor −

Example

public class Puppy {
   public Puppy() {
   }

   public Puppy(String name) {
      // This constructor has one parameter, name.
   }
}

Java also supports Singleton Classes where you would be able to create only one instance of a class.

Note − We have two different types of constructors. We are going to discuss constructors in detail in the subsequent chapters.

Creating an Object


As mentioned previously, a class provides the blueprints for objects. So basically, an object is created from a class. In Java, the new keyword is used to create new objects.

There are three steps when creating an object from a class −

◉ Declaration − A variable declaration with a variable name with an object type.

◉ Instantiation − The 'new' keyword is used to create the object.

◉ Initialization − The 'new' keyword is followed by a call to a constructor. This call initializes the new object.

Following is an example of creating an object −

Example

public class Puppy {
   public Puppy(String name) {
      // This constructor has one parameter, name.
      System.out.println("Passed Name is :" + name );
   }

   public static void main(String []args) {
      // Following statement would create an object myPuppy
      Puppy myPuppy = new Puppy( "tommy" );
   }
}

If we compile and run the above program, then it will produce the following result −

Output

Passed Name is :tommy

Accessing Instance Variables and Methods


Instance variables and methods are accessed via created objects. To access an instance variable, following is the fully qualified path −

/* First create an object */
ObjectReference = new Constructor();

/* Now call a variable as follows */
ObjectReference.variableName;

/* Now you can call a class method as follows */
ObjectReference.MethodName();

Example

This example explains how to access instance variables and methods of a class.

public class Puppy {
   int puppyAge;

   public Puppy(String name) {
      // This constructor has one parameter, name.
      System.out.println("Name chosen is :" + name );
   }

   public void setAge( int age ) {
      puppyAge = age;
   }

   public int getAge( ) {
      System.out.println("Puppy's age is :" + puppyAge );
      return puppyAge;
   }

   public static void main(String []args) {
      /* Object creation */
      Puppy myPuppy = new Puppy( "tommy" );

      /* Call class method to set puppy's age */
      myPuppy.setAge( 2 );

      /* Call another class method to get puppy's age */
      myPuppy.getAge( );

      /* You can access instance variable as follows as well */
      System.out.println("Variable Value :" + myPuppy.puppyAge );
   }
}

If we compile and run the above program, then it will produce the following result −

Output

Name chosen is :tommy
Puppy's age is :2
Variable Value :2


Source File Declaration Rules



As the last part of this section, let's now look into the source file declaration rules. These rules are essential when declaring classes, import statements and package statements in a source file.

◉ There can be only one public class per source file.

◉ A source file can have multiple non-public classes.

◉ The public class name should be the name of the source file as well which should be appended by .java at the end. For example: the class name is public class Employee{} then the source file should be as Employee.java.

◉ If the class is defined inside a package, then the package statement should be the first statement in the source file.

◉ If import statements are present, then they must be written between the package statement and the class declaration. If there are no package statements, then the import statement should be the first line in the source file.

◉ Import and package statements will imply to all the classes present in the source file. It is not possible to declare different import and/or package statements to different classes in the source file.

Classes have several access levels and there are different types of classes; abstract classes, final classes, etc. We will be explaining about all these in the access modifiers chapter.

Apart from the above mentioned types of classes, Java also has some special classes called Inner classes and Anonymous classes.

Java Package


In simple words, it is a way of categorizing the classes and interfaces. When developing applications in Java, hundreds of classes and interfaces will be written, therefore categorizing these classes is a must as well as makes life much easier.

Import Statements


In Java if a fully qualified name, which includes the package and the class name is given, then the compiler can easily locate the source code or classes. Import statement is a way of giving the proper location for the compiler to find that particular class.

For example, the following line would ask the compiler to load all the classes available in directory java_installation/java/io −

import java.io.*;

A Simple Case Study


For our case study, we will be creating two classes. They are Employee and EmployeeTest.

First open notepad and add the following code. Remember this is the Employee class and the class is a public class. Now, save this source file with the name Employee.java.

The Employee class has four instance variables - name, age, designation and salary. The class has one explicitly defined constructor, which takes a parameter.

Example

import java.io.*;
public class Employee {

   String name;
   int age;
   String designation;
   double salary;

   // This is the constructor of the class Employee
   public Employee(String name) {
      this.name = name;
   }

   // Assign the age of the Employee  to the variable age.
   public void empAge(int empAge) {
      age = empAge;
   }

   /* Assign the designation to the variable designation.*/
   public void empDesignation(String empDesig) {
      designation = empDesig;
   }

   /* Assign the salary to the variable salary.*/
   public void empSalary(double empSalary) {
      salary = empSalary;
   }

   /* Print the Employee details */
   public void printEmployee() {
      System.out.println("Name:"+ name );
      System.out.println("Age:" + age );
      System.out.println("Designation:" + designation );
      System.out.println("Salary:" + salary);
   }
}

As mentioned previously in this tutorial, processing starts from the main method. Therefore, in order for us to run this Employee class there should be a main method and objects should be created. We will be creating a separate class for these tasks.

Following is the EmployeeTest class, which creates two instances of the class Employee and invokes the methods for each object to assign values for each variable.

Save the following code in EmployeeTest.java file.

import java.io.*;
public class EmployeeTest {

   public static void main(String args[]) {
      /* Create two objects using constructor */
      Employee empOne = new Employee("James Smith");
      Employee empTwo = new Employee("Mary Anne");

      // Invoking methods for each object created
      empOne.empAge(26);
      empOne.empDesignation("Senior Software Engineer");
      empOne.empSalary(1000);
      empOne.printEmployee();

      empTwo.empAge(21);
      empTwo.empDesignation("Software Engineer");
      empTwo.empSalary(500);
      empTwo.printEmployee();
   }
}

Now, compile both the classes and then run EmployeeTest to see the result as follows −

Output

C:\> javac Employee.java
C:\> javac EmployeeTest.java
C:\> java EmployeeTest
Name:James Smith
Age:26
Designation:Senior Software Engineer
Salary:1000.0
Name:Mary Anne
Age:21
Designation:Software Engineer
Salary:500.0