JavaBeat

  • Home
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Privacy
  • Contact Us

Defining A Java Constant: When, Why, and How to Do It

August 1, 2019 by itadmin Leave a Comment

Coding on laptop above the table

Knowing how to define a Java constant is an essential step to mastering Java. As your programs increase in complexity, the use of constants will help simplify them.

Quick Navigation
What Is a Constant?
How to Define a Constant
Using Constants
Add It to Your Toolbelt

What Is a Constant?

Constants are numbers that do not change, such as the number of hours in a day.

Person coding on laptop

Image by ​Lukas via Pexels

In an algebraic expression, constants are numbers that stand on their own and therefore represent a single unchanging entity.

For example, we call the 7 in 11x - 7 a constant.

Constants vs. variables

A java constant differs from variables in a few key ways.

First, variables are subject to change.

The age of your cat changes from year to year. However, the name, gender, and breed of your cat are constants because they will always stay the same.

Second, while you may use constants to manipulate variables, it never works in reverse.

Person using laptop near books

Image by ​Christina Morillo via Pexels

Use variables to add up sums, determine if something is true or false, allow the user to name things, etc. Define constants to give names to numbers and strings that you use often but never change.

Finally, the ways you define and call on a Java constant are slightly different from how you would for variables.

A Java constant requires the use of modifiers to declare. However, you can easily call on them without having to create an object, as you would with a variable.

Benefits of a constant

A Java constant makes your programs easier for others to read. Rather than remembering why a number is there, they can simply read the names of the constant.

For example, it's easier to understand the meaning of "days_in_April" than it is "30." The number 30 could apply to another month, or relate to something completely different.

Woman coding on mac

Image by Negative Space via Pexels

Constants can increase the performance of your programs because the Java Virtual Machine (JVM) caches them in addition to your application. That you can call on them directly from a class can also be more efficient.

How to Define a Constant

You can only define a Java constant as a modifier to instance variables. Applying the same modifiers to local variables will not work.

An instance variable is one that exists inside a class, but outside of a method. The following is an example of an instance variable vs. a local one:

public class Name{


>int days_in_April = 30;//Instance variable


void methodName() {


int days_in_April = 30;//local variable


}


}

Person coding on mac

Image by ​Lee Campbell via Pexels

In order to modify an instance variable so that it becomes a constant, use this line of code:

static final int DAYS_IN_APRIL = 30;

When using a Java constant, ensure that you write it in all caps. This lets you and everyone viewing your application know that it is not a variable.

The words "static" in that line of code is what allows you to call on the constant outside of an object.

By using the word "final," you let the program know that the values will never change, and the JVM can cache them.

Note that "int" is not the only kind of variable that you can modify to make a constant. Although it's is the most common, there is also short, long, byte, char, float, double, and boolean.

Using Constants

People coding on macbook

Image by Christina Morillo via Pexels

Here is an example of how you can put your constant to use:

public class className {
static void main(String[] args) {
System.out.println("Days in April: " + className.DAYS_IN_APRIL);

}
}

This will display the message "Days in April: 30" on the screen.

Add It to Your Toolbelt

Now that you understand how to use a Java constant, how will you implement them in your applications? Let us know in the comments below!

Featured image by Negative Space via pexels.

Filed Under: Content Tagged With: java constant

Servlet Life Cycle: Explanation

June 27, 2019 by itadmin Leave a Comment

Servlets are small programs that run at server side and creates dynamic web pages. Servlets respond to requests sent by the user. In MVC architecture, servlets act as a controller. The controller processes and responds to user requests. The Servlet Life Cycle contains the following steps:

  • Load servlet class.
  • Create a servlet instance.
  • Call the init method.
  • Call the service method.
  • Call the destroy method.

Servlet Life Cycle: Class Loading

The first step in the creation of a servlet component is to load the servlet class file into the web container’s JVM (Java Virtual Machine). When the web.xml invokes or configures a first-time servlet with a load-on-startup element, it invokes this step.

Creating Servlet Instance

After loading the servlet class into the web container’s JVM, create an instance of that class. Servlet specification creates only one servlet instance for a single definition in the deployment descriptor.

The init () method

The web container initializes the parameters specified in the deployment descriptor. A servlet first loads into memory, invoking the init () method. The syntax of the init () method looks like this:

[code lang="java"]
public void init () throws Servlet Exception {
//code
}
[/code]

The service () method

After initializing the servlet component, the web container begins sending requests to that component utilizing the service method. The service method processes the request. The web container issues a unique request and response to the service method. The syntax of the service () method:

[code lang="java"]
public void service (Servletrequest request, Servletresponse  response)
     throws ServletException, IOException {
}
[/code]

When the web container calls the service () method, it invokes the doGet (), doPost (), doPut (), doDelete (), doTrace (), doOptions (), getLastModified () methods.

The doGet () and doPost () are most frequently used with each service request. We must override doGet () and doPost () methods depending on the type of request.

The doGet () method: We use doGet () method to send a specific amount of data. The address bar displays the data. Override doGet () method depending on the type of request. Define as follows:

