Author: Dr. Noman Islam
Introduction
Java has become a popular choice for programming these days. It provides a platform for developing applications for desktop, web, enterprise and mobile platforms etc. This article serves as a primer on writing programs in Java language. It introduces the reader to various artifacts of a Java program, specifically discussing Java classes, and main method i.e. the starting point of execution for any Java program.
Java program structure
A program is a sequence of instructions to the computer. All the programming language specifies a certain structure for writing program. In Java, programs are written based on the notion of object oriented programming. A program is organized around objects. Each object has a set of properties and methods, which are specified using classes. A class also specifies the access modifiers for each of its members. Since Java is a pure object oriented language, almost all of its statements are specified inside a Java class. A Java program comprises a set of classes. All Java programs must have at least main method, defined in one of its classes.
main() method in Java
A program needs to start its execution somewhere. In Java, this starting point is the main method. It takes an array of String's as parameter and returns void. The signature of main method is: public static void main (String args[]). The access modifier of the main method is normally public. However, it can be specified as protected or friendly as well. When a Java program is started, it is invoked normally via the command line, as discussed in coming sections. The class to be executed is passed as argument to the Java Runtime Environment (JRE). The JRE searches for the main method of the particular class. A set of arguments can also be passed to the program. The Java application is then executed by the JVM. If no main method is found, JRE throws an exception and terminates the program.
Writing first Java program
In order to write a Java application, the Java Development Kit (JDK) must be installed on the system. The current version is JDK 7, which can be downloaded from http://www.oracle.com/technetwork/java/javase/downloads/index.html. A Java program can be written using any editor, though there are advanced editors also available. Type the following in any editor of choice: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World"); } }. Save the file as ‘HelloWorld.java’. All the public classes in Java must be saved with the same name as the name of the class.
Compiling and running the program
Before a Java program is executed, it must be compiled first. A compiler translates a program into a language more suitable for processing by computer. To compile the program, type the following lines on terminal: % javac HelloWorld.java. If there is no error message, it means the program has compiled correctly. Otherwise a list of errors can appear. Once the program is compiled, it can be run by typing % java HelloWorld on terminal. A ‘Hello, World’ message should appear on prompt.
Understanding the code
Every Java program starts with a set of zero or more import statements. The import statement is used to include pre-developed libraries for I/O, networking and graphics etc. in a program. In every Java program, a package named java.lang is imported by default. This package has classes that are mostly required for all types of Java programs. The next line of code defines a Java class ‘HelloWorld’. The HelloWorld class contains a function main, which is the entry point for execution of all Java program. The function main outputs the text ‘Hello, World’ on console using the System library available in java.lang package.
Conclusion
This short tutorial provides an overview of programming using Java. It discusses the basic structure of a Java program. Java language provides a number of packages for I/O operations (java.io), graphics (java.awt and javax.swing) and utilities (java.util) etc. Besides, user can also write its own libraries. Different libraries are also for web applications, mobile applications and enterprise applications as well.
Tip
Java language provides four types of access modifiers. These are private, friendly, protected and public modifiers. The private members of a class are accessible only inside class. The friendly members are accessible inside class as well as by the classes of same package. The protected members are accessible inside classes and packages, as well as sub classes. Finally, the public members are accessible from any location of program.
Author: Dr. Noman Islam
Introduction
Most of the modern languages provide constructs for writing programs that can execute in parallel. Parallel programming, also called concurrent programming, is the simultaneous execution of different tasks of a program in parallel. There are various approaches to perform parallel programming. For instance, Unix offers execution of multiple processes to achieve concurrency in program. Java language provides multithreading i.e. execution of multiple threads of a program to achieve concurrency. This article discusses how multithreading can be implemented in Java along with the various issues associated with multithreading, and a discussion on how Java handles these issues.
Multithreading in Java
A process is a program in execution. When a program is run, a process is created by operating system for its execution. A process has a self-contained execution environment i.e. a complete and private set of basic run-time resources. Multithreading refers to two or more tasks executing concurrently within a single program. Java provides two approaches to perform multithreading in Java. One can implement the Runnable interface, overriding the run method to specify the operations to be performed. Alternatively, one can extend the Thread class that has already implemented the Runnable interface. The run method is then overridden and thread behavior is specified. Finally, the thread can be started by calling the start method. Following section discusses these two approaches of performing multithreading in Java.
Creating thread using Runnable interface
The easiest way to create a thread is to create a class that implements the Runnable interface which is available in java.lang package. For instance, ‘public class Test implements Runnable { public void run () { // thread behavior } }’ creates a class Test that implements Runnable interface and has a method run. The method run can then be filled with the task’s code to be performed by this thread. To use this thread, an instance of Thread class should be created, passing the object of Test class i.e. Thread t = new Thread (new Test()). After the new thread is created, it will not start running, until start() method is called, which is declared within Thread class. The line t.start() will start execution of thread.
Creating thread by extending Thread class
The second way to create a thread is to create a new class that extends Thread class, and then create an instance of that class. The code public class Test extends Thread { public void run() { // thread behavior}} creates a thread and override its run method, which is the entry point for the new thread. Then an instance of test class will be created and its start method will be called to start the thread. The following line will achieve this: ‘Thread t = new Test(); t.start();’
Thread Methods
The thread class provides a number of methods to perform various operations to control thread execution. The priority of a thread can be set by calling setPriority method, specifying an integer value as argument. To run a thread as a daemon, setDaemon can be called with an argument ‘true’. A daemon thread executes in background and stops its execution when all the threads of the program have stopped. To test if a thread is alve, its isAlive method can be called. A true value signifies that the thread is alive and false value means thread has stopped working. To pause the current thread of execution, the static method sleep is called with specifying the number of milliseconds to sleep. To stop the current thread of execution till another thread finishes, the join method can be called.
Synchronization issues
One of the most important issues with multithreading is the synchronization issue that arise when two thread tries to access same data or block of code simultaneously. Java provides synchronization keyword to address this issue. There are two ways in which synchronization can be achieved in Java. To allow only one thread to execute a function at a time, the synchronized keyword can be placed with the method declaration. For instance, synchronized public void doTransaction() { acc.doDebit(); } will allow only one thread to execute the doTransaction function, at a time. Alternatively, synchronized keyword can be used with an object to allow only one thread to access the object at a time. Hence, the code public void doTransaction() { synchronized(acc) {acc.doDebit(); }} will allow only one thread to access the acc object.
Conclusion
This article briefly discusses the concept of multithreading in Java Random. Multithreading is an essential constituent of modern software applications. However, addressing synchronization issues associated with a thread is one of the most difficult aspects of any multithreaded application. Fortunately, most of the Java enterprise application servers themselves handle the synchronization issues associated with application.
Tip
Some of the classes of Java language provide thread safe implementation. For instance, Vector class of Java which is used to hold a collection of objects provides a thread safe implementation to manipulate its elements.
Author: Dr. Noman Islam
Introduction
One of the important utilities in any programming language is generating random number or a sequence of random numbers. Random numbers are often required in situations where producing an unpredictable result is desirable. Some of the situations where random numbers have applications are gambling, statistical sampling, computer simulation, cryptography and completely randomized design etc. Fortunately, Java has a rich toolkit for generating random numbers. This includes Math.random() function that can be used to generate random numbers. Another approach in Java is the use of Random class, which is the topic of discussion of this article. This article introduces its readers to random number class, various ways to instantiate the class and generating random numbers.
Introduction to Random Class
Java has a class ‘Random’ that can be used to produce a random sequence of values of different types. The various types of random numbers that can be generated using Java are Booleans, integers, doubles and longs etc. The random numbers generated are simply uniformly distributed sequences. For generating random numbers, a seed value is used, that can also be provided while instantiating the class. If two instances of Random numbers are created with the same seed, they will generate identical sequences of numbers. The Java random number uses a 48-bit seed to generate random numbers. According to the Java documentation, the seed is modified using a linear congruential formula. However, subclasses can also use other algorithms to compute seed values.
Using random numbers
The Java Random class is found in java.util package. So to use random numbers, the first step in any program is to import this package. The statement import java.util.*; will import the package into current program. To generate a random number, an instance of Random class is created i.e. Random r = new Random(). Different methods of random classes can then be invoked to generated random numbers of different types. For instance, r.nextInt() method will produce a random integer value. Similarly, nextDouble() will produce a random double number. Further details of the various methods to generate random numbers have been provided in next section. Following is an example program to produce 100 random numbers of type integer: import java.util.Random; public final class Test { public static final void main(String args[]){ Random r = new Random(); for (int i = 1; i <= 100; ++i){ int randomInt = r.nextInt(); } }
Random class methods
The Random class inherits the Object class of Java. So, all the methods of Object class are inherited by the Random class. The Random class can be instantiated using its default no argument constructor. The class provides different methods for generating random numbers of different types. The nextInt, nextBoolean, nextLong, nextFloat and nextDouble methods are used to generate next integer, Boolean, long, float and double random number values respectively. The method nextInt(int val) returns a uniformly distributed randomly number between 0 (inclusive) and the specified val (exclusive). Finally, the method nextGaussian() returns the next normally distributed double value with mean 0.0 and standard deviation 1.0 from the random number generator's sequence.
Modifying random number’s range and scale
Random number generators produce values in a particular range. Often, programmers need random numbers to lie in a different range. One can make random numbers lie in a longer or shorter range by multiplying them by a scale factor. For instance, r.nextDouble() * 360.0 produces a random double value between 0 and 360. Similarly, one can make random numbers lie in a range that is translated to higher or lower numbers than the original by adding (or subtracting) a value from the random numbers. r.nextInt(100) + 1 produces a number between 1 and 100.
Seeding random number
While creating a random number generator using its default constructor, it initializes its sequence from a value called its ‘seed’. The seed value is very likely to be distinct from any other invocation of this constructor. But, user has no control over what that value is. The class also provides a constructor for Random class that allows to provide custom seed value. The constructor takes a long integer as argument. For example, new Random(39887490) creates a random number generator with seed. The Random class also provides a method ‘setSeed’, to set the seed of the random number generator using a single long seed.
Conclusion
This article briefly discusses the Java Random class and its various methods. Besides the class discussed, there are several other classes to generate random numbers in Java. The class SecureRandom provides a cryptographically strong random number generator (RNG). Similarly, the ThreadLocalRandom, provides a thread safe implementation for generating random numbers in multi-threaded environment.
Tip
Random number generators are random for a short span of time. But, if observed over some time, there is a certain consistency in their output. This is because they are generated using certain formula (further randomized using the seed values).
Author: Dr. Noman Islam
Introduction
A programming language provides various constructs to write a program. This includes keywords, predefined libraries and a set of operators etc. An operator takes a set of input values, performs some mathematical or logical computation and produces an output. Java language is equipped with a set of operators to perform mathematical operations (+, -, *, / and %), logical operations (& and |) and shift operations (>>,>>> and <<) etc. This article discusses ternary operator of Java. It is one of the unique, yet a powerful operator that provides convenience to write large mathematical operations in a concise way.
Ternary operator
A ternary operator is part of the syntax for a basic conditional expression in several programming languages including C, C++ and Java etc. Ternary operators are also commonly called conditional operator, inline if (iif), or ternary if etc. A ternary operation, as its name implies, is a 3-ary operation and takes three operands as arguments. The first argument is a comparison argument, the second is the result upon a true comparison and the third is the result upon a false comparison. It is often used as a way to assign variables based on the result of some comparison. Common usages of ternary operator will be discussed in coming sections. When formatted correctly, ternary operator can help in increasing the readability and reduces the amount of lines in code.
Syntax of ternary operator
The syntax of a ternary operator is ‘expression1 ? expression2: expression3’. Here, expression1 can be any expression that evaluates to a Boolean value. If expression1 is true, then expression2 is the result of the statement. On the contrary, if expression1 is false, expression3 will be the result of statement. Both expression2 and expression3 are required to return the same type. The possible data types of expression1 and expression 2 can be integer, float, string, Boolean or any user defined types. The ternary operator can seem somewhat confusing at first instance; but with time, one can get use to it and can employ it to write effective, clearner and precise code.
Ternary operator and if/else
Ternary operator can be considered as a shorthand replacement of if/else statement. Suppose, the following lines of code have been written to determine if a number is even or add: if(num%2==0) { result = “Even”; } else{ result = “Odd” }. This long sequence of statements can be written in a single line using ternary operator as follows: result = num%2 ==0 ? “Even” : “Odd”. Here, first the remainder of num with respect to 2 is computed. If it is zero, the ternary operator’s evaluated value is “Even”. Otherwise, the “Odd” value is the output of ternary operator. The resultant value is finally assigned to the variable result.
Examples
The ternary operator allows executing different code depending on the value of a condition. It can be used in a variety of situation to write simple lines of code. Its most common usage is to make simple conditional assignment statement like weather = temperature > 25 ? “Hot” : “Cold”. In this statement, weather is computed depending upon the value of temperature. Similarly, ternary operator can also be used to display a different message based on the value of the variable. The statement System.out.println( age > 18 ? “User is adult” : “User is not adult”) will output if the user is adult or not adult depending upon his age.
Nested ternary operators
Ternary operators can be nested to write more complex conditional statements. For instance, to find maximum value from three numbers num1, num2 and num3; one can write: max = num1 > num2 ? (num1 > num3 ? num1: num3) : (num3>num2? num3: num2). In this statement, three conditional operators are used. First num1 is compared with num2. If it evaluates to true, num1 is compared with num3, and depending on the result, the maximum will be num1 or num3. If the value of first conditional operator is false, then num3 is compared with num2 to determine which of the two is greater; yielding the maximum among the three numbers. Because of its complexity, nested ternary operators are not normally used in programming.
Conclusion
This article briefly discusses the ternary operator in Java. It discusses the syntax and various examples to illustrate the scenarios where this operator can be useful. Besides ternary operator, there are several other conditional operators provided by Java. For instance, switch operator can be used to write a sequence of cases to be executed based on the value of a variable. Similarly, the if/else statements are used to write conditional statements to be executed based on certain conditions.
Tip
Java provides three types of operators i.e. unary, binary and ternary operators. The unary operator operates on single operand. Examples of unary operators are ‘–‘ and ‘!’ operators etc. The binary operator works with two operands. +, -, *, /, &&, ||, &, and | etc. are classic examples of binary operators. Finally, the ternary operator (?) has been discussed in this article. It operates on three operands and produces an output.