Java

Appeared in:
1995
Influenced by:
Influenced:
Paradigm:
Typing discipline:
File extensions:
.java, .class, .jar
Versions and implementations (Collapse all | Expand all):
Programming language

Java is a high-level object-oriented platform-independent programming language.

Java development started in 1991 under the name “Oak”. It was renamed to “Java” (chosen as a random word) later to avoid trademarks conflict.

Java first public implementation was released by Sun Microsystems in 1995. Several major releases by Sun followed, current one being Java 6 released in 2006. Sun remains the main vendor of Java in several editions (Card, Micro, Standard and Enterprise), though there exist several alternative implementations like GNU Compiler for Java.

Note that Java has no official ANSI or ISO standard. Its “standard” is controlled through Java Community Process — a formalized process of adding and modifying features and versions of Java that allows participation of all interested parties.

Java developers aimed to create a language with C++-like syntax which should be object-oriented, secure, high-performance and portable, i.e. platform-independent. This should facilitate large-scale cross-platform software development.

Java code is compiled to .class files (optionally united in .jar archives). These files contain bytecode which can be executed on any Java Virtual Machine (JVM) which implements corresponding Java version, regardless of the platform behind JVM. Thus, Java applications are meant to be platform-independent, which is one of the major Java advantages. Java is not as platform-independent as its developers aimed it to be, but applications which don’t use JVM-specific features can be executed with most implementations, and the abstraction layer provided by JVM makes cross-platform development much easier.

Since its first release in 1995 Java has become one of the most popular programming languages for application development worldwide. It is nearly ubiquitous in mobile devices, web servers and enterprise applications, and present on desktop computers as applets and Java Runtime Environment (JRE).

Object-oriented programming paradigm is determinative for Java: all code is written as part of classes definition, and most entities (with the exception of elementary data types — numeric, boolean and character) are objects.

Elements of syntax:

Inline comments // ...
Non-nestable comments /* ... */
Case-sensitivity yes
Variable identifier regexp [_a-zA-Z$][_a-zA-Z0-9$]*
Function identifier regexp [_a-zA-Z$][_a-zA-Z0-9$]*
Variable assignment varname = value
Variable declaration type varname
Variable declaration with assignment type varname = value
Grouping expressions ( ... )
Block { ... }
Physical (shallow) equality a == b
Physical (shallow) inequality a != b
Deep equality a.equals(b) (a and b are objects)
Deep inequality !a.equals(b) (a and b are objects)
Comparison < > <= >=
Sequence ;
If - then if (condition) trueBlock
If - then - else if (condition) trueBlock else falseBlock
Loop forever while (true) loopBody
While condition do while (condition) loopBody
Do until condition do loopBody while (!condition)
For each value in a numeric range, 1 increment for (int i = first; i <= last ; i++) loopBody
For each value in a numeric range, 1 decrement for (int i = last; i >= first; i--) loopBody

Examples:

Hello, World!:

Example for versions Groovy 1.7, Sun Java 6, gcj 3.4.5
public class HelloWorld {
    public static void main(String[] args)
    {
        System.out.println("Hello, World!");
    }
}

Factorial:

Example for versions Groovy 1.7, Sun Java 6, gcj 3.4.5

This example uses recursive factorial definition.

public class Factorial {
    static long factorial(int n)
    {
        return ( n==0 ? 1 : n*factorial(n-1) );
    }
    public static void main(String[] args)
    {
        for (int n=0; n<=16; n++)
            System.out.println(n+"! = "+factorial(n));
    }
}

Factorial:

Example for versions Groovy 1.7, Sun Java 6, gcj 3.4.5

This example uses iterative calculation of factorial and illustrates the use of built-in class BigInteger which allows to handle arbitrarily large integer numbers.

import java.math.BigInteger;

public class Factorial {
    public static void main(String[] args)
    {
        BigInteger f = BigInteger.ONE;
        System.out.println("0! = " + f);
        for (int n=1; n<=16; n++)
        {   f = f.multiply(BigInteger.valueOf(n));
            System.out.println( n + "! = " + f);
        }
    }
}

Fibonacci numbers:

Example for versions Groovy 1.7, Sun Java 6, gcj 3.4.5

This example uses recursive definition of Fibonacci numbers.

public class Fibonacci {
    static int fibonacci(int n)
    {
        return (n<=2 ? 1 : fibonacci(n-1) + fibonacci(n-2));
    }
    public static void main(String[] args)
    {
        for (int n=1; n<=16; n++)
            System.out.print(fibonacci(n)+", ");
        System.out.println("...");
    }
}

Quadratic equation:

Example for versions Groovy 1.7, Sun Java 6, gcj 3.4.5

Java doesn’t provide complex numbers, so the calculations are done in real numbers with separate check for discriminant sign. This implementation allows to solve quadratic equations not only with integer coefficients but also with floating-point ones.

The coefficients are read from stream System.in, which allows only individual bytes to be read directly, so two wrapper classes InputStreamReader and BufferedReader are used to make reading more comfortable. The strings read from System.in are converted into double values using parseDouble method of class Double. In Java all input operations must be wrapped in try ... catch blocks to handle IOException — class of exceptions which are thrown by reading routines.

import java.util.*;
import java.io.*;

public class Quadratic {
    static String print(double real, double imag)
    {   if (Math.abs(imag)<1E-6)
            return ""+real;
        else 
            return "("+real+","+imag+")";
    }
    public static void main(String[] args)
    {   double A,B,C,D;
      try {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("A = ");
        A = Double.parseDouble(br.readLine());
        if (Math.abs(A)<1E-3)
        {   System.out.println("Not a quadratic equation.");
            return;
        }
        System.out.print("B = ");
        B = Double.parseDouble(br.readLine());
        System.out.print("C = ");
        C = Double.parseDouble(br.readLine());
      }
      catch (Exception e) {
        System.err.println("An error occured while reading input parameters.");
        return;
      }
        A = 2*A;
        D = B*B-2*A*C;
        if (Math.abs(D)<1E-3)
        {   System.out.println("x = "+(-B/A));
            return;
        }
        if (D>0)
            System.out.println("x1 = "+print((-B+Math.sqrt(D))/A, 0)+"\nx2 = "+print((-B-Math.sqrt(D))/A, 0));
        else
            System.out.println("x1 = "+print(-B/A,Math.sqrt(-D)/A)+"\nx2 = "+print(-B/A,-Math.sqrt(-D)/A));
    }
}

CamelCase:

Example for versions Groovy 1.7, Sun Java 6

This example uses Java regular expressions. A regular expression [a-zA-Z]+ describes any contiguous sequence of letters (in any case), surrounded with non-letter characters or ends of string. Classes Pattern and Matcher allow to create this regular expression and extract from the string all fragments which match it. For each such fragment, its first letter is converted to upper case, and the rest of it — to lower case. Finally, the resulting word is appended to StringBuffer variable which accumulates the result.

import java.util.regex.*;
import java.io.*;

public class CamelCase {
    public static void main(String[] args) {
      try {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        Pattern p = Pattern.compile("[a-zA-Z]+");
        Matcher m = p.matcher(br.readLine());
        StringBuffer result = new StringBuffer();
        String word;
        while (m.find()) {
            word = m.group();
            result.append(word.substring(0, 1).toUpperCase() + word.substring(1).toLowerCase());
        }
        System.out.println(result.toString());
      } catch (Exception e) {
        System.err.println("An error occured while reading input string.");
      }
    }
}