[code lang="java"]
public void doGet (HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException{
//code
}
[/code]

The doPost () method: Send a large amount of data using the doPost () method. Data is not viewable in the address bar when using this method. The doPost () method sends secure data like passwords. Override the doPost () method depending on the type of request. Define as follows:

[code lang="java"]
public void doPost (HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException{
//code
}
[/code]

doDelete (): is used to delete files, web pages, or documents from the server. It will return HTTP “Bad Request” error if requests are formatted incorrectly. Example:

[code lang="java"]
 protected  void doDelete (HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException{
 //code
}
[/code]

doPut(): Puts files, web pages, or documents in the server for uploading files. If requests are formatted incorrectly then it will return an HTTP “Bad Request” error. Example:

[code lang="java"]
protected  void doPut (HttpServletRequest request, HttpServletResponse response)
 throws ServletException, IOException{
  //code
}
 [/code]

doTrace (): Logs and debugs. It also tests the requested message. There is no need to override this method. For example:

[code lang="java"]
protected void doTrace(HttpServletRequest request, HttpServletResponse response)
 throws ServletException, IOException{
  //code
 }
             [/code]

doOptions (): Handles the OPTIONS request. There is no need to override this method. It determines which HTTP method is supported by the server and returns the correct header. If requests are formatted incorrectly then it will return an HTTP “Bad Request” error.
For example:

[code lang="java"]
protected void doOptions(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException{
 //code
 }
[/code]

getLastModified (): Returns what time the request was last modified. It should override a GET request to return the modification time of an object.
For example:

[code lang="java"]
protected long getLastModified (HttpServletRequest request)
     throws ServletException, IOException{
                     //code
}  [/code]

The destroy () method

When a web application shuts down, the web container calls the destroy method. The destroy method cleans up any resources that servlet might have initialized. Example of a destroy () method syntax:

[code lang="java"]
public  void destroy(){
//code
}
[/code]

Servlet Life Cycle: Example

Now, we will create a servlet example using Eclipse IDE. To create a servlet application, use the following steps:

    • Environment used:
      • JDK
      • Eclipse IDE
      • Apache Tomcat Server
      • Java-api
    • Open the Eclipse IDE and Go to File Menu ->New->Select Dynamic Web Project.
      servlet life cycle example
    • Enter Project Name. Click Next.
    • Click on Generate web.xml deployment descriptor and click Finish.
    • Under the project, click Java Resources ->select src, right mouse click, and select New->Package to type the name as javabeat.net.servlets
      servlet life cycle new java package example
    • Now click on the package javabeat.net.servlets and New ->select Servlet
      servlet life cycle select new servlet
      Type the class name as ServletDemo and click Finish.
    • Now, add a servlet-api.jar to project with the following steps.
      • Right click on Project name, select -> Properties ->select Java Build Path-> Click Add External JARs.
      • Select servlet-api.jar from the Apache Tomcat directory.
      • Hit Open and click OK.

      servlet life cycle add external JARs

    • Add the following content to the ServletDemo.java:
      [code lang="java"]
      package javabeat.net.servlets;
      
      
      import java.io.IOException;
      import java.io.PrintWriter;
      
      import javax.servlet.ServletException;
      import javax.servlet.http.HttpServlet;
      import javax.servlet.http.HttpServletRequest;
      import javax.servlet.http.HttpServletResponse;
      
      /**
       * Servlet implementation class ServletDemo
       */
      public class ServletDemo extends HttpServlet {
      
      /**
       * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
       */
      protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      	response.setContentType("text/html");
      	PrintWriter out = response.getWriter();
      
      	out.println("<html>");
      	out.println("  <head>");
      	out.println("    <title>SimpleServlet</title>");
      	out.println("  </head>");
      	out.println("  <body>");
      	out.println("    Hello, World");
      	out.println("  </body>");
      	out.println("</html>");
      	}
      
      }
      [/code]
    • Edit the web.xml and add the following content:
      [code lang="xml"]
      <?xml version="1.0" encoding="UTF-8"?>
      <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
        <servlet>
              <servlet-name>ServletDemo</servlet-name>
              <servlet-class>javabeat.net.servlets.ServletDemo</servlet-class>
          </servlet>
      
      
          <servlet-mapping>
              <servlet-name>ServletDemo</servlet-name>
              <url-pattern>/ServletDemo</url-pattern>
          </servlet-mapping>
      </web-app>
      [/code]
    • Select the class ServletDemo. Right click->Run As and select Run on Server, and you should achieve the output shown below:

servlet life cycle demo example

  • Java EE Tutorials
  • Servlets Tutorials
  • Servlets Interview Questions

Previous Tutorial: Servlet API  || Next Tutorial: Generic Servlet and HTTP Servlet

Filed Under: Java EE Tagged With: Servlets Tutorials

Java Scanner Class With Examples

June 26, 2019 by itadmin Leave a Comment

This article will discuss the scanner class in Java with some examples and illustrations. Once you know the basics of programming, the time comes for a developer to work with novice programs in text mode (console).

Many begin using the scanner class, precisely because it facilitates the data input in the console. Java 5 introduced this class. Before then, creating programs that received variable values in Console mode was difficult.

Java Scanner Concept

For many, the Scanner class’s meaning is often complicated and difficult to understand in the beginning. With time and effort, however, the programmer can come to understand the definition. A simple text scanner parses primitive types and Strings using regular expressions.

The class Scanner aims to separate the entry of text into blocks, generating the known tokens, which are sequences of characters separated by delimiters by default corresponding to blanks, tabs, and newline.

With this class, you can convert text to primitives. The texts are considered objects of type String, InputStream, and files.

  • What is a transient keyword in Java?
  • How to use ByteBuffer in Java?
  • Using Lambda Expressions of Java 8 in Java FX event handlers

Java Scanner In Practice

Importing the Scanner class in Java

Firstly, you need to know the functions and features of this class. When using the Scanner class, the compiler will ask you to do the following imports:

[java]
import java.util.Scanner;
[/java]

Declarations Scanner

As described in the introduction, this class assists in reading data. The example below shows how to use the Scanner object.

It is necessary to create an object of type Scanner and then an argument of object System.in to the Scanner constructor, as follows:

[java]
package net.javabeat;

import java.util.Scanner;

public class TestScannerDeclaration {
	public static void main(String[] args) {
		// Read from the command line
		Scanner sc1 = new Scanner(System.in);
		String textString = "Manisha Patil";
		// Read from a String
		Scanner sc2 = new Scanner(textString);
	}
}
[/java]

Count tokens in the string

Now that you have created your scanner class, focus on learning to read the data. The example below illustrates that we need to iterate through each token in the input to read data.

[java]
package net.javabeat;

import java.util.Scanner;

public class CountTokens {
	public static void main (String [] args) {
        int i = 0;
        Scanner sc = new  Scanner(System. in );
        System.out.print("Enter some text:" );
        while (sc.hasNext()) {
            i++;
            System.out.println("Token:" + sc.next ());
        }
        sc.close(); // End of program
    }
}
[/java]

The object System.in takes the input that you type from your keyboard.

Methods of class Scanner

Below are some of the main methods that can be invoked based on the input data type. For each primitive, there is a method call to return the value of the input data type.

[java]
Scanner sc = new  Scanner(System.in);

float numF = sc.nextFloat();
int num1 = sc.nextInt();
byte byte1 = sc.nextByte();
long lg1 = sc.nextLong();
boolean b1 = sc.nextBoolean();
double num2 = sc.nextDouble();
String name = sc.nextLine();
[/java]

Demonstration of InputMismatchException

The class Scanner reads data as command line arguments. Therefore, it is always a good practice to use try/catch. Try/catch helps you avoid the exceptions caused by the wrong data type entry.

For example, in the below image, you can see that the incorrect data type entry causes an exception. The method was expecting a data of type Double.

Demonstration of exception InputMismatchException

Scanner Class Methods

Below is a list of some of the main methods of the Scanner class.

  • close(): Closes the current scanner.
  • findInLine(): Attempts to find the next occurrence of the specified pattern ignoring delimiters.
  • hasNext(): Returns true if this scanner has another token in its input.
  • hasNextXyz(): Returns true if the next token in this scanner’s input can be interpreted as an Xyz in the default radix using the nextXyz() method. Here Xyz can be any of these types: BigDecimal, BigInteger, Boolean, Byte, Short, Int, Long, Float, or Double.
  • match(): Returns the match result of the last scanning operation performed by this scanner.
  • next(): Finds and returns the next complete token from this scanner.
  • nextXyz(): Scans the next token of the input as an Xyz where Xyz can be any of these types: boolean, byte, short, int, long, float or double.
  • nextLine(): Advances this scanner past the current line and returns the skipped input.
  • radix(): Returns the current index of the Scanner object.
  • remove(): The implementation of an Iterator does not support this operation.
  • skip(): Skip to the next search for a specified pattern ignoring delimiters.
  • string(): Returns a string representation of the object is a Scanner.
Example

Take a look at this full-fledged example of what to with the Scanner class.

The classes IndividualScannerTest and Person use object-oriented programming (OOP). OOP aims to show object manipulation. Methods setters (setAttributeName) keeps the value entered. The values are then used to generate the output of each object created in the list.

[java]
package net.javabeat;

public class Person {
	private Integer code;
	private String name;
	private String address;
	private Integer age;

	public Integer getCode() {
		return code;
	}

	public void setCode(Integer code) {
		this.code = code;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public Integer getAge() {
		return age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}

	@Override
	public String toString() {
		return "code:" + code + "" + "\n" + "Name:" + name + "" + "\n"
				+ "Address:" + address + "" + "\n" + "Age:" + age + "\n";
	}
}
[/java]

The class IndividualScannerTest shows that several Person objects can be stored in a list and later printed.

Take a test, insert two or more entries, and then choose option 2. All Person objects stored in the list will be printed.

[java]
package net.javabeat;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class IndividualScannerTest {
	public static void main(String[] args) {
		peopleData();
	}

	public static void peopleData() {
		Scanner sc = new Scanner(System.in);
		Person person;
		List<Person> personList = new ArrayList<Person>();
		int option = 0;

		do {
			System.out.println("# # Choose one of the options below # #");
			System.out.println("Option 1 - Enroll people");
			System.out.println("Option 2 - Print people registered");
			System.out.println("Option 0 - Exit program");
			System.out.println("_______________________");

			System.out.print("Enter your choice here:");
			option = Integer.parseInt(sc.nextLine());

			if (option == 1) {
				// Create a new object
				person = new Person();

				System.out.print("Enter code:");
				person.setCode(Integer.parseInt(sc.nextLine()));

				System.out.print("Enter the name:");
				person.setName(sc.nextLine());

				System.out.print("Enter the address:");
				person.setAddress(sc.nextLine());

				System.out.print("Enter the age:");
				person.setAge(Integer.parseInt(sc.nextLine()));

				System.out.println();

				// Holds the person object in a list.
				personList.add(person);
			} else if (option == 2) {
				if (personList.isEmpty()) {
					System.out
							.println("There are people registered, press any key to continue");
					sc.nextLine();
				} else {
					System.out.println(personList.toString());

					System.out.println("Press one key to continue.");
					sc.nextLine();
				}
			}
		} while (option != 0);

		sc.close();
	}
}

[/java]

Reading data from a file

In the previous example, we read data from the command line. If the data is large, it is better to store it in a file and then read the data from the file. Let us see an example of how to read data from a file using Scanner class.

[java]
package net.javabeat;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ReadFile {
	public static void SpeakIt(String fileName) {
		try {
			File file = new File(fileName);
			Scanner sc = new Scanner(file);
			while (sc.hasNext()) {
				System.out.print(sc.nextLine());
			}

			sc.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		SpeakIt("samplefile.txt"); // change the path of the desired file.
	}
}

[/java]

Further Reading:

  • Working with Virtual Proxy Pattern
  • Reading file asynchronously in Java

We worked through some basic concepts of Scanner class in Java. Programmers use the scanner class in Java to read data from a command line input, or a file system.

If you are interested in receiving future articles, please subscribe here. Follow us on @twitter and @facebook.

Filed Under: Java Tagged With: Java

Gradle Tutorial

June 25, 2019 by itadmin Leave a Comment

There are many automated build tools used for building, testing, publishing deployment, and packaging software these days. Apache Ant, Maven, and Gradle are the most popular automated build tools.

Gradle is a build automation tool that helps developers by eliminating the need for unnecessary efforts. Standard directory preparation, compilation, packaging, generating the required artifacts, and other tasks would otherwise waste a lot of time.

The understanding of a concept, determining the lifecycle and phases of Gradle tool, and managing the required libraries and dependencies are the most essential skills that developers look for in a build tool. The video tutorial at the end of this article will help you learn Gradle using audio-visual explanation. The text portion of this tutorial will explain the following concepts:

  1. What is Gradle?
  2. How to Install Gradle?
  3. Basic Example using Gradle Script
  4. Dependency management using Gradle
  5. Gradle Tasks

1. What is Gradle?

Gradle is a build automation tool that combines the power and flexibility of Ant with the dependency management and conventions of Maven. This new build tool has become popular among developers. Powered by a Groovy DSL, Gradle provides a declarative way of describing builds through sensible defaults. For example, Spring IO and Maven tool both support the new build. Important points:

  1. A very general flexible purpose build tool like Ant
  2. Very powerful support for multi-project builds
  3. Very powerful dependency management
  4. Full support for your existing Maven infrastructure
  5. Support for Ant tasks and builds
  6. Groovy-based build script
  7. A rich domain model for describing your build

2. How to install:

  • Download the latest Gradle 2.0 binaries.
  • Copy the downloaded file and import it to your local directory. For this tutorial, we have used D:\Gradle\gradle-2.0.
  • Add Gradle into environment variables as illustrated below.

Gradle - Add System Variable

  • Open your command line and type gradle -version to get the version installed on your system.

Gradle - Print Out Gradle Version At this time, you should be ready to use it. Gradle 2.0 was the latest available release when this article was written.

3. Scripts, Basics, and Hello World

Let us make the simplest Gradle build file that can help us understand the basics. You can print a hello, world message using one task or using two different tasks.

  • Create an empty file called build.gradle and define the first task you want to execute. Put these files inside an empty folder.
  • Define a task to print out the message.

build.gradle

[code]
task helloWorld << {
println 'hello, world'}
[/code]

build.gradle

[code]
task hello << {
println 'hello, '}
task world(dependsOn:hello) << {
println 'world'}
[/code]
  • Navigate to the folder that contains the build.gradle file and execute gradle -q <<taskName>>.

Gradle - Execute Task

Gradle - Execute Task Depends On Other

Gradle - Files DefinedIllustration explanation:

  • The build file is not required to include anything and does not rely on external dependencies.
  • The execution of two build files causes a “hello world” message to be displayed into your console.
  • The second file defines the “world” task as a dependent one. The execution will directly cause the task “hello” to execute. This is a simple example of how to use “dependsOn” for executing the tasks.

Now, build a Java program using the Gradle build. Create a project structure that looks like this: Gradle - Create Project Structure

  • Type apply plugin: ‘java’ inside your build.gradle file, located at the same level as your src directory.
  • Create your own HelloWorld.java file that contains a simple main method to get the Hello World! message to be displayed.
  • From your command console, run Gradle build.

Gradle - Gradle Build Result

  • The new build directory automatically generates after running the command “gradle build”. The build directory contains classes followed by your package, dependency cache, and other directories.  This is the result of the conventions of Gradle’s Java plugin. There was no need to make a single entry or write a line of configuration.
  • Navigate to your package to see your compiled HelloWorld.class. Type java -cp build/classes/main/ net.javabeat.gradle.example.HelloWorld.

Gradle - Running Java Application

4. Dependency Management

Dependencies are classes, files, and JARs required for building your project and deploying it successfully. Typically, there are two types of dependencies. Your project needs incoming dependencies to build and run. Publications are the outgoings your project produces.

  • Dependency Resolution:

    • Tell Gradle what dependencies your project needs so it can find and make them available in your build. Dependency resolution finds dependencies, downloads them from different repositories, locates them in the local directories, and brings them from another building project in the same multi-project build.
  • Transitive Dependencies:

    • In general, dependencies need other dependencies. Gradle finds these transitive dependencies and makes them available.
  • Publication:

    • Gradle also maintains publication processes.
    • Once you declare your publications, Gradle publishes them to your desired location. The desired location can be a local directory, remote repository (Maven and ivy), or direct consuming through multi-project build procedure.

HelloWorld class is supposed to use Apache POI 3.10-FINAL version for creating an excel document. Create a build.gradle file: build.gradle

[code]
apply plugin : 'java'
repositories {
mavenLocal()
mavenCentral()
}
dependencies {
compile 'org.apache.poi:poi:3.10-FINAL'}
[/code]
  • Gradle provides numerous plugins for you to use. Plugin Java defines a set of tasks from compileJava—which compiles your sources. Java plugin needs a defined set of configurations.
  • Repositories should be defined for referencing dependencies. For example, Maven Local repository refers to your local repository defined beneath your home directory/.m2/repository. The dependencies that are not located inside will be downloaded from the maven central one.
  • Dependencies closure defines your dependencies. Java plugins define various standard configurations. Compile, runtime, testCompile, and testRuntime define the scopes of your dependencies. Compile specifies the dependencies required to compile project source. Runtime lists what dependencies are required at runtime.
  • Executing gradle build causes the program to search mentioned dependencies inside your local repository. Gradle will download them if they are not found. Java plugin executes after Apache Poi downloads the tasks.

Gradle - Downloading Poi Dependency Gradle - Java Plugin Tasks Are Executed Automatically

  • Gradle maintains each downloaded dependency inside its local cache. The dependency downloads from the maven central repository or fetches from a local one.

Gradle - Apache Poi has been downloaded into your gradle cache

  • HelloWorld class has been changed to contain the Excel workbook.

HelloWorld.java

[code lang="java"]
package net.javabeat.gradle.example;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class HelloWorld {
	public static final void main(String [] args) throws Exception{
		System.out.println("Hello World !");
		HSSFWorkbook book = new HSSFWorkbook();
		System.out.println("Excel Book Created :: "+book);
	}
}
[/code]
  • Use the plugin “application” to execute your application.
  • “gradle tasks” provides a list of the plugin’s tasks.

build.gradle

[code]
apply plugin : 'java'
apply plugin:'application'

mainClassName = "net.javabeat.gradle.example.HelloWorld"

repositories {
	mavenLocal()
	mavenCentral()
}

dependencies {
	compile 'org.apache.poi:poi:3.10-FINAL'
}
[/code]

Gradle - Application Plugin Listed Tasks

  • Gradle command uses the Java and Application tasks listed directly.
  • Type gradle run to execute your Java application.

Gradle - Running Application With Dependency Respective

5. Tasks

Tasks are a fundamental unit of build activity. Tasks are named collections of build instructions Gradle uses to perform a build. Above, we used a direct task definition with HelloWorld task and a pre-defined task with compileJava. You need a task name to declare it. build.gradle

[code]
apply plugin : 'java'
apply plugin:'application'

mainClassName = "net.javabeat.gradle.example.HelloWorld"

task hello

repositories {
	mavenLocal()
	mavenCentral()
}

dependencies {
	compile 'org.apache.poi:poi:3.10-FINAL'
}
[/code]

Gradle - Hello Task Definition

  • To define a hello task, type the keyword followed by the task name.
  • Executing gradle tasks prints out all tasks your build file contains, including those defined by the plugins used. Your custom tasks are listed under Other tasks.

If you are executing your hello task using gradle hello command, you will not see any results because it does not define any action. Use left-shift << operator to assign the action into a certain task. It will make your task able to execute specific actions, like the print message.

build.gradle

[code lang="xml"]
apply plugin : 'java'
apply plugin:'application'

mainClassName = "net.javabeat.gradle.example.HelloWorld"

task hello &amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt; {
	println 'Hello World !'
}

repositories {
	mavenLocal()
	mavenCentral()
}

dependencies {
	compile 'org.apache.poi:poi:3.10-FINAL'
}
[/code]

Gradle - Hello Task Action Execution Result

  • By using the left shift operator, you can define your desired action.
  • Executing “hello task” will print out the message you have provided.
  • Your desired action is enclosed with two curly brackets, often called Task Closure.

Gradle defines two phases. Configuration and execution mainly initiate configuration task and action task respectively. The following simple example that provides you a mix between action and configuration tasks. build.gradle

[code]
apply plugin : 'java'
apply plugin:'application'

mainClassName = "net.javabeat.gradle.example.HelloWorld"

task hello

hello &amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt; {
	println 'Action Time'
	print 'Hello'
}

hello &amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt; {
	println ' World !'
}

hello {
	println 'Configuration Time !'
}

repositories {
	mavenLocal()
	mavenCentral()
}

dependencies {
	compile 'org.apache.poi:poi:3.10-FINAL'
}
[/code]

How to work with action and configuration tasks:

  • The output of the action task is appended in the Hello World! message.
  • Configuration tasks are the same as action tasks. One major difference here is the configuration task has eliminated the left shift operator.
  • Configuration block is the place you set up variables and data structures that will be needed by task action when it runs.

Gradle creates an internal object model of your build before it executes. Every task that you declare is a task object within the overall project. By default, each new task receives the type DefaultTask. The main methods Default Task provides are as followed:

  • dependsOn(task): adds a task as a dependency of the calling task.
  • doFirst(closure): adds a block of executable code to the beginning of a task’s action.
  • doLast(closure): adds a block of executable code to the end of a task’s action.
  • onlyIf(closure): allows you to express a predicate which determines if a task should be executed. The value of the predicate is the value of the closure.

Below is a simple example of how you can leverage all the inherited methods in your build. build.gradle

[code]
apply plugin : 'java'
apply plugin:'application'

mainClassName = "net.javabeat.gradle.example.HelloWorld"

task preHello
task hello (dependsOn:preHello)

preHello &amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt; {
	println 'Action Time'
}
preHello.doFirst{
	println 'Do First'
}

preHello.doLast {
	println 'Do Last'
}

hello  &amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt; {
	print 'Hello'
}

hello &amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt; {
	println ' World !'
}

hello {
	println 'Configuration Time !'
}

repositories {
	mavenLocal()
	mavenCentral()
}

dependencies {
	compile 'org.apache.poi:poi:3.10-FINAL'
}
[/code]

Gradle - Leverage DefaultTask Inherited Methods DefaultTask has a defined set of properties that your own custom tasks can use. Here are the provided properties:

  • didWork: a boolean property that provides an indicator if a certain task has been completed successfully. didWork property can be accessed by using tasks.<<task-name>>.didWork expression.
  • enabled: a boolean property that provides an indicator of when a certain task will be executing. Accessing the enabled indicator can be done using tasks.<<task-name>>.enabled expression.
  • path: a string property containing the fully qualified path of a task. If you have written tasks.<<task-name>>.path inside your build file, you will get a colon followed by your written task name, like :task-name which gives you an indicator for this task defined in the top-level build file. Since Gradle supports dependent sub-projects or nested builds, and in case your typed task existed in a nested build called nested.gradle, then the path of it will be :nested:task-name.
  • logger: a reference of an implicit logger object. Logging is a common requirement for various types of frameworks and platforms. DEBUG, INFO, LIFECYCLE, WARN, QUIET, and ERROR are levels supported by Gradle. For logging messages, you should use logger.<<LOGGING-LEVEL>> ‘<<Messages>>’ expression.
  • logging: a property that gives you access to the log level setting where you can specify all of the logging messages shown. Following the example, a debug logging level has been specified before using logger.debug expression.
  • description: a meta-data human-readable property used to describe the purpose of a certain task. The description property is defined at the declaration of a task. Following expression task <<Your-Task>>(description:'<<Your-Description>>’) <<{ … } used to leverage description property.
  • temporaryDir: a property used for reference Temporal File Object points to a temporary directory that corresponds to the build file. If you’ve typed expression like println tasks.compileJava.temporaryDir As an example, D:\Gradle\HelloWorld\build\tmp\compileJava path will be shown.

Example of leveraging the above properties inside your build file: build.gradle

[code]
apply plugin : 'java'
apply plugin:'application'

mainClassName = "net.javabeat.gradle.example.HelloWorld"

task preHello
task hello (dependsOn:preHello)
task notifyMe(dependsOn:compileJava) &amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt; {
	logging.level = 'DEBUG'
	if(tasks.compileJava.didWork){
		logger.debug 'Compilation finsihed sucessfully'
	}
}

preHello &amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt; {
	println 'Action Time'
}
preHello.doFirst{
	println 'Do First'
}

preHello.doLast {
	println 'Do Last'
}

hello  &amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt; {
	print 'Hello'
}

hello &amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt; {
	println ' World !'
}

hello {
	println 'Configuration Time !'
}

repositories {
	mavenLocal()
	mavenCentral()
}

dependencies {
	compile 'org.apache.poi:poi:3.10-FINAL'
}
[/code]

Gradle - Leverage DefaultTask Inherited Properties Be sure to remember:

  • The compileJava didWork flag will never be flagged true if your classes are compiled before. Execute gradle clean to clean all of your compiled classes.
  • NotifyMe task uses didWork flag upon compileJava to determine if the task has accomplished.
  • Once compileJava task is done, the didWork flag will be set to true. The logger will then log your desired message.
  • Configuration phase is implemented before the phase of execution. It enables you to configure some variables, resources, and so on.

Besides the DefaultTask we explored, there a set of different task types you may need to be aware of:

  • Copy: copies files from one place into another.
  • Jar: creates a Jar file from your sources. Java Plugin already provides one.
  • JavaExec: runs Java class with main() method. Application Plugin already provides one.

6. Build Phases

Gradle executes a build by running through three distinct phases:

  • Initialization 

    The first executed phase where Gradle determines the projects that will be participating in the build. Settings.gradle build file is used for initialization phase configuration.

  • The configuration

    The second executed phase in which the build file’s tasks are assembled into an internal object model—usually called DAG (Directed Acyclic Graph). All tasks tagged as Configuration Tasks (Refer above) usually get executed at this phase.

  • Execution

    The last phase executes build tasks in the order arranged by their dependencies relationship. Tasks tagged as Execution Tasks (Refer above) are executed at this phase.

We explored the execution and configuration phases earlier. Now we will take a look at the Initialization phase. The settings file defines all user-defined actions. The following sample shows you the impact of defining a file. settings.gradle

[code]
println 'This message will be printed out as a part of initialization phase'
[/code]

Gradle - Initialization Phase

  • Initialization phase associates with the settings.gradle file.
  • build.gradle script file has not changed from the last one provided.

7. More Information:

Gradle is a build tool. This tutorial provides excellent guidance for you on how to use Gradle and what you need to use it. We explored the phases, tasks, methods, and properties throughout the sections of this tutorial. For more information on these concepts, refer to the Gradle official documentation/reference tutorials that provide more insights.

8. Video Tutorial

9. Download Source Code

[wpdm_file id=116]

Filed Under: Gradle Tagged With: Build Tools

Spring Annotations [Quick Reference]

June 19, 2019 by itadmin Leave a Comment

Below is the summary of the spring annotations that people use most frequently across spring applications. Spring Framework 2.5 added the annotations to the framework.

Before that, the XML files defined every configuration. Annotations became more convenient to reduce the XML configuration files and annotate the classes and methods with different annotations used at the time of scanning the files in the classpath.

Quick Reference for Spring Annotations

In this tutorial, I will list down the essential spring annotations used in Spring Core, Spring MVC, Spring Boot, Spring Data JPA, etc. modules previously published in this blog. I will continuously update this reference when I am writing the tutorial for new annotations.

You can bookmark this tutorial for quick reference of the most important annotations used in spring applications.

Spring Annotations Reference

Annotations Description
@Component, @Repository, and @Service @Component annotation is the generalized form considered as a candidate for auto-detection when using annotation-based configuration and classpath scanning. It extended to more specific forms such as @Controller, @Repository, and @Service.
@Autowired The XML files define string bean dependencies, and the same can be automatically detected by the Spring container by using the @Autowired annotation. This would eliminate the use of XML configurations.
@Qualifier There may be scenarios when you create more than one bean of the same type and want to wire only one of them with a property. Control this using @Qualifier annotation along with the @Autowired annotation.
@Required @Required annotation applies to bean property setter methods and enforces required properties
Difference between @Resource, @Autowired, and @Inject This tutorial explains the difference between these three annotations @Resource, @Autowired and @Inject used for injecting the objects.
@Inject and @Named @Inject and @Named annotations are JSR-330 annotations were introduced in Spring 3 as an alternative for the spring annotations @Autowired and @Component.
@Resource, @PostConstruct, and @PreDestroy This tutorial explains the JSR-250 annotations that Spring 2.5 introduces, which include @Resource, @PostConstruct, and @PreDestroy annotations.
@RestController @RestController annotation is inherited from the @Controller annotation. This is the special version of @Controller annotation for implementing the RESTful Web Services. @RestController was added as part of the Spring 4 release.
@RequestHeader @RequestHeader annotation for facilitating us to get the header details easily in our controller class. This annotation would bind the header details with the method arguments, and it can be used inside the methods.
@ControllerAdvice @ControllerAdvice annotation used for defining the exception handler with specific exception details for each method. This component will handle any exception thrown on any part of the application.
@ModelAttribute @ModelAttribute annotation can be used as the method arguments or before the method declaration. The primary objective of this annotation to bind the request parameters or form fields to a model object.
@Conditional This tutorial explains one of the new features introduced in spring 4, conditional annotation type.
@Query This spring data series tutorial explains @query annotation and how to create a custom query using the @query annotation.
@Profile This tutorial explains how to enable profiles in your spring application for different environments.
@Configuration Instead of using the XML files, we can use plain Java classes to annotate the configurations by using the @Configuration annotation. If you annotate a class with @Configuration, it indicates that the class defines the beans using the @Bean annotation.
@PathVariable We have to use @PathVariable for accepting the customized or more dynamic parameters in the request paths.
@Controller, @RequestMapping, @RequestParam, @SessionAttributes, and @InitBinder This tutorial explains some of the key annotations that are related to Spring MVC applications @Controller, @RequestMapping, @RequestParam, @SessionAttributes, and @InitBinder
Difference between @RequestParam and @PathVariable This tutorial explains the difference between the two annotations @RequestParam and @PathVariable.
@RequestMapping You can use @RequestMapping annotation for mapping web requests to particular handler classes or handler methods.
@Value  This tutorial shows how to load the properties file values using the @Value annotation.
@Import @Import is the annotation used for consolidating all the configurations defined in various configuration files using @Configuration annotation.
@Transactional Use annotation @Transactional to define a particular method that should be within a transaction.
@SpringBootApplication This is annotation is the heart of spring boot application. @SpringBootApplication indicates that it is the entry point for the spring boot application.
@EnableAutoConfiguration This example demonstrates how to use the @EnableAutoConfiguration annotations for auto-configuring the spring boot applications.
@EnableCaching @EnableCaching annotation is the annotation-driven cache management feature in the spring framework. This annotation added to the spring in version 3.1.

I will be adding more tutorials on annotations on this page. The above list will be updated frequently to reflect the latest spring annotations in the framework. If you are interested in receiving the updates on spring framework, please subscribe here.

Thank you for reading my blog!! Happy Learning!! If you have any questions related to spring development, please drop a comment or send me a mail. I will try my best to respond to your queries.

Filed Under: Spring Framework Tagged With: Spring Annotations, XML files

3 Kids Coding Languages To Learn Right Now

June 13, 2019 by itadmin Leave a Comment

boy and woman looking at a computer

​Kids learn essential skills like reading, writing, and arithmetic in the everyday classroom. However, the ever-growing importance of technology remains outside of many school curricula.

​Certain school districts fail to update their curricula with regularity. Some educational models use the same requirements as they did in the 1970s. Kids who attend these schools later find themselves at a disadvantage once out in the workforce.

​Kids miss out on the key skill of learning how to code at these schools.  Countless high-paying career paths call for proficiency in coding (or programming) computer languages. Without learning to code at a young age, a kid misses out on valuable opportunities.

​Once you have established the critical skill of coding, you must next explore what computer languages are appropriate to teach a kid. Despite the demand for coding in the modern workplace, a child is not worried about the job marketplace. Perusing a job site to see what coding skills are in demand is unnecessary.

​As a matter of fact, choosing a coding language based on what professionals use causes further issues in education. You may end up picking too complicated a coding language to teach in everyday schools. Furthermore, some coding languages rely on higher forms of math that children do not encounter until high school or later.

​By the time your kid enters the workplace, coding languages may have changed to the point that the language you chose solely due to its career value may not be relevant anymore.  Picking a kids’ coding language for its relevance to the marketplace is not wise.

two kids writing

​Source: Pexels

​When looking for a language that better appeals to kids, avoid compiled languages.

​Compilation, a complicated step in coding, requires a high level of fluency regarding abstract concepts. Enough adults find the idea of compiling too difficult to comprehend — kids cannot even begin to grasp the concept.

​Certainly, there are kids and teenagers in the world capable of grasping the ideas behind compiled languages. For the majority, however, the rule stands.

If you do not know what compiled versus interpreted means, please see the JavaScript section. We will avoid compiled languages when considering kids programming languages.

​We want to introduce kids to coding via languages that have relevance in today’s society, as opposed to an outdated language or those that do not work well. Teach coding languages that achieve immediate results, rather than languages that require more time and input before making any progress.

​Focus on languages that rely on visual elements. Children learn better when presented with illustrated information, as opposed to other types of data. For example, a kid’s coding language that works with graphics or web pages would be better than a language that focuses on databases or server management.

​Highly-Recommended Kids Coding Languages to Try

girl learning kids coding language with her mother

​Source: Pexels

Introducing kids at an early stage in education creates an interest. Cultivating an interest in young minds defines the main idea of coding as a standard in common curricula. A graphically appealing kids coding language helps you create and foster that interest, even if it does not produce a coder ready for their first big job right out of high school.

​Keep those thoughts in mind while you consider teaching the following computer languages to kids with hopes they spark an interest in coding.

​1. HTML/CSS

While HTML is not technically a programming language, it is similar enough to be mentioned here. HTML (Hypertext Markup Language) is the standard language that most web developers use to create pages on the World Wide Web.

​HTML, a markup language, uses English abbreviations to “markup” a document. This language tells the computer how large the heading should be or what words should be italicized, for example. An official definition can be found through Merriam-Webster.

​HTML fits the language criteria required to teach kids. Hypertext has been around for decades, and Hypertext Markup Language still is used all over the world to program and design webpages.

​One line of code using HTML can produce an almost immediate effect a kid can see and understand. Teaching coding through the HTML language requires minimal lessons on understanding the internet. Without time wasted teaching about browsers and such, the process of learning to code begins sooner.

HTML Advantages

​Among other advantages, learning HTML does not require a high proficiency in math. The average middle schooler can handle the math HTML requires for coding.

​Markup originally specialized in editing documents. Considering this fact, the appropriate math needed to code in HTML makes sense. The language was designed for editors, not coders. More information on markup can be found at Lifewire.

​In order to program in HTML, you only need a web browser and a text editor, such as Sublime or Notepad. With other languages, the instructor must install software packages themselves or give permission for students to download software packages. There is no need for downloading software when using HTML.

​Seasoned instructors know that permitting children to download software packages on school computers never ends well. Unless you enjoy working with anti-virus programs and deleting games on student laptops every so often, consider a different tactic.

​”HTML” often includes the abbreviation “CSS.” CSS ( or Cascading Style Sheets) adds a lot of customization to HTML.

​By itself, HTML resembles the plain websites of the 90s. CSS gives coders a lot more options. As a matter of fact, CSS Zen Garden illustrates all of the different ways CSS can change the appearance of a website, even if the HTML stays exactly the same!

​CSS also has all of the advantages for teaching kids coding languages that HTML does, including the fact that you only need a text editor and a web browser in order to code using CSS.

​CSS is not a programming language — it would be most accurately be classified as markup. But, like HTML, CSS is still heavily used by the world and is not in danger of going away any time soon.

​In fact, certain functions previously available only in JavaScript are now available in CSS. Its popularity has probably never been greater. For these reasons,  consider HTML as a kids coding language.

​2. ​JavaScript

​JavaScript is one of the languages mentioned most when it comes to web development. What is JavaScript exactly?

​Unlike HTML/CSS, JavaScript is a scripting language. In other words, JavaScript has many (if not all) of a programming language, but instead of using a compiler, it uses an interpreter to convert its syntax to machine code.

​You see, coders must convert all programming and scripting languages to a machine language to run them.

​Interpreted languages do this as the program is running, not needing an additional step to translate the language.

​The major downside to this process is that it slows the computer down a bit when compared to compiled programs, but this slowdown isn’t enough to affect any coding, especially at the student level. JavaScript is still plenty fast enough for the average student. (Find an excellent tutorial for JavaScript at w3schools.)

​Meanwhile, compiled programs take an extra step to run. The student must code the program, then the compiler compiles it and checks for errors, and finally, the program runs. This process may be counterintuitive for most students and involves a step in which nothing happens, which kids see as boring. In this article, we will not recommend programming languages that require a compile step as a kids’ coding language.

Advantages of JavaScript

​JavaScript is an interpreted language, which is an advantage in teaching it. What other benefits does JavaScript have over other languages when considering it for the classroom?

​Well, like HTML/CSS, JavaScript is used by nearly every browser to create functionality on websites. Anytime you see an effect on a website or play a browser game, the language used to create it is almost certainly JavaScript.

vector graphic of smiley programming with laptop

​Source: Pixabay

​Also, like HTML/CSS, a coder can program with JavaScript using just a web browser and a text editor. So, you don’t have to worry about installing a lot of extra software. Some examples of great usage of JavaScript can be found at CreativeBloq.

​However, unlike HTML, for a student to truly become proficient in JavaScript, they will need some skills in mathematics. While basic Algebra may be enough for a talented student to understand the syntax, the student should at least be familiar with Geometry, and possibly even more advanced Mathematical principles. JavaScript is more demanding than HTML/CSS and should be treated accordingly. Even so, it is worthy of consideration as a kid’s coding language.

​Also, JavaScript doesn’t reward the coder quite as quickly as HTML/CSS does. With HTML, large results generally originate from small amounts of code. With JavaScript, small results typically originate from small amounts of code.

​For example, with HTML/CSS, it is relatively easy to change the background color of the browser with one line of code. But with JavaScript, it takes a lot of effort by a kid coding (and debugging) to create something simple in the language, like a number-guessing game.

​So why teach JavaScript at all? Well, JavaScript shares a lot of syntax with advanced coding languages, unlike HTML/CSS.

JavaScript was created using a patchwork of commands from C, C++, and Java(which is an entirely different programming language). So learning JavaScript will give a student some insight as to how other computer languages work.

​However, JavaScript tends to be more forgiving of errors than many programming languages, so there won’t be as much frustration for students. As long as your kids are of the appropriate skill level, JavaScript is an excellent choice as a coding language for them to learn.

​3. ​​​PHP

At first glance, PHP doesn’t appear to belong on this list. It is an interpreted language, like JavaScript, but unlike JavaScript or HTML/CSS, PHP generally focuses on databases and server management.

​While important, databases and server management will generally bore kids to tears, which has the possibility of making them hate coding languages and perhaps even your class (perish the thought!).

​However, PHP has gained several graphics tools over the years and now can incorporate HTML, CSS, and JavaScript in its framework. Now, PHP is used for substantially more than databases, although it still excels at those tasks. So, if a kid wants to create the next Facebook, they could do worse than starting by learning PHP as a coding language.

PHP and WordPress

​PHP has also taken on an added importance for kids as well as adults because it is the primary coding language that powers WordPress. WordPress is a website CMS (or Content Management System) that also allows users who are not familiar with HTML to build their websites.

​WordPress has become more and more popular in the last few years, and all students should probably at least know WordPress basics, which require no math and are relatively easy to pick up.

​Nearly all WordPress sites and applications are written in PHP, and WordPress is so vital that you should include PHP in your curriculum due to that fact.

WordPress logo on a bicycly

​Source: Pixabay

​Many articles and opinions state that the future of websites is in WordPress. If that is the case, then the future is inarguably PHP, and teaching this language to your students will make life easier for them later.

​Unfortunately, unlike the previous kids’ coding languages we have covered, PHP is only available as a download. So you must either download PHP on every student’s computer or allow them to do it themselves.

​As mentioned before, I highly recommend that you or an aide download PHP onto the students’ computers as opposed to allowing them to do it themselves. The download is free at PHP.net.

​Complications of PHP

PHP is more complex than the other kids’ coding languages listed here. It would be a good idea if your students already had training in HTML, CSS, and JavaScript before attempting to learn PHP.

​Perhaps, you could include a small amount of PHP for kids when teaching a WordPress class, or at the end of a course in HTML/CSS and JavaScript. While useful, a PHP coding language class on its own may be a bit too much for most students.

​PHP also requires a solid understanding of math. Algebra almost certainly is necessary, but PHP may also require the equivalent of an Algebra II class for kids, to truly master the coding language. PHP requires a high-school level or above understanding of math, along with some maturity and patience.

​As you can see, there are many options available for instructors who wish to teach their students how to code. From a simple HTML web page to a complicated JavaScript program, there are many levels of difficulty available for the teacher who wishes to challenge, but not frustrate, their students.

​However, the importance of teaching coding to young people cannot be denied. Across the world, coding is taking on more and more significance as humanity relies on computers for even the most mundane tasks.

​Make sure to teach your students coding, if you can. They may not always enjoy it now, but they will benefit from it later.

​​​​Honorable Mention: Python

Suppose you have a class of gifted students, and you feel that teaching them JavaScript or PHP wouldn’t be enough of a challenge for them.

​Although both of those languages can get very challenging in some of their tasks, I would recommend teaching them a language like Python. Python differs from the languages listed here in many ways but definitely is a viable language to teach advanced high schoolers.

​For example, Python is an interpreted language, just like JavaScript. So, like JavaScript, your students won’t have to wait for a compiler in order to run a program. Unlike the languages listed above, though, Python is much more versatile.

​Many programs, from Dropbox to some Call of Duty games, run on Python. This popularity stands in contrast to PHP—generally used for internet content—and JavaScript—usually used for small applications. Python can be used for pretty much anything.

​One note about python syntax (the way the language is structured). Unlike JavaScript, CSS, and PHP that use braces to separate commands and functions, Python uses indentation. Indentation makes it more challenging to keep the code clean if your students tend to be sloppy (as many kids tend to be).

Python programming codes

​Source: Pixabay

​If your students tend to be more disorganized, you may want to consider teaching them JavaScript or a kid’s coding language that makes it easier for them to keep things neat.

​Also, mastering Python requires quite a bit of math, so I would recommend that any student who wishes to learn Python be required to know Algebra at the very least.

​Even simple concepts such as variables may go over the heads of students who are not conversant in Algebraic ideas. The last thing we as educators want to do is to throw kids into the deep end of the metaphorical pool and let them struggle with a coding language. Proper background learning is necessary for anyone to succeed in any endeavor.

​Python is not impossible to learn, however. Unlike many other computer languages, Python accommodates different learning styles. If your students cannot wrap their heads around object-oriented programming, then you can try a different tactic. The language can work with you.

​Also, Python is known for being more forgiving of kids’ errors than certain other coding languages, and it is written in English syntax. More information can be found regarding Python as a kids’ coding language at CodeWizardsHQ.

​​​Get Your Kids into Coding!

boy using computer

​Source: Pixabay

​Once again, no matter which language you decide to choose, the important thing is to get your students coding! From HTML to Python, coding will teach your students valuable skills that will accompany them through life. The time to start teaching them is now.

Filed Under: Foundation

National Skills Registry: Everything You Need To Know

June 12, 2019 by itadmin Leave a Comment

One of the most difficult challenges for any business is filling skilled worker positions in the company. Success requires the right mix of skills. Any gap or weakness in skill, experience, expertise, and technical proficiency can hold the business back and keep it from gaining new work.

A challenge for any worker is letting prospective employers know the skills and experience you bring to a position. Looking for a new job often requires finding an edge or attracting attention to those critical skills you offer. Many times, you can lose out on the perfect job, not because you lack the skills or experience, but because the employer did not know you had them.

The National Skills Registry (NSR) works to solve these challenges through a managed database of credible information about the skills and expertise of the people working in the industry. Both potential employees and companies can use the NSR to connect workers with businesses that need them and build trust in the industry.

What is the National Skills Registry?

National Skills Registry Website

The National Skills Registry is owned and managed by the National Database Management Limited (NDML), which is a fully-owned subsidiary of the National Securities Depository Limited (NSDL).

NDML manages the National Skills Registry for NASSCOM, the National Association of Software and Services Companies. NASSCOM is a trade association for Indian Information Technology (IT) and Business Process Outsourcing (BPO) with more than 2000-member companies across the world.

NASCOMM focuses not only on promoting IT and BPO services, software development, and software services, but also on improving the service quality, talent recruitment outcomes, and level of service offered by IT and BPO companies. By improving the level of service quality, the organization can further promote member organizations and develop global trade.

The NSR helps in this mission by ensuring companies are hiring only the best-qualified employees for critical positions in IT and BPO.

NSDL designs, implements, and manages large databases across India, and specializes in data security. Security is critical in maintaining the NSR database.

Included in the National Skills Registry

The registry provides information on IT and BPO professionals. This information includes a sheet with background check reports that help ensure the identity of prospective employees.

The fact sheet includes the resume, qualifications, certifications, career information, and personal information — such as photo identification — for each registered professional.

Only the registered user can load information into the system. Likewise, only the user can modify the information included. Employers can verify information on their employees, but cannot change the information.

Any participating company can then authorize verification of the information in the fact sheet. Both the company and the user will be notified of the results of the verification.

Only the employer of a user or an authorized company can access the information. All access to the information is logged in the system. The NSR strives to keep your information completely confidential.

How to Use the National Skills Registry

Keyboard with Register word

The Registry includes features for both sides of the hiring and employment coin. We have included information about NSR registration for professionals who create profiles and businesses that become subscribers to use the NSR.

Registering Your Profile in the National Skills Registry

For the individual seeking work, the process for registering is not difficult:

  1. Create a National Skills Registry Profile: Go to the National Skills Registry website (www.nationalskillsregistry.com) and create a profile by clicking “Register for NSR.” When prompted, you’ll need to include the details of the company that has asked you to register. Enter credible and verifiable information in your profile. Be sure to include a resume and job history, as well as any certifications and schooling you may have earned. Keep the given password for access your profile later. Be aware that there is a fee for registering.
  2. Biometric Registration: All profiles in the NSR include biometrics to support the validity and credibility of the professional. You will need to visit a Point of Service (POS) center to record your biometrics and conduct the identity check. You can find a list of POS centers on the main website. Again, a fee is included.
  3. Proof of Identity: You will need to bring photo proof of identification to the POS center. This could include a passport, driver’s license, or a college ID card. You’ll also need an employer ID card if you have one. The Photo ID you provide is included in your profile.

Post-Registration

Once you have registered, you will receive an identification number, called an ITPIN, that gives you access to your profile.

From your profile, you should continue to update your personal information. Add new jobs or job skills when you receive them. If you continue education and certification programs, document these instances in your profile as well.

You can update your personal information when needed. It is up to you to maintain and update the profile with factual and correct information. Never let your profile become ridden with out-dated information.

You can also use the system to authorize anyone with access to your profile, including a prospective employer. You will have a complete record of who accessed your profile and the status of any background checks or verifications completed in your name.

There is a yearly fee for the use of the National Skills Registry. You will lose access to your profile if you do not pay the fee.

How Companies Can Use the National Skills Registry

The National Skills Registry connects workers in the IT or BPO industry with hiring companies. Businesses can use the NSR as a reference for hiring, accessing information on client assignments, or as a background check for a prospective employee. It is a quick and secure way to make sure you are hiring the right people.

The information included in a profile will cover the resume of a prospective employee. You will also find personal information including a photograph, qualifications, and career information. The system will provide source verification when requested to ensure the accuracy of information.

A company will need to subscribe to use the Registry, which does cost a fee. Once you are registered, you will have access to the full benefits of the NSR, which include:

Accurate and verified resumes

All facts on an applicant’s resume are verified. Within the system, you can see precisely how facts were verified and cross-checked to determine where and how discrepancies in the information were identified. You can also see any pending verifications, remarks, or notes.

User Access

You can assign Admin and Functional Users to your subscriber account. This will allow you to limit access to confidential employee information while still getting the full benefit of the NSR for authorized users.

Standard information

The registry promotes standard information on all resumes, ensuring transparency on applications and the ability to more accurately compare applicants.

Quick confirmation of an applicant’s credentials

With the system managing verification, you can quickly check the profile of an applicant to eliminate time spent with an unqualified person.

Once your business becomes a subscriber—either through membership in NASSCOM or when approved by the NSR—you should begin registering your existing employees and all job applicants. This will give you a permanent, credible profile for your employees. The profile also serves as a record of employment and an easy place to update new skills and experience.

Concern for Security

There continues to be some concern about the privacy and data security of the NSR. The system holds the biometric information of more than 1.6 million registrants and provides subscribers access to that information.

There is a risk for abuse, especially since employers have access to verify and comment on employee information. A sense of courtesy and professionalism are essential to implementing the system in a positive way.

If professionals and companies use the National Skills Registry as intended, it can help build a connection between companies and provide a greater sense of trust in the companies included.

Getting the Most from the National Skills Registry

Gadgets

This database is a powerful tool for professionals in the IT and BPO industries, as well as software developers, network services, software services, e-commerce, and related technical fields. The web-based tool gives an objective perspective on service professionals.

It’s also an excellent way to increase the credibility of companies. Once you have your employees registered, clients and customers can verify the skills and experience of the people working for them.

The record and experience of work of each professional included in the registry have been verified. Companies reviewing applicants and businesses know the importance of verification. It increases trust and professionalism in the industry and benefits everyone.

Filed Under: Java

IntelliJ vs Eclipse: Which To Use For Java Development

June 11, 2019 by itadmin Leave a Comment

When coding a program in Java, deciding on the language to use is only half the battle. The programmer must decide which IDE (or integrated development environment) works best for the job. The undertaking of large projects in Java requires the use of an IDE.

The right IDE can perform invaluable tasks like decompiling files. Usually, the IDE includes a code editor, a Java compiler (which is usually faster than the compiler included with Java), and a debugger. The popular comparison of “IntelliJ vs Eclipse” deserves a thorough discussion.

Java logo

These tools are accessed through a Graphical User Interface (GUI) that helps coders finish tasks quickly and efficiently. A competent IDE will help a coder immensely when dealing with any programming challenges.

Two of the most well-known Java integrated development interfaces out on the market are Eclipse and IDEA. While the two IDEs couldn’t be more different in many respects, both development spaces have positive and negative attributes that affect a Java project developed within them.

This article will examine both IDEs in depth to consider which development space, IntelliJ vs Eclipse, is right for your project.

Eclipse

First, let’s examine Eclipse. Created back in 2001, Eclipse was one of the first IDEs developed in Java. This IDE is one of the most popular (if not the most popular) program for Java. Eclipse is open-source, which is great news for Java programmers on a budget.

Eclipse Logo

Positives:

At least to an extent, open-source software is generally free to all users. Even better, anyone with a computer and some expertise can create plug-ins or write code to implement new features or make the IDE run more efficiently.

In other words, while an “official” Eclipse update is released every June, programmers are continually writing plug-ins for the IDE. Considering all of that support, it’s highly unlikely that a bug or issue that a programmer has with Eclipse would be unsolved for long.

Eclipse has a number of other features that make it worth considering. For example, one helpful feature is “UI Monitoring.” How many times have programmers experienced a system slowdown or even a system hang when programming? With Eclipse, you can monitor just what process is causing the problem and can easily cancel it if necessary.

A new feature for this year’s Eclipse update is expanded Rust support, along with support for building Java 10 and Java EE 8 based applications out of the box. A multitude of improvements to themes have been included.

Eclipse has excellent Git support. Instead of having to drop to the command line in order to use Git Flow, you have access to all the features right from the Eclipse UI.

If you don’t know what Git is, you should. Git is the most popular version control software in the world. It was originally developed as version control for UNIX and has mushroomed into something bigger.

Git is easy to use, is lightweight, and basically ensures that every member of your team is on the same page. In short, it’s a good idea to use Git on a large project, and the fact that Eclipse is so compatible with it is wonderful.

Negatives:

Despite all the pros of the program, there are some issues with Eclipse that need to be taken into consideration. First of all, due to Eclipse’s architecture, it is usually slower and less responsive than other IDEs.

Eclipse compiles in the background while you’re working. This is great when it comes time to compile the program. The environment can seem sluggish while coding because of this. You should remember this lag when considering Inellij vs Eclipse.

According to Slant, the plug-in system for Eclipse introduces several incredibly useful features, such as the ability to use Eclipse in other programming and scripting languages, like C++.

Java Eclipse Platform

These features are plug-ins and do not come pre-installed. You don’t need to install the plug-ins and have them take up memory if you have no intention of using them.

However, if you do choose to install the plug-ins, you have to be careful. Eclipse plug-ins can conflict with each other. If two plug-ins cause a significant conflict, the entire programming environment may freeze or crash.

Also, if the coder installs too many plug-ins, Eclipse can get bogged down and become practically unusable. Make sure to use plug-ins with prudence and restraint.

IDEA

IDEA has few of the issues Eclipse does. Also developed in 2001, this IDE has been available for quite a while. Jetbrain, formerly known as IntelliJ, mainly developed IDEA as one company. However, Jetbrain has made a version of IDEA open-source, so that users can try it and alter it for free.

intellij vs eclipse

Please note that Jetbrain does charge for the IDEA Ultimate Edition, which includes a number of web applications and opens the number of languages IDEA uses. The price of the Ultimate Edition varies but can be high. However, as Javaworld points out, the expense can be worth it.

Make sure to check recent pricing on the Jetbrain website before you opt for the Ultimate Edition of IDEA as your IDE solution for Java. Pricing can be another factor in the IntelliJ vs Eclipse decision.

IntelliJ Logo on blue surface

Positives:

If you decide to use Eclipse, you should be comfortable with participating in forums to get answers to questions. Most programmers are used to doing this by now, but occasionally, going on forums to get responses can be a bit troublesome. When looking at IntelliJ vs IDEA, this tendency is another positive for IDEA.

IDEA also has plug-ins, but they are not as numerous or as useful as those available to Eclipse users. However, as adherents of IDEA point out, the base development environment in IDEA has functionality that can only be imparted by a plug-in when using other environments.

IDEA’s environment runs faster than Eclipse. IDEA generally does not have any issues with the plug-ins that are available to it. There is no need to worry about plug-ins having conflicts or even crashing the development environment as you would in Eclipse. IDEA does not compile in the background as you code, which also helps it run smoothly.

Another benefit to using IDEA is that documentation tends to be fairly easy to find and up-to-date, due to the fact one company manages it. Meanwhile, with Eclipse, documentation may lag implementation of features by several months.

Computer Settings for Plug-Ins

IDEA also includes Git integration, and some Git-specific features are especially noteworthy. For example, when working with Git, it’s much easier to find files with merge conflicts than it used to be.

IDEA groups these files under a Merge Conflicts mode for each changelist. All you have to do to fix any issues caused by a merge conflict is to click the Resolve action link. Clicking will open the Files Merged with Conflicts dialog, and you will be able to fix the merge conflict.

The latest version of IDEA aids the user in helping to resolve Git conflicts. It now displays Git branch names in a Files Merged with Conflicts dialog when you perform a pull, merge, or rebase. When using this dialog, you may group files by directory, which should come in handy if there are multiple files merged with conflicts.

Another feature for IDEA to note is a preview panel for Extract Method refactoring. This preview allows you to see what the results of your refactoring will look like before confirming the changes. Refactoring can be extremely useful when trying to achieve an easy-to-read code base. If you have a lot of duplicated fragments in your code, previewing your Extract Method refactoring can save a lot of time and hassle.

Negatives:

Despite the many positives included, IDEA is seen as lacking in plug-ins. If there is a specific functionality that you need for a particular Java project, you may want to check and make sure it is supported before choosing to use IDEA.

IntelliJ vs Eclipse? You Choose

As you can see, both Jetbrain’s IDEA and Eclipse are valid IDEs for programming in Java. However, they do have very different strengths and weaknesses.

IntelliJ logo Eclipse logo

When considering IntelliJ vs Eclipse, keep in mind that Eclipse is well-supported and has been open-source for much longer than IDEA. Its plug-ins provide flexibility that IDEA still can’t match, even though the makers of IDEA recently made it open-source as well.

However, Eclipse’s documentation lags its latest release. Depending on the plug-ins chosen, Eclipse can run slowly compared to other IDEs.

IDEA, however, tends to run faster than Eclipse does. Documentation is generally up-to-date, which is an advantage for anyone who doesn’t have time to go on forums to get answers to questions.

IDEA doesn’t have as many plug-ins as Eclipse does. However, according to the internet, IDEA is more stable than Eclipse. For these reasons, if considering IntelliJ vs Eclipse, you would do well to choose Jetbrain/IntelliJ’s IDEA as your Integrated Development Environment for your next project.

Filed Under: Java

Beginner’s Guide – Java vs. C++ Which Of This Two Should I Learn?

January 10, 2019 by itadmin Leave a Comment

When it comes to coding, there are tons of languages to choose from. Students new to coding can choose between high-level languages like Python and low-level languages like C or C++.

But which is the best one to start with? Every professional programmer on the planet made a choice like this one at the beginning of their academic career. It may be the first and most important choice that any future programmer has to make.

In many situations, the list of potential first-time coding languages narrows down to two options: Java and C++. The most significant reasons for this revolve around the nature of each language as it pertains to the tech industry as a whole:

  • Java is a hugely popular general-purpose programming language designed to run on nearly any device. It the language of choice for client-server web applications, with 9 million developers using the platform for this purpose.
  • C++ is a low-level programming language commonly used for large software infrastructure projects and for embedded software projects. It offers a more versatile environment suitable for achieving a wide range of programming goals.

 

Identify Your Goals Before Choosing Between Java vs. C++

Two woman working using a laptop

It’s impossible to say whether you should choose between Java or C++ without focusing on your long-term goals. These goals will define which aspects of each language – and later languages you are likely to learn – are the most useful and attractive.

Both Java and C++ programmers make six-figure incomes on average. While there is generally more overall demand for Java, C++ is a fixture of some of the largest and most important institutions on the planet, and it’s a powerful platform for increasing your overall career prospects as a programmer.

To be clear: learning a programming language cannot limit your opportunities, so there is no structural reason why a programming student cannot learn both Java and C++ at the same time. However, focusing on one at a time can be more practical for anyone who doesn’t have the luxury of an unlimited timeframe to learn.

Both of these programming languages have important applications in the tech industry and beyond. Finding out what they do best can be a great help when choosing between them.

Where Java Can Take You

When programmers think of Java, they often think of the following things:

  • Application servers
  • Web applications
  • Mobile applications
  • Desktop and enterprise applications

However, there are many other uses for Java and for languages related to Java. Cross-language development applications like JNBridge allow Java developers to leverage their Java experience even when not working on purely Java-based applications.

Java’s ability to work anywhere makes it a powerful skillset in dynamic environments where lots of users need access to high-level functionalities. This makes Java a great tool for coding cloud-based applications, e-commerce web portals, and customized mobile apps.

Java is also one of the languages of choice for unit testing. Unit testing is the process by which software objects emulate real-world ones in a test environment, passing or failing according to the desired outcome of the object’s activity. Java programmers can learn to do this for robotic and Internet of Things (IoT) applications.

IoT is an important area of Java development. While the industrial side of IoT development is usually covered by lower-level languages, Java is one of the languages of choice when it comes to IoT user interface development, wearable tech applications, and other smart technologies.

Java is also an important language for mobile and browser-based gaming. Android relies on Java for a broad range of games, and some of its most popular apps. But if you want to develop games for console platforms and PC, then C++ is the best place to start.

Java is structurally similar to Ruby, which is an in-demand language for quickly building websites and web applications. The Ruby on Rails framework reduces the amount of time programmers have to spend writing repetitive code by offering a set of agreed-upon conventions that allow for speedy development.

Where Can C++ Take You

Most programmers would agree that being well-versed in C++ is a great foundation for further development in the tech industry. C++ is a lower-level, more fundamental programming language that requires more work (for some) to learn and master than Java.

C++ is the language of choice for a few very important applications:

  • Large, institutional applications like those used by banks, governments, and other institutions.
  • Embedded software designed to operate robots, satellites, consumer electronics, and other hardware devices.
  • Graphics-intensive video games and scientific applications.

C++ is the older of the two languages, and much of Java’s syntax is borrowed from the C++ mindset. While some may find it takes longer to learn, it offers a more robust foundation for further learning. For instance, learning Java is simple for someone who is already familiar with C++, but the opposite is not true.

C++ is part of some of the world’s biggest and most respected brands. Bjarne Stroustrup, the inventor of C++, maintains a list of some of these companies, which include Adobe, Amazon, Apple, Facebook, Google, and more.

Stroustrup’s list illustrates a key difference between Java and C++. Whereas Java is an easy language to learn and write in, which reduces development time, C++ produces the leanest and most effective code for high-impact applications. This is why Lockheed-Martin uses it for mission-critical airplane software – they can afford to keep a C++ programmer busy.

Compared to almost every other language, C++ costs more in terms of development time and costs much less in terms of operational expenses. Programs written in C++ tend to use computer resources more efficiently than those written in Java or other languages. Part of the reason is that C++ programmers can actively route and sort memory threading pathways in ways that other languages don’t support.

Programmers with experience in C++ are more likely to be part of huge projects with large teams in an enterprise environment. In this type of environment, a completed project can easily take up more than a million lines of code, and it’s not uncommon to reach five, six, or even ten million lines. The resulting programs are solid, valuable tools that offer key completely customized functionality to users.

 

Java vs. C++: Long-Term Goals for New Programmers

Man using a laptop

Different types of people will find themselves suited to each of these languages for different reasons. For instance, someone who likes the idea of being their own boss and working as a freelance mobile application developer will have a lot more success with Java than with C++.

However, that same person may be able to leverage their knowledge of C++ to learn a complimentary language like Perl or Python, vastly improving their marketability in a competitive economy.

Most professional computer programmers know multiple languages. It’s very common for programmers to learn new languages on-the-fly when working on projects that require them – experienced developers can become “fluent” in a new computer programming language in a few weeks.

This is an ingrained part of the tech industry. It’s not uncommon for a professional C++ programmer working on a large project to work on a user interface written in Java, reporting to a database written in PHP, and generating reports in HTML and CSS. Each one of these program interfaces gives the entire team a little bit more knowledge of the other programming languages involved.

 

Learn New Languages On a Needs-Oriented Basis

3 People looking at the laptop

One of the best pieces of advice that new programming students can take to heart is to treat new languages as the tools they are. Learning a programming language for fun is interesting at first, but won’t produce a sustainable environment for cultivating professional skills in the long run – not on its own, at least.

Students who learn new programming languages on a needs-oriented basis position themselves to gather the most useful information for their goals in an efficient, results-oriented way.

This means that instead of comparing Java vs. C++ as your first programming language, you may be more successful by asking yourself what kinds of programs you want to make:

  • If you want to build a web scraper capable of handling lots of data, learn Python or Java.
  • If you want to write mobile applications, focus on Java or Apple’s Swift.
  • If you’re into PC and console-based video games, start with C++.
  • If you want to analyze lots of data or write machine learning programs, learn Python or R.
  • If writing embedded systems to make hardware function fascinates you, go for C++.
  • If you want to enter the world of IoT development, rely on either Java or C++ to take you there.

By focusing on the results of your programming skills, you will conveniently sidestep the risk of spending time and energy learning skills you end up rarely using. You will have a clear path towards determining which language is the best fit for your needs and be able to start down the path of becoming a professional programmer.

Filed Under: Java

JQueryUI Selectable Widget Example

November 13, 2014 by itadmin Leave a Comment

jQueryUI provides selectable widget which allows selecting elements individually or in group elements by using the mouse. It also possible to select elements with the mouse hovering on the elements by dragging a box. Elements can be selected by clicking on the element or by dragging the element and also allows selecting of multiple elements on the webpage. Hold down the Ctrl key to select the multiple elements.

also read:

  • JQuery Keydown, Keypress and Keyup
  • JQUery Setting Drop Down Value
  • JQuery prepend() and prependTo()

The selectable method can be used in the following forms:

  • $(selector, context). selectable (options)
  • $(selector, context). selectable (“actions”, [params])

The following example demonstrates a simple example of selectable widget:

[code lang=”xml”]
<!DOCTYPE html>
<head>
<link href="http://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel="stylesheet">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<style type="text/css">
#selectMe {
list-style-type: none;
margin: 0;
padding: 0;
width: 100px;
}
#selectMe .ui-selected{
background: orange;
}
.myList {
background: gray;
border: 1px solid cyan;
}
</style>
<script>
$(function(){
$("#selectMe").selectable();
});
</script>
</head>
<title>JQueryUI Example</title>
<body>
<h2>Select the Countries</h2>
<ul id="selectMe">
<li class="myList">India</li>
<li class="myList">Srilanka</li>
<li class="myList">Australia</li>
<li class="myList">South Africa</li>
<li class="myList">China</li>
<li class="myList">Japan</li>
<li class="myList">Italy</li>
<li class="myList">France</li>
<li class="myList">Canada</li>
<li class="myList">Brazil</li>
</ul>
</body>
</html>
[/code]

  • The above simple script defines selecting elements individually or in group elements by using the mouse. It selects elements by dragging a box.
  • When we click on the element or dragged the elements, the color will get change to orange color which indicates the selected elements in the list.

Run JQueryUI Simpe Selectable Demo

JQueryUI Simple Selectable Example

Selectable Widget Options

The selectable method contains following options:

Option Description Default Value
appendTo It appends the specified element while selecting. body
autoRefresh The position and size of selectable elements should be refreshed or not at the beginning of selection when it is set to true. true
cancel It is used to cancel the selection operation on the specified element . input, textarea, button, select, option
delay It specifies the delay time in milliseconds when selection operation starts. 0
disabled It disables the selection of elements when it is set to true i.e. it stops selecting the elements. false
distance It determines the displacement when selection of elements should start in the form of pixels. 0
filter It determines which elements will be made able to be selected or can be made part of the selection. *
tolerance It is used for testing whether the selection helper should select an item. touch

The following example demonstrates usage of delay and distance options:

[code lang=”xml”]
<!DOCTYPE html>
<head>
<link href="http://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel="stylesheet">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<style type="text/css">
#selectMe1,#selectMe2{
list-style-type: none;
margin: 0;
padding: 0;
width: 100px;
}
#selectMe1 .ui-selected, #selectMe2 .ui-selected{
background: orange;
}
#selectMe1 .ui-selecting, #selectMe2 .ui-selecting{
background: red;
}
.myList {
background: gray;
border: 1px solid cyan;
}

</style>
<script>

$(function(){
$("#selectMe1").selectable({
delay: 500
});
$("#selectMe2").selectable({
distance:100
});
});
</script>

<title>JQueryUI Example</title>
</head>
<body>

<h2>Starts after Delay of 500ms </h2>
<ul id="selectMe1">
<li class="myList">India</li>
<li class="myList">Srilanka</li>
<li class="myList">Australia</li>
<li class="myList">South Africa</li>
</ul>
<h2>Moves after the distance of 100px</h2>
<ul id="selectMe2">
<li class="myList">China</li>
<li class="myList">Japan</li>
<li class="myList">Italy</li>
<li class="myList">France</li>
<li class="myList">Canada</li>
<li class="myList">Brazil</li>
</ul>
</body>
</html>

[/code]

  • When we run the above script, we will get two parts of list of country names i.e. one for delay option and another for distance option.
  • The delay option specifies time in milliseconds when selection operation starts. Here, we have defined 500ms i.e. we can select the elements after the 500 ms.
  • The distance option determines the displacement when selection of elements should start in the form of pixels. In the script, it’s defined as 100px i.e. we can starts selecting the elements after mouse moves distance of 100px.
  • These two options uses particular ID selector and also for using different CSS styles which display the result with specified values.

Run JQueryUI Selectable Options Demo

JQueryUI Selectable Options Example

The following example shows usage of cancel option:

[code lang=”xml”]
<!DOCTYPE html>
<head>
<link href="http://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel="stylesheet">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<style type="text/css">
#selectMe{
list-style-type: none;
margin: 0;
padding: 0;
width: 100px;
}
#selectMe .ui-selected{
background: orange;
}
.myList {
background: gray;
border: 1px solid cyan;
}
.blocked {
background: green;
border: 1px solid cyan;
}
</style>
<script>
$(function(){
$("#selectMe").selectable({
cancel: ".blocked"
});
});
</script>
</head>
<title>JQueryUI Example</title>
<body>
<h2>Starts after Delay of 500ms </h2>
<ul id="selectMe">
<li class="myList">India</li>
<li class="myList">Srilanka</li>
<li class="myList">Australia</li>
<li class="myList">South Africa</li>
<li class="myList">China</li>
<li class="blocked">Japan</li>
<li class="myList">Italy</li>
<li class="blocked">France</li>
<li class="myList">Canada</li>
<li class="blocked">Brazil</li>
</ul>
</body>
</html>
[/code]

  • The script uses option called cancel which stops selecting the elements with matching selector.
  • We have used the class blocked, which specifies the blocked elements where we can’t able to select the element and these elements are displayed with green background color.

