JAVA

Java is a broadly useful PC programming dialect that is simultaneous, class-based, protest oriented,and particularly intended to have as few execution conditions as could be allowed. It is proposed to give application engineers “a chance to compose once, run anyplace” (WORA), meaning that aggregated Java code can keep running on all stages that help Java without the requirement for recompilation.Java applications are ordinarily assembled to bytecode that can keep running on any Java virtual machine (JVM) paying little mind to PC design. Starting at 2016, Java is a standout amongst the most mainstream programming dialects in use,particularly for customer server web applications, with an announced 9 million developers. Java was initially created by James Gosling at Sun Microsystems (which has since been obtained by Oracle Corporation) and discharged in 1995 as a center part of Sun Microsystems’ Java stage. The dialect infers quite a bit of its grammar from C and C++, yet it has less low-level offices than both of them.

The first and reference execution Java compilers, virtual machines, and class libraries were initially discharged by Sun under exclusive licenses. As of May 2007, in consistence with the determinations of the Java Community Process, Sun relicensed the greater part of its Java advancements under the GNU General Public License. Others have additionally created elective usage of these Sun advances, for example, the GNU Compiler for Java (bytecode compiler), GNU Classpath (standard libraries), and IcedTea-Web (program module for applets).

The most recent adaptation is Java 9, discharged on September 21, 2017, and is one of the two forms as of now bolstered for nothing by Oracle. Forms sooner than Java 8 are bolstered by organizations on a business premise; e.g. by Oracle back to Java 6 as of October 2017 (while they still “exceptionally suggest that you uninstall” pre-Java 8 from at any rate Windows PCs.

Versions

As of 2017, both Java 8 and 9 are officially supported. Major release versions of Java, along with their release dates:

  • JDK 1.0 (January 23, 1996)[40]
  • JDK 1.1 (February 19, 1997)
  • J2SE 1.2 (December 8, 1998)
  • J2SE 1.3 (May 8, 2000)
  • J2SE 1.4 (February 6, 2002)
  • J2SE 5.0 (September 30, 2004)
  • Java SE 6 (December 11, 2006)
  • Java SE 7 (July 28, 2011)
  • Java SE 8 (March 18, 2014)
  • Java SE 9 (September 21, 2017)

Java platform

 Java (software platform) and Java virtual machine

One plan objective of Java is versatility, which implies that projects composed for the Java stage must run comparatively on any mix of equipment and working framework with sufficient runtime bolster. This is accomplished by assembling the Java dialect code to a middle of the road portrayal called Java bytecode, rather than specifically to design particular machine code. Java bytecode directions are practically equivalent to machine code, yet they are planned to be executed by a virtual machine (VM) composed particularly for the host equipment. End clients regularly utilize a Java Runtime Environment (JRE) introduced without anyone else machine for independent Java applications, or in a web program for Java applets.

Standard libraries give a nonexclusive method to get to have particular highlights, for example, illustrations, threading, and organizing.

The utilization of all inclusive bytecode makes porting basic. In any case, the overhead of deciphering bytecode into machine guidelines made translated programs quite often run more gradually than local executables. Without a moment to spare (JIT) compilers that incorporate bytecodes to machine code amid runtime were presented from a beginning period. Java itself is stage autonomous and is adjusted to the specific stage it is to keep running on by a Java virtual machine for it, which makes an interpretation of the Java bytecode into the stage’s machine dialect.

Implementations

Performance
Automatic memory management

Java utilizes a programmed junk jockey to oversee memory in the question lifecycle. The software engineer decides when objects are made, and the Java runtime is in charge of recuperating the memory once protests are never again being used. Once no references to a question remain, the inaccessible memory winds up qualified to be liberated naturally by the junk jockey. Something like a memory break may at present happen if a software engineer’s code holds a reference to a question that is never again required, commonly when protests that are never again required are put away in compartments that are still being used. In the event that techniques for a nonexistent question are called, an “invalid pointer special case” is tossed.

One of the thoughts behind Java’s programmed memory administration show is that software engineers can be saved the weight of performing manual memory administration. In a few dialects, memory for the formation of articles is certainly assigned on the stack or unequivocally allotted and deallocated from the load. In the last case, the duty of overseeing memory dwells with the developer. In the event that the program does not deallocate a protest, a memory spill happens. On the off chance that the program endeavors to get to or deallocate memory that has just been deallocated, the outcome is indistinct and hard to anticipate, and the program is probably going to end up precarious or crash. This can be in part cured by the utilization of keen pointers, yet these include overhead and multifaceted nature. Note that waste gathering does not avert “legitimate” memory spills, i.e., those where the memory is as yet referenced yet never utilized.

Waste gathering may occur whenever. Preferably, it will happen when a program is sit out of gear. It is ensured to be activated if there is deficient free memory on the load to dispense another question; this can make a program slow down immediately. Express memory administration isn’t conceivable in Java.

Java does not bolster C/C++ style pointer number-crunching, where protest addresses and unsigned whole numbers (typically long whole numbers) can be utilized conversely. This enables the junk jockey to move referenced questions and guarantees write wellbeing and security.

As in C++ and some other protest arranged dialects, factors of Java’s crude information writes are either put away straightforwardly in fields (for objects) or on the stack (for strategies) as opposed to on the load, as is regularly valid for non-crude information composes (however observe escape examination). This was a cognizant choice by Java’s planners for execution reasons.

Java contains numerous kinds of junk jockeys. Of course, HotSpot utilizes the parallel rummage junk collector. However, there are likewise a few other trash specialists that can be utilized to deal with the pile. For 90% of uses in Java, the Concurrent Mark-Sweep (CMS) city worker is sufficient.Oracle means to supplant CMS with the Garbage-First gatherer (G1)

Syntax

The sentence structure of Java is to a great extent affected by C++. Dissimilar to C++, which consolidates the sentence structure for organized, nonexclusive, and protest arranged programming, Java was manufactured solely as a question situated language.All code is composed inside classes, and each datum thing is a protest, except for the crude information writes, (i.e. whole numbers, skimming point numbers, boolean qualities, and characters), which are not objects for execution reasons. Java reuses some prevalent parts of C++, (for example, printf() strategy).

Not at all like C++, Java does not bolster administrator over-burdening or various legacy for classes, however numerous legacy is upheld for interfaces.

Java utilizes remarks like those of C++. There are three distinct styles of remarks: a solitary line style set apart with two slices (//), a numerous line style opened with/* and shut with */, and the Javadoc remarking style opened with/** and shut with */. The Javadoc style of remarking enables the client to run the Javadoc executable to make documentation for the program and can be perused by some coordinated improvement conditions (IDEs, for example, Eclipse to enable engineers to get to documentation inside the IDE.

Example:

// This is an example of a single line comment using two slashes

/* This is an example of a multiple line comment using the slash and asterisk.
 This type of comment can be used to hold a lot of information or deactivate
 code, but it is very important to remember to close the comment. */

package fibsandlies;
import java.util.HashMap;

/**
 * This is an example of a Javadoc comment; Javadoc can compile documentation
 * from this text. Javadoc comments must immediately precede the class, method, or field being documented.
 */
public class FibCalculator extends Fibonacci implements Calculator {
    private static Map<Integer, Integer> memoized = new HashMap<Integer, Integer>();

    /*
     * The main method written as follows is used by the JVM as a starting point for the program.
     */
    public static void main(String[] args) {
        memoized.put(1, 1);
        memoized.put(2, 1);
        System.out.println(fibonacci(12)); //Get the 12th Fibonacci number and print to console
    }

    /**
     * An example of a method written in Java, wrapped in a class.
     * Given a non-negative number FIBINDEX, returns
     * the Nth Fibonacci number, where N equals FIBINDEX.
     * @param fibIndex The index of the Fibonacci number
     * @return The Fibonacci number
     */
    public static int fibonacci(int fibIndex) {
        if (memoized.containsKey(fibIndex)) {
            return memoized.get(fibIndex);
        } else {
            int answer = fibonacci(fibIndex - 1) + fibonacci(fibIndex - 2);
            memoized.put(fibIndex, answer);
            return answer;
        }
    }
}
“Hello world” example

The traditional “Hello, world!” program can be written in Java as:

class HelloWorldApp {
    public static void main(String[] args) {
        System.out.println("Hello World!"); // Prints the string to the console.
    }
}

Source files must be named after the public class they contain, appending the suffix .java, for example, HelloWorldApp.java. It must first be compiled into bytecode, using a Java compiler, producing a file named HelloWorldApp.class. Only then can it be executed, or “launched”. The Java source file may only contain one public class, but it can contain multiple classes with other than public access and any number of public inner classes. When the source file contains multiple classes, make one class “public” and name the source file with that public class name.

A class that is not declared public may be stored in any .java file. The compiler will generate a class file for each class defined in the source file. The name of the class file is the name of the class, with .class appended. For class file generation, anonymous classes are treated as if their name were the concatenation of the name of their enclosing class, a $, and an integer.

The keyword public denotes that a method can be called from code in other classes, or that a class may be used by classes outside the class hierarchy. The class hierarchy is related to the name of the directory in which the .java file is located. This is called an access level modifier. Other access level modifiers include the keywords private and protected.

The keyword static in front of a method indicates a static method, which is associated only with the class and not with any specific instance of that class. Only static methods can be invoked without a reference to an object. Static methods cannot access any class members that are not also static. Methods that are not designated static are instance methods and require a specific instance of a class to operate.

The keyword void indicates that the main method does not return any value to the caller. If a Java program is to exit with an error code, it must call System.exit() explicitly.

The method name “main” is not a keyword in the Java language. It is simply the name of the method the Java launcher calls to pass control to the program. Java classes that run in managed environments such as applets and Enterprise JavaBeans do not use or need a main() method. A Java program may contain multiple classes that have main methods, which means that the VM needs to be explicitly told which class to launch from.

The main method must accept an array of String objects. By convention, it is referenced as args although any other legal identifier name can be used. Since Java 5, the main method can also use variable arguments, in the form of public static void main(String... args), allowing the main method to be invoked with an arbitrary number of String arguments. The effect of this alternate declaration is semantically identical (the args parameter is still an array of Stringobjects), but it allows an alternative syntax for creating and passing the array.

The Java launcher launches Java by loading a given class (specified on the command line or as an attribute in a JAR) and starting its public static void main(String[]) method. Stand-alone programs must declare this method explicitly. The String[] args parameter is an array of String objects containing any arguments passed to the class. The parameters to main are often passed by means of a command line.

Printing is part of a Java standard library: The System class defines a public static field called out. The out object is an instance of the PrintStreamclass and provides many methods for printing data to standard out, including println(String) which also appends a new line to the passed string.

The string “Hello World!” is automatically converted to a String object by the compiler.

Special classes

 Java applet

Java applets are programs that are embedded in other applications, typically in a Web page displayed in a web browser.

// Hello.java
import javax.swing.JApplet;
import java.awt.Graphics;

public class Hello extends JApplet {
    public void paintComponent(final Graphics g) {
        g.drawString("Hello, world!", 65, 95);
    }
}

The import statements direct the Java compiler to include the javax.swing.JApplet and java.awt.Graphics classes in the compilation. The import statement allows these classes to be referenced in the source code using the simple class name (i.e. JApplet) instead of the fully qualified class name (FQCN, i.e. javax.swing.JApplet).

The Hello class extends (subclasses) the JApplet (Java Applet) class; the JApplet class provides the framework for the host application to display and control the lifecycle of the applet. The JApplet class is a JComponent (Java Graphical Component) which provides the applet with the capability to display a graphical user interface (GUI) and respond to user events.

The Hello class overrides the paintComponent(Graphics) method (additionally indicated with the annotation, supported as of JDK 1.5, Override) inherited from the Container superclass to provide the code to display the applet. The paintComponent() method is passed a Graphics object that contains the graphic context used to display the applet. The paintComponent() method calls the graphic context drawString(String, int, int) method to display the “Hello, world!” string at a pixel offset of (65, 95) from the upper-left corner in the applet’s display.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<!-- Hello.html -->
<html>
    <head>
        <title>Hello World Applet</title>
    </head>
    <body>
        <applet code="Hello.class" width="200" height="200">
        </applet>
    </body>
</html>

An applet is placed in an HTML document using the <applet> HTML element. The applet tag has three attributes set: code="Hello.class" specifies the name of the JApplet class and width="200" height="200" sets the pixel width and height of the applet. Applets may also be embedded in HTML using either the object or embed element,[54] although support for these elements by web browsers is inconsistent.[55] However, the applet tag is deprecated, so the object tag is preferred where supported.

The host application, typically a Web browser, instantiates the Hello applet and creates an AppletContext for the applet. Once the applet has initialized itself, it is added to the AWT display hierarchy. The paintComponent() method is called by the AWT event dispatching thread whenever the display needs the applet to draw itself.

Servlet

Java Servlet technology provides Web developers with a simple, consistent mechanism for extending the functionality of a Web server and for accessing existing business systems. Servlets are server-side Java EE components that generate responses (typically HTML pages) to requests (typically HTTP requests) from clients. A servlet can almost be thought of as an applet that runs on the server side—without a face.

// Hello.java
import java.io.*;
import javax.servlet.*;

public class Hello extends GenericServlet {
    public void service(final ServletRequest request, final ServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html");
        final PrintWriter pw = response.getWriter();
        try {
            pw.println("Hello, world!");
        } finally {
            pw.close();
        }
    }
}

The import statements direct the Java compiler to include all the public classes and interfaces from the java.io and javax.servlet packages in the compilation. Packages make Java well suited for large scale applications.

The Hello class extends the GenericServlet class; the GenericServlet class provides the interface for the server to forward requests to the servlet and control the servlet’s lifecycle.

The Hello class overrides the service(ServletRequest, ServletResponse) method defined by the Servlet interface to provide the code for the service request handler. The service() method is passed: a ServletRequest object that contains the request from the client and a ServletResponseobject used to create the response returned to the client. The service() method declares that it throws the exceptions ServletException and IOException if a problem prevents it from responding to the request.

The setContentType(String) method in the response object is called to set the MIME content type of the returned data to “text/html”. The getWriter()method in the response returns a PrintWriter object that is used to write the data that is sent to the client. The println(String) method is called to write the “Hello, world!” string to the response and then the close() method is called to close the print writer, which causes the data that has been written to the stream to be returned to the client.

JavaServer Pages

JavaServer Pages (JSP) are server-side Java EE components that generate responses, typically HTML pages, to HTTP requests from clients. JSPs embed Java code in an HTML page by using the special delimiters <% and %>. A JSP is compiled to a Java servlet, a Java application in its own right, the first time it is accessed. After that, the generated servlet creates the response.

Swing application

Swing is a graphical user interface library for the Java SE platform. It is possible to specify a different look and feel through the pluggable look and feel system of Swing. Clones of Windows, GTK+, and Motif are supplied by Sun. Apple also provides an Aqua look and feel for macOS. Where prior implementations of these looks and feels may have been considered lacking, Swing in Java SE 6 addresses this problem by using more native GUI widget drawing routines of the underlying platforms.

This example Swing application creates a single window with “Hello, world!” inside:

// Hello.java (Java SE 5)
import javax.swing.*;

public class Hello extends JFrame {
    public Hello() {
        super("hello");
        super.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        super.add(new JLabel("Hello, world!"));
        super.pack();
        super.setVisible(true);
    }
 
    public static void main(final String[] args) {
        new Hello();
    }
}

The first import includes all the public classes and interfaces from the javax.swing package.

The Hello class extends the JFrame class; the JFrame class implements a window with a title bar and a close control.

The Hello() constructor initializes the frame by first calling the superclass constructor, passing the parameter "hello", which is used as the window’s title. It then calls the setDefaultCloseOperation(int) method inherited from JFrame to set the default operation when the close control on the title bar is selected to WindowConstants.EXIT_ON_CLOSE – this causes the JFrame to be disposed of when the frame is closed (as opposed to merely hidden), which allows the Java virtual machine to exit and the program to terminate. Next, a JLabel is created for the string “Hello, world!” and the add(Component) method inherited from the Container superclass is called to add the label to the frame. The pack() method inherited from the Window superclass is called to size the window and lay out its contents.

The main() method is called by the Java virtual machine when the program starts. It instantiates a new Hello frame and causes it to be displayed by calling the setVisible(boolean) method inherited from the Component superclass with the boolean parameter true. Once the frame is displayed, exiting the mainmethod does not cause the program to terminate because the AWT event dispatching thread remains active until all of the Swing top-level windows have been disposed.

Generics

In 2004, generics were added to the Java language, as part of J2SE 5.0. Prior to the introduction of generics, each variable declaration had to be of a specific type. For container classes, for example, this is a problem because there is no easy way to create a container that accepts only specific types of objects. Either the container operates on all subtypes of a class or interface, usually Object, or a different container class has to be created for each contained class. Generics allow compile-time type checking without having to create many container classes, each containing almost identical code. In addition to enabling more efficient code, certain runtime exceptions are prevented from occurring, by issuing compile-time errors. If Java prevented all runtime type errors (ClassCastException‘s) from occurring, it would be type safe.

In 2016, the type system was shown not to be safe at all, it was proven unsound.

Criticism

Criticisms directed at Java include the implementation of generics,speed, the handling of unsigned numbers,[59] the implementation of floating-point arithmetic, and a history of security vulnerabilities in the primary Java VM implementation HotSpot.

Use outside the Java platform

The Java programming language requires the presence of a software platform in order for compiled programs to be executed. Oracle supplies the Java platform for use with Java. The Android SDK is an alternative software platform, used primarily for developing Android applications.

Andriod

The Java language is a key pillar in Android, an open source mobile operating system. Although Android, built on the Linux kernel, is written largely in C, the Android SDK uses the Java language as the basis for Android applications. The bytecode language supported by the Android SDK is incompatible with Java bytecode and runs on its own virtual machine, optimized for low-memory devices such as smartphones and tablet computers. Depending on the Android version, the bytecode is either interpreted by the Dalvik virtual machine or compiled into native code by the Android Runtime.

Android does not provide the full Java SE standard library, although the Android SDK does include an independent implementation of a large subset of it. It supports Java 6 and some Java 7 features, offering an implementation compatible with the standard library (Apache Harmony).

Leave a Reply

Your email address will not be published. Required fields are marked *