Run JQueryUI Selectable Options Demo1

JQueryUI Selectable Options Example1

The following example demonstrates usage of filter option:

[code lang=”xml”]
<!DOCTYPE html>
<head>
<link href="http://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel="stylesheet">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<style type="text/css">
#selectMe{
list-style-type: none;
margin: 0;
padding: 0;
width: 100px;
}
#selectMe .ui-selected{
background: orange;
}
.myList {
background: gray;
border: 1px solid cyan;
}
.myClass {
background: green;
border: 1px solid cyan;
}
</style>
<script>
$(function(){
$("#selectMe").selectable({
filter: "li:not(.myClass)"
});
});
</script>
</head>
<title>JQueryUI Example</title>
<body>
<h2>Starts after Delay of 500ms </h2>
<ul id="selectMe">
<li class="myList">India</li>
<li class="myList">Srilanka</li>
<li class="myList">Australia</li>
<li class="myList">South Africa</li>
<li class="myList">China</li>
<li class="myClass">Japan</li>
<li class="myList">Italy</li>
<li class="myClass">France</li>
<li class="myList">Canada</li>
<li class="myClass">Brazil</li>
</ul>
</body>
</html>
[/code]

  • The script uses filter option indicates which elements can be part of the selection.
  • When we run the script, we could select the all the elements except the elements which are related to the class myClass.
  • The matching elements child elements will be made selectees and the elements which are defined within the class myClass will not get selected and these are displayed within green background color.

Run JQueryUI Selectable Options Demo2

JQueryUI Selectable Options Example2

Selectable Widget Methods

The following table shows some of the methods which are used with selectable widget:

Method Description
destroy() It removes the selectable functionality .
disable() This method disables the selectable operation.
enable() This method enables the selectable operation.
options() It returns the options property. It sets selectable operation with specified option name.
refresh It refreshes the position and size of the selected elements.
widget()</ It defines selectable element with jQuery object.

The following example demonstrates usage of disable and option methods:

[code lang=”xml”]
<!DOCTYPE html>
<head>
<link href="http://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel="stylesheet">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<style type="text/css">
#selectMe1, #selectMe2{
list-style-type: none;
margin: 0;
padding: 0;
width: 100px;
}
#selectMe1 .ui-selected, #selectMe2 .ui-selected{
background: orange;
}
#selectMe1 .ui-selecting, #selectMe2 .ui-selecting{
background: red;
}
.myList {
background: gray;
border: 1px solid cyan;
}
</style>
<script>
$(function(){
$("#selectMe1").selectable();
$("#selectMe1").selectable(‘disable’);
$("#selectMe2").selectable();
$("#selectMe2").selectable("option", "distance", 1);
});
</script>
</head>
<title>JQueryUI Example</title>
<body>
<h2>Using Disable Method</h2>
<ul id="selectMe1">
<li class="myList">India</li>
<li class="myList">Srilanka</li>
<li class="myList">Australia</li>
<li class="myList">South Africa</li>
</ul>
<h2>Using Options Method</h2>
<ul id="selectMe2">
<li class="myList">China</li>
<li class="myList">Japan</li>
<li class="myList">Italy</li>
<li class="myList">France</li>
<li class="myList">Canada</li>
<li class="myList">Brazil</li>
</ul>
</body>
</html>
[/code]

  • The above script uses selectable methods disable and option.
  • The disable method disables the selectable elements which does not accept any arguments.
  • The option method returns the options property. It sets the selectable operation with specified option name. In the script, we are using distance option which determines the displacement when selection of elements should start in the form of pixels.
  • Both the methods uses particular ID selector to define different CSS styles, when they will get appear on the webpage.

Run JQueryUI Selectable Methods Demo

JQueryUI Selectable Methods Example

Selectable Widget Events

The following table shows events which are used with selectable widget:

Event Description
create(event, ui) It fires when selectable element is created.
selected(event, ui) It fires when each element selected.
selecting(event, ui) It fires when each element is about to get selected.
start(event, ui) It fires when selectable operation starts.
stop(event, ui) It fires when selectable operation ends.
unselected(event, ui) It fires when each element is unselected.
unselecting(event, ui) It fires when each element is about to get unselected.

The following example demonstrates usage of selected event:

[code lang=”xml”]
<!DOCTYPE html>
<head>
<link href="http://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel="stylesheet">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<style type="text/css">
#selectMe{
list-style-type: none;
margin: 0;
padding: 0;
width: 100px;
}
#selectMe .ui-selected{
background: orange;
}
.myList {
background: gray;
border: 1px solid cyan;
}
</style>
<script>
$(function(){
$("#selectMe").selectable({
selected: function(event, ui){
var selected=$("li[class$=’ui-selected’]").length;
$("#myval").html("you selected " +selected+ " countries");
}
});
});
</script>
</head>
<title>JQueryUI Example</title>
<body>
<h2>Using Selected Event</h2>
<ul id="selectMe">
<li class="myList">India</li>
<li class="myList">Srilanka</li>
<li class="myList">Australia</li>
<li class="myList">South Africa</li>
<li class="myList">China</li>
<li class="myList">Japan</li>
<li class="myList">Italy</li>
<li class="myList">France</li>
<li class="myList">Canada</li>
<li class="myList">Brazil</li>
</ul><br>
<span id="myval" style="color:green;">selected 0 countries.</span>
</body>
</html>
[/code]

  • The script makes use of selectable option called selected which fires when each element is selected in the list.
  • When we selecting the elements from the list, we will get statement, for instance “Selected 2 countries” like this it will go on increasing the numbers while selecting the elements.

Run JQueryUI Selectable Events Demo

JQueryUI Selectable Events Example

Filed Under: jQuery Tagged With: JQuery Events

  • 1
  • 2
  • 3
  • …
  • 6
  • Next Page »

Follow Us

  • Facebook
  • Pinterest

As a participant in the Amazon Services LLC Associates Program, this site may earn from qualifying purchases. We may also earn commissions on purchases from other retail websites.

JavaBeat

FEATURED TUTORIALS

Answered: Using Java to Convert Int to String

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Copyright © by JavaBeat · All rights reserved