Java is an object-oriented
programming
language developed by James Gosling and colleagues at Sun Microsystems in the
early 1990s. Unlike conventional languages which are generally designed either
to be compiled to native (machine) code, or to be interpreted from source code
at runtime, Java is intended to be compiled to a bytecode, which is then run
(generally using JIT compilation) by a Java Virtual Machine.
The language itself borrows much syntax from C and C++ but has a simpler object model and fewer low-level facilities. Java is only distantly related to JavaScript, though they have similar names and share a C-like syntax.
History
Java was started as a project called "Oak" by James Gosling in June 1991. Gosling's goals were to implement a virtual machine and a language that had a familiar C-like notation but with greater uniformity and simplicity than C/C++. The first public implementation was Java 1.0 in 1995. It made the promise of "Write Once, Run Anywhere", with free runtimes on popular platforms. It was fairly secure and its security was configurable, allowing for network and file access to be limited. The major web browsers soon incorporated it into their standard configurations in a secure "applet" configuration. popular quickly. New versions for large and small platforms (J2EE and J2ME) soon were designed with the advent of "Java 2". Sun has not announced any plans for a "Java 3".
In 1997, Sun approached the ISO/IEC JTC1 standards body and later the Ecma International to formalize Java, but it soon withdrew from the process. Java remains a proprietary de facto standard that is controlled through the Java Community Process. Sun makes most of its Java implementations available without charge, with revenue being generated by specialized products such as the Java Enterprise System. Sun distinguishes between its Software Development Kit (SDK) and Runtime Environment (JRE) which is a subset of the SDK, the primary distinction being that in the JRE the compiler is not present.
There were five primary goals in the creation of the Java language:
1. It should use the object-oriented programming methodology.
2. It should allow the same program to be executed on multiple operating systems.
3. It should contain built-in support for using computer networks.
4. It should be designed to execute code from remote sources securely.
5. It should be easy to use by selecting what was considered the good parts of other object-oriented languages.
Object orientation
The first characteristic, object orientation ("OO"), refers to a method of programming and language design. Although there are many interpretations of OO, one primary distinguishing idea is to design software so that the various types of data it manipulates are combined together with their relevant operations. Thus, data and code are combined into entities called objects. An object can be thought of as a self-contained bundle of behavior (code) and state (data). The principle is to separate the things that change from the things that stay the same; often, a change to some data structure requires a corresponding change to the code that operates on that data, or vice versa. This separation into coherent objects provides a more stable foundation for a software system's design. The intent is to make large software projects easier to manage, thus improving quality and reducing the number of failed projects.
Another primary goal of OO programming is to develop more generic objects so that software can become more reusable between projects. A generic "customer" object, for example, should have roughly the same basic set of behaviors between different software projects, especially when these projects overlap on some fundamental level as they often do in large organizations. In this sense, software objects can hopefully be seen more as pluggable components, helping the software industry build projects largely from existing and well-tested pieces, thus leading to a massive reduction in development times. Software reusability has met with mixed practical results, with two main difficulties: the design of truly generic objects is poorly understood, and a methodology for broad communication of reuse opportunities is lacking. Some open source communities want to help ease the reuse problem, by providing authors with ways to disseminate information about generally reusable objects and object libraries.
Syntax
The syntax of Java is largely derived from C++. However, unlike C++, which combines the syntax for structured, generic, and object-oriented programming, Java was built from the ground up to be virtually fully object-oriented: everything in Java is an object with the exceptions of atomic datatypes (ordinal and real numbers, boolean values, and characters) and everything in Java is written inside a class.
Applet
Java applets are programs that are embedded in other applications, typically in a Web page displayed in a Web browser.
// Hello.java
import java.applet.Applet;
import java.awt.Graphics;
public class Hello extends Applet {
public void paint(Graphics gc) {
gc.drawString("Hello, world!", 65, 95);
}
}
This applet will simply draw the string "Hello, world!" in the rectangle within which the applet will run. This is a slightly better example of using Java's OO features in that the class explicitly extends the basic "Applet" class, that it overrides the "paint" method and that it uses import statements.
<!-- Hello.html -->
<html>
<head>
<title>Hello World Applet</title>
</head>
<body>
<applet code="Hello" 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" specifies the name of the Applet 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, although support for these elements by Web browsers is inconsistent.
Servlet
Java servlets are server-side Java EE components that generate responses to requests from clients.
// Hello.java
import java.io.*;
import javax.servlet.*;
public class Hello extends GenericServlet {
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("Hello, world!");
pw.close();
}
}
The import statements direct the Java compiler to include all of the public classes and interfaces from the java.io and javax.servlet packages in the compilation. 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 ServletResponse object 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.
Swing application
Swing is the advanced graphical user interface library for the Java SE platform.
// Hello.java
import javax.swing.*;
public class Hello extends JFrame {
Hello() {
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
add(new JLabel("Hello, world!"));
pack();
}
public static void main(String[] args) {
new Hello().setVisible(true);
}
}
The import statement directs the Java compiler to include all of the public classes and interfaces from the javax.swing package in the compilation. The Hello class extends the JFrame class; the JFrame class implements a window with a title bar with a close control.
The Hello() constructor initializes the frame by first calling the setDefaultCloseOperation(int) method inherited from JFrame to set the default operation when the close control on the title bar is selected to WindowConstants.DISPOSE_ON_CLOSE—this causes the JFrame to be disposed of when the frame is closed (as opposed to merely hidden), which allows the JVM to exit and the program to terminate. Next a new 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 layout its contents.
The main() method is called by the JVM 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. Note that once the frame is displayed, exiting the main method 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.
Look and feel
The default look and feel of GUI applications written in Java using the Swing toolkit is very different from native applications. 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 Mac OS X. Though prior implementations of these look and feels have been considered lacking, Swing in Java SE 6 addresses this problem by using more native widget drawing routines of the underlying platforms. Alternatively, third party toolkits such as wx4j or SWT may be used for increased integration with the native windowing system.
Lack of OO purity and facilities
Java's primitive types are not objects. Primitive types hold their values in the stack rather than being references to values. This was a conscious decision by Java's designers for performance reasons. Because of this, Java is not considered to be a pure object-oriented programming language. However, as of Java 5.0, autoboxing enables programmers to write as if primitive types are their wrapper classes, and freely interchange between them for improved flexibility. Java designers decided not to implement certain features present in other OO languages, including:
* multiple inheritance
* operator overloading
* class properties
* tuples
Java Runtime Environment
The Java Runtime Environment or JRE is the software required to run any application deployed on the Java Platform. End-users commonly use a JRE in software packages and Web browser plugins. Sun also distributes a superset of the JRE called the Java 2 SDK (more commonly known as the JDK), which includes development tools such as the Java compiler, Javadoc, and debugger.
In 1977, DoD launched a project to build the perfect programming language. The project lead to the creation of the most expensive programming language to be ever created, Ada. A more valuable outcome of this project was the realization that a perfect language is not possible. Language creation involves several trade-offs, for example, a language cannot be both strictly typed and loosely typed. Therefore, it cannot provide the benefits of both. An ideal language for a specific domain is possible but a globally perfect language is not possible. Java is also not a perfect language. Following is a list of advantages and disadvantages of Java.
- fully object-oriented language facilitating modular design
- platform-independent
- secure
- facilitates distributed programming
- strong multithreading support
- strictly type language promoting robust code development
- strictly typed
- not suitable for scripting
Many Java programmers are constantly annoyed by the never-ending introduction of new J's i.e. newer technologies, all of whom contain a J in the name; JSF, JSP, JAXP, ... Every time a new problem is solved, such as adding ability to process XML DOM, or an existing feature is improved, a completely new technology is created with an annoying learning curve. Comparatively, python simply requires adding a new library, PHP simply adds new functions to existing list of functions.
Seasoned Java
programmers tend to think only in Java. Seasoned Microsoft technology
programmers tend to think only in Microsoft technologies. No technology is
perfect and each has its advantages and disadvantages. A programmer should
think in terms of problem solving, not programming languages. Solve the problem
on paper and then and only then choose a language which best serves the purpose
and syncs well in the environment.
To provide a more tangible analogy, think of an automobile assembly line. Cars are created in factories. A group of engineers and others designed every detail of the car i.e. created a blueprint for the car. All cars are produced to the exact specifications with the possibility of customizations such as color, leather interior, sound system, sunroof, etc. The factory is the Java compiler. The blueprint is the class. Each individual car coming off the assembly line is an object. A class can be used to create infinite number of objects. Depending on the code of the class, objects can have different properties such as the color of the car. The act of creating an object is called instantiation.
A class is declared with the keyword class.
In Calc.java, operand1, operand2, and result are are data members of the class. They are variables of type int.
Calc() is the constructor. It serves to initialize a class. Note that it does not have a return type i.e. no void, int, etc. in front of the method name. A constructor has the same name and the class. Note that the constructor is assigning default values to the data members.
calculate() sums operand1 and operand2 and stores the result in result. Note that they are accessed with "this" operator. "this" is a reference to the current object. Without, "this" Java will return an error since it won't be able to see outside the method and the variable is not declared in the method. "return" returns the value to the caller. In this code, the caller is a testCalc object.
The code begins at testCalc since it contains the "main" method. Line 3 instantiates the class Calc and creates the object c. During instantiation, the class is created and the constructor is called. The constructor sets the default values of the data members. Line 4 calls the calculate() method. calculate() sums the two numbers and saves the result with Calc object. Line 5 calls the getResult() method which prints the result to screen.
Constructors
Constructors are special kinds of methods which have the following properties:
- Constructors don't have a return type
- Constructors have the same name as the class
- Constructors are used to initialize data members
- Constructors can have arguments
- Constructor definition is optional
- Multiple constructors can be defined as long as the signature is different
- Constructors cannot have abstract, final, or static modifiers.
Default constructors
If a constructor is not provided, the compiler uses the no-argument constructor of the superclass. If the superclass does not have a no-argument constructor, the compiler would complain. Many classes don't have s superclass. For these classes, the class "Object" is the superclass and it provides a no-argument constructor. Not providing a constructor is bad programming and you should get in the habit of always providing constructors.
Passing parameters to constructors
In the example on the previous page, the following constructor was provided. It assigns predetermined values to data members.
Multiple constructors
It is possible to define multiple constructors but their signatures must be different. A signature is a set of parameter. In the example above, the signature is two int variables. An int variable and a String variable would be a different signature. Following is an example with a two constructors.
Buses, cars and trucks are all vehicles. They all have wheels, doors, brakes, etc. Instead of defining all these properties of every kind of vehicle, we can define a class vehicle that would define all the properties. The subclasses Car and Truck will only modify what is needed define a car. Following is the superclass Vehicle.java
The following example creates a new subclass Truck.java. The superclass Vehicle remains unchanged.
4
18
Truck has 18 wheels.
testVehicles class
Truck.setWheels(18). Since Truck does not have this method defined, the method
defined in Vehicle is called and the value of wheels is changed from 4 to 18.
Call to t.getParameters() confirms that the change did happen. Both Truck and
Vehicle define print() so only the print() method defined in Truck will be
called. However, we want both print methods to be called. So super.print() is
used in Truck's print() method. The keyword super is used to call methods of
the superclass.
What is method overloading in Java
Method overloading in Java is a programming concept when programmer declare two methods of same name but with different method signature e.g. change in argument list or change in type of argument. method overloading is a powerful Java programming technique to declare method which does similar performance but with different kind of input. One of the most popular example of method overloading is System.out.println() method which is overloaded to accept all kinds of data types in Java
One idea behind Java's automatic memory management model is that programmers should be spared the burden of having to perform manual memory management. In some languages the programmer allocates memory to create any object stored on the heap and is responsible for later manually deallocating that memory to delete any such objects. If a programmer forgets to deallocate memory or writes code that fails to do so in a timely fashion, a memory leak can occur: the program will consume a potentially arbitrarily large amount of memory. In addition, if a region of memory is deallocated twice, the program can become unstable and may crash. Finally, in non garbage collected environments, there is a certain degree of overhead and complexity of user-code to track and finalize allocations.
In Java, this potential problem is avoided by automatic garbage collection. The programmer determines when objects are created, and the Java runtime is responsible for managing the object's lifecycle. The program or other objects can reference an object by holding a reference to it (which, from a low-level point of view, is its address on the heap). When no references to an object remain, the Java garbage collector automatically deletes the unreachable object, freeing memory and preventing a memory leak. Memory leaks may still occur if a programmer's code holds a reference to an object that is no longer needed—in other words, they can still occur but at higher conceptual levels.
The use of garbage collection in a language can also affect programming paradigms. If, for example, the developer assumes that the cost of memory allocation/recollection is low, they may choose to more freely construct objects instead of pre-initializing, holding and reusing them. With the small cost of potential performance penalties (inner-loop construction of large/complex objects), this facilitates thread-isolation (no need to synchronize as different threads work on different object instances) and data-hiding. The use of transient immutable value-objects minimizes side-effect programming.
Comparing Java and C++, it is possible in C++ to implement similar functionality (for example, a memory management model for specific classes can be designed in C++ to improve speed and lower memory fragmentation considerably), with the possible cost of extra development time and some application complexity. In Java, garbage collection is built-in and virtually invisible to the developer. That is, developers may have no notion of when garbage collection will take place as it may not necessarily correlate with any actions being explicitly performed by the code they write. Depending on intended application, this can be beneficial or disadvantageous: the programmer is freed from performing low-level tasks, but at the same time loses the option of writing lower level code.
Why garbage collection?
After a method throws an exception, the runtime system attempts to find something to handle it. The set of possible "somethings" to handle the exception is the ordered list of methods that had been called to get to the method where the error occurred. The list of methods is known as the call stack.
1. Exception is an error event that can happen during the execution of a program and disrupts its normal flow. Java provides a robust and object oriented way to handle exception scenarios, known as Java Exception HandlingChecked exceptions: A checked exception is an exception that is typically a user error or a problem that cannot be foreseen by the programmer. For example, if a file is to be opened, but the file cannot be found, an exception occurs. These exceptions cannot simply be ignored at the time of compilation.
The throws/throw
Keywords:
The language itself borrows much syntax from C and C++ but has a simpler object model and fewer low-level facilities. Java is only distantly related to JavaScript, though they have similar names and share a C-like syntax.
History
Java was started as a project called "Oak" by James Gosling in June 1991. Gosling's goals were to implement a virtual machine and a language that had a familiar C-like notation but with greater uniformity and simplicity than C/C++. The first public implementation was Java 1.0 in 1995. It made the promise of "Write Once, Run Anywhere", with free runtimes on popular platforms. It was fairly secure and its security was configurable, allowing for network and file access to be limited. The major web browsers soon incorporated it into their standard configurations in a secure "applet" configuration. popular quickly. New versions for large and small platforms (J2EE and J2ME) soon were designed with the advent of "Java 2". Sun has not announced any plans for a "Java 3".
In 1997, Sun approached the ISO/IEC JTC1 standards body and later the Ecma International to formalize Java, but it soon withdrew from the process. Java remains a proprietary de facto standard that is controlled through the Java Community Process. Sun makes most of its Java implementations available without charge, with revenue being generated by specialized products such as the Java Enterprise System. Sun distinguishes between its Software Development Kit (SDK) and Runtime Environment (JRE) which is a subset of the SDK, the primary distinction being that in the JRE the compiler is not present.
There were five primary goals in the creation of the Java language:
1. It should use the object-oriented programming methodology.
2. It should allow the same program to be executed on multiple operating systems.
3. It should contain built-in support for using computer networks.
4. It should be designed to execute code from remote sources securely.
5. It should be easy to use by selecting what was considered the good parts of other object-oriented languages.
Object orientation
The first characteristic, object orientation ("OO"), refers to a method of programming and language design. Although there are many interpretations of OO, one primary distinguishing idea is to design software so that the various types of data it manipulates are combined together with their relevant operations. Thus, data and code are combined into entities called objects. An object can be thought of as a self-contained bundle of behavior (code) and state (data). The principle is to separate the things that change from the things that stay the same; often, a change to some data structure requires a corresponding change to the code that operates on that data, or vice versa. This separation into coherent objects provides a more stable foundation for a software system's design. The intent is to make large software projects easier to manage, thus improving quality and reducing the number of failed projects.
Another primary goal of OO programming is to develop more generic objects so that software can become more reusable between projects. A generic "customer" object, for example, should have roughly the same basic set of behaviors between different software projects, especially when these projects overlap on some fundamental level as they often do in large organizations. In this sense, software objects can hopefully be seen more as pluggable components, helping the software industry build projects largely from existing and well-tested pieces, thus leading to a massive reduction in development times. Software reusability has met with mixed practical results, with two main difficulties: the design of truly generic objects is poorly understood, and a methodology for broad communication of reuse opportunities is lacking. Some open source communities want to help ease the reuse problem, by providing authors with ways to disseminate information about generally reusable objects and object libraries.
Syntax
The syntax of Java is largely derived from C++. However, unlike C++, which combines the syntax for structured, generic, and object-oriented programming, Java was built from the ground up to be virtually fully object-oriented: everything in Java is an object with the exceptions of atomic datatypes (ordinal and real numbers, boolean values, and characters) and everything in Java is written inside a class.
Applet
Java applets are programs that are embedded in other applications, typically in a Web page displayed in a Web browser.
// Hello.java
import java.applet.Applet;
import java.awt.Graphics;
public class Hello extends Applet {
public void paint(Graphics gc) {
gc.drawString("Hello, world!", 65, 95);
}
}
This applet will simply draw the string "Hello, world!" in the rectangle within which the applet will run. This is a slightly better example of using Java's OO features in that the class explicitly extends the basic "Applet" class, that it overrides the "paint" method and that it uses import statements.
<!-- Hello.html -->
<html>
<head>
<title>Hello World Applet</title>
</head>
<body>
<applet code="Hello" 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" specifies the name of the Applet 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, although support for these elements by Web browsers is inconsistent.
Servlet
Java servlets are server-side Java EE components that generate responses to requests from clients.
// Hello.java
import java.io.*;
import javax.servlet.*;
public class Hello extends GenericServlet {
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("Hello, world!");
pw.close();
}
}
The import statements direct the Java compiler to include all of the public classes and interfaces from the java.io and javax.servlet packages in the compilation. 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 ServletResponse object 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.
Swing application
Swing is the advanced graphical user interface library for the Java SE platform.
// Hello.java
import javax.swing.*;
public class Hello extends JFrame {
Hello() {
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
add(new JLabel("Hello, world!"));
pack();
}
public static void main(String[] args) {
new Hello().setVisible(true);
}
}
The import statement directs the Java compiler to include all of the public classes and interfaces from the javax.swing package in the compilation. The Hello class extends the JFrame class; the JFrame class implements a window with a title bar with a close control.
The Hello() constructor initializes the frame by first calling the setDefaultCloseOperation(int) method inherited from JFrame to set the default operation when the close control on the title bar is selected to WindowConstants.DISPOSE_ON_CLOSE—this causes the JFrame to be disposed of when the frame is closed (as opposed to merely hidden), which allows the JVM to exit and the program to terminate. Next a new 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 layout its contents.
The main() method is called by the JVM 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. Note that once the frame is displayed, exiting the main method 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.
Look and feel
The default look and feel of GUI applications written in Java using the Swing toolkit is very different from native applications. 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 Mac OS X. Though prior implementations of these look and feels have been considered lacking, Swing in Java SE 6 addresses this problem by using more native widget drawing routines of the underlying platforms. Alternatively, third party toolkits such as wx4j or SWT may be used for increased integration with the native windowing system.
Lack of OO purity and facilities
Java's primitive types are not objects. Primitive types hold their values in the stack rather than being references to values. This was a conscious decision by Java's designers for performance reasons. Because of this, Java is not considered to be a pure object-oriented programming language. However, as of Java 5.0, autoboxing enables programmers to write as if primitive types are their wrapper classes, and freely interchange between them for improved flexibility. Java designers decided not to implement certain features present in other OO languages, including:
* multiple inheritance
* operator overloading
* class properties
* tuples
Java Runtime Environment
The Java Runtime Environment or JRE is the software required to run any application deployed on the Java Platform. End-users commonly use a JRE in software packages and Web browser plugins. Sun also distributes a superset of the JRE called the Java 2 SDK (more commonly known as the JDK), which includes development tools such as the Java compiler, Javadoc, and debugger.
Features of Java, How Java is different from C++
Ø
It’s the current “hot” language.
Ø
It’s almost entirely object-oriented.
Ø
It has a vast library of predefined objects and operations.
Ø
It’s more platform independent this makes it great for Web
programming.
Ø
It’s more secure.
Java is diff from c++
Ø C++ uses pointers
and have memory leaks , where java doesn't have pointers and there are no
memory leaks (although there are logic memory leaks,I think) ..
Ø C++ compiles to
machine language , when Java compiles to byte code .
Ø Java has
no virtual , since everything in java is virtual (please
correct me if I'm wrong) .
Ø In C++ the programmer
needs to worry about freeing the allocated memory , where in Java the Garbage
Collector (with all its algorithms , I can think of at least 3 algorithms)
takes care of the the unneeded / unused variables .
Advantages and disadvantages of Java
In 1977, DoD launched a project to build the perfect programming language. The project lead to the creation of the most expensive programming language to be ever created, Ada. A more valuable outcome of this project was the realization that a perfect language is not possible. Language creation involves several trade-offs, for example, a language cannot be both strictly typed and loosely typed. Therefore, it cannot provide the benefits of both. An ideal language for a specific domain is possible but a globally perfect language is not possible. Java is also not a perfect language. Following is a list of advantages and disadvantages of Java.
Advantages
- Automatic memory allocation and garbage collection- fully object-oriented language facilitating modular design
- platform-independent
- secure
- facilitates distributed programming
- strong multithreading support
- strictly type language promoting robust code development
Disadvantages
- slower than C, C++, and many other languages- strictly typed
- not suitable for scripting
Many Java programmers are constantly annoyed by the never-ending introduction of new J's i.e. newer technologies, all of whom contain a J in the name; JSF, JSP, JAXP, ... Every time a new problem is solved, such as adding ability to process XML DOM, or an existing feature is improved, a completely new technology is created with an annoying learning curve. Comparatively, python simply requires adding a new library, PHP simply adds new functions to existing list of functions.
Object-Oriented Programming in Java
Java is a fully
object-oriented language. Every program has at least one class. Classes are
instantiated to create objects. To provide a more tangible analogy, think of an automobile assembly line. Cars are created in factories. A group of engineers and others designed every detail of the car i.e. created a blueprint for the car. All cars are produced to the exact specifications with the possibility of customizations such as color, leather interior, sound system, sunroof, etc. The factory is the Java compiler. The blueprint is the class. Each individual car coming off the assembly line is an object. A class can be used to create infinite number of objects. Depending on the code of the class, objects can have different properties such as the color of the car. The act of creating an object is called instantiation.
A class is declared with the keyword class.
class MyClass {
// some code
}
Objects are
instantiated with the new keyword.
MyClass mc = new MyClass();
Time for an example.
We will be creating a calculator:
public class Calc {
int operand1;
int operand2;
int result;
Calc() {
this.operand1 = 1;
this.operand2 = 2;
this.result = 0;
}
void calculate() {
this.result = this.operand1 + this.operand2;
}
int getResult() {
return this.result;
}
}
Save this as
Calc.java. The name of the file must be the same as the name of the class.
public class testCalc {
public static void main(String[] args) {
Calc c = new Calc();
c.calculate();
System.out.println(c.getResult());
}
}
Save this as
testCalc.java. Compile and run both. The output should be the number 3.In Calc.java, operand1, operand2, and result are are data members of the class. They are variables of type int.
Calc() is the constructor. It serves to initialize a class. Note that it does not have a return type i.e. no void, int, etc. in front of the method name. A constructor has the same name and the class. Note that the constructor is assigning default values to the data members.
calculate() sums operand1 and operand2 and stores the result in result. Note that they are accessed with "this" operator. "this" is a reference to the current object. Without, "this" Java will return an error since it won't be able to see outside the method and the variable is not declared in the method. "return" returns the value to the caller. In this code, the caller is a testCalc object.
The code begins at testCalc since it contains the "main" method. Line 3 instantiates the class Calc and creates the object c. During instantiation, the class is created and the constructor is called. The constructor sets the default values of the data members. Line 4 calls the calculate() method. calculate() sums the two numbers and saves the result with Calc object. Line 5 calls the getResult() method which prints the result to screen.
Constructors
Constructor in Java is block of code which is executed at the
time of Object creation. But other than getting called, Constructor is entirely
different than methods and has some specific properties like name of
constructor must be same as name of Class. Constructor also can not have any
return type, constructor’s are automatically chained
by using this
keyword and super. Since Constructor is used to create
object, object initialization code is normally hosted in Constructor.
Constructors are special kinds of methods which have the following properties:
- Constructors don't have a return type
- Constructors have the same name as the class
- Constructors are used to initialize data members
- Constructors can have arguments
- Constructor definition is optional
- Multiple constructors can be defined as long as the signature is different
- Constructors cannot have abstract, final, or static modifiers.
Default constructors
If a constructor is not provided, the compiler uses the no-argument constructor of the superclass. If the superclass does not have a no-argument constructor, the compiler would complain. Many classes don't have s superclass. For these classes, the class "Object" is the superclass and it provides a no-argument constructor. Not providing a constructor is bad programming and you should get in the habit of always providing constructors.
Passing parameters to constructors
In the example on the previous page, the following constructor was provided. It assigns predetermined values to data members.
Calc() {
this.operand1 = 1;
this.operand2 = 2;
this.result = 0;
}
A constructor can
accept parameters from the caller. Following is a rewrite of the previous
page's example with a constructor that accepts parameters
public class Calc {
int operand1;
int operand2;
int result;
Calc(int op1, int op2) {
this.operand1 = op1;
this.operand2 = op2;
this.result = 0;
}
void calculate() {
this.result = this.operand1 + this.operand2;
}
int getResult() {
return this.result;
}
}
public class testCalc {
public static void main(String[] args) {
Calc c = new Calc(2, 3);
c.calculate();
System.out.println(c.getResult());
}
}
When the object is
instantiated, the values 2 and 3 are passed to the calculator. The constructor
accepts two int values. These values are then assigned to class variables
operand1 and operand2. With this change in the code, testCalc can now send any
two integers and get a sum. However, a new object needs to be created for every
sum. This example was only to show how to pass parameters to constructors.
Don't use this logic in your real-world programs i.e. objects creation cost
memory and processing time, so never create unnecessary objects.Multiple constructors
It is possible to define multiple constructors but their signatures must be different. A signature is a set of parameter. In the example above, the signature is two int variables. An int variable and a String variable would be a different signature. Following is an example with a two constructors.
public class Calc {
int operand1;
int operand2;
int operand3;
int result;
Calc(int op1, int op2) {
this.operand1 = op1;
this.operand2 = op2;
this.operand3 = 0;
this.result = 0;
}
Calc(int op1, int op2, int op3) {
this.operand1 = op1;
this.operand2 = op2;
this.operand3 = op3;
this.result = 0;
}
void calculate() {
this.result = this.operand1 + this.operand2 + this.operand3;
}
int getResult() {
return this.result;
}
}
public class testCalc {
public static void main(String[] args) {
Calc c = new Calc(2, 3);
c.calculate();
System.out.println(c.getResult());
Calc d = new Calc(2, 3, 4);
d.calculate();
System.out.println(d.getResult());
}
}
The new constructor
accepts three int variables. calculate() is modified to sum three variables.
When there are only two variables, the value of operand3 is 0, so the sum would
be equivalent to the sum of two numbers. A new object is instantiated to sum
three numbers and the result is printed.Inheritance
Inheritance is a fantastic feature which simplifies development and facilitates reuse of classes. A class can inherit properties and methods from another class. The inheriting class is called the subclass while the class it is inheriting from is called the superclass. subclasses have the option to add new methods and properties as well as modify the functionality of existing methods if needed. To inherit from another class, we need to use the extends keyword.Buses, cars and trucks are all vehicles. They all have wheels, doors, brakes, etc. Instead of defining all these properties of every kind of vehicle, we can define a class vehicle that would define all the properties. The subclasses Car and Truck will only modify what is needed define a car. Following is the superclass Vehicle.java
public class Vehicle {
int wheels;
Vehicle() {
this.wheels = 4;
}
public void setWheels(int w) {
this.wheels = w;
}
public void getParameters() {
System.out.println(this.wheels);
}
public void print() {
System.out.println("has " + this.wheels + " wheels.");
}
}
and subclass Car
public class Car extends Vehicle {
// will work without any code here
}
and the test class
public class testVehicles {
public static void main(String[] args) {
Car c = new Car();
c.getParameters();
}
}
testVehicles
instantiates a Car object and calls getParameters(). Car is an empty class with
no methods defined. Yet it prints results because it extends the class Vehicle.
Vehicle defines the method getParameters(). The result we see comes from the
class Vehicle.The following example creates a new subclass Truck.java. The superclass Vehicle remains unchanged.
public class Truck extends Vehicle {
public void print() {
System.out.print("Truck ");
super.print();
}
}
Modified
testVehicles.java.
public class testVehicles {
public static void main(String[] args) {
Car c = new Car();
c.getParameters();
Truck t = new Truck();
t.setWheels(18);
t.getParameters();
t.print();
}
}
Output:4
18
Truck has 18 wheels.
Abstract Methods and Classes
An
abstract class is a class that is declared abstract—it may or may not include
abstract methods. Abstract classes cannot be instantiated, but they can be
subclassed. An abstract method is a method that is declared without an
implementation (without braces, and followed by a semicolon), like this:
abstract
void moveTo(double deltaX, double deltaY);
If
a class includes abstract methods, the class itself must be declared abstract,
as in:
public
abstract class GraphicObject {
// declare fields
// declare non-abstract methods
abstract void draw();
}
Abstract
classes cannot be instantiated; they must be subclassed, and actual
implementations must be provided for the abstract methods. Any implementation
specified can, of course, be overridden by additional subclasses. An object
must have an implementation for all of its methods. You need to create a
subclass that provides an implementation for the abstract method.
Final keyword
Final
is a keyword or reserved word in java and can be applied to member variables,
methods, class and local variables in Java. Once you make a reference final you
are not allowed to change that reference and compiler will verify this and
raise compilation error if you try to re-initialized final variables in java.
Final method in Java
Final
keyword in java can also be applied to methods. A java method with final
keyword is called final method and it can not be overridden in sub-class. You
should make a method final in java if you think it’s complete and its behavior should
remain constant in sub-classes. Final methods are faster than non-final methods
because they are not required to be resolved during run-time and they are
bonded on compile time.
Method overloading in Java is a programming concept when programmer declare two methods of same name but with different method signature e.g. change in argument list or change in type of argument. method overloading is a powerful Java programming technique to declare method which does similar performance but with different kind of input. One of the most popular example of method overloading is System.out.println() method which is overloaded to accept all kinds of data types in Java
Ø
Java supports to define two or more methods with same names within
a class.
Ø
All the methods should differ in either by the number or type of
parameters.
Ø
The method System.out.println() receives multiple parameters.
Ø
Ex : System.out.println(“Welcome to Java Technology”);// parameter
as String type
System.out.println(number);// parameter as integer type
System.out.println(number);// parameter as integer type
Ø
These methods are known as overloaded methods and the process is
referred as method overloading
One way of implementing polymorphism is method overloading.
Garbage collection
The name "garbage collection" implies
that objects that are no longer needed by the program are "garbage"
and can be thrown away. A more accurate and up-to-date metaphor might be
"memory recycling." When an object is no longer referenced by the
program, the HEAP SPACE it occupies must be
recycled so that the space is available for subsequent new objects.
The JVM's heap stores all objects created by an
executing Java program. Objects are created by Java's "new" operator,
and memory for new objects is allocated on the heap at run time. Garbage
collection is the process of automatically freeing objects that are no longer referenced
by the program. This frees the programmer from having to keep track of when to
free allocated memory, thereby preventing many potential bugs and headaches.
Automatic garbage collection
One idea behind Java's automatic memory management model is that programmers should be spared the burden of having to perform manual memory management. In some languages the programmer allocates memory to create any object stored on the heap and is responsible for later manually deallocating that memory to delete any such objects. If a programmer forgets to deallocate memory or writes code that fails to do so in a timely fashion, a memory leak can occur: the program will consume a potentially arbitrarily large amount of memory. In addition, if a region of memory is deallocated twice, the program can become unstable and may crash. Finally, in non garbage collected environments, there is a certain degree of overhead and complexity of user-code to track and finalize allocations.
In Java, this potential problem is avoided by automatic garbage collection. The programmer determines when objects are created, and the Java runtime is responsible for managing the object's lifecycle. The program or other objects can reference an object by holding a reference to it (which, from a low-level point of view, is its address on the heap). When no references to an object remain, the Java garbage collector automatically deletes the unreachable object, freeing memory and preventing a memory leak. Memory leaks may still occur if a programmer's code holds a reference to an object that is no longer needed—in other words, they can still occur but at higher conceptual levels.
The use of garbage collection in a language can also affect programming paradigms. If, for example, the developer assumes that the cost of memory allocation/recollection is low, they may choose to more freely construct objects instead of pre-initializing, holding and reusing them. With the small cost of potential performance penalties (inner-loop construction of large/complex objects), this facilitates thread-isolation (no need to synchronize as different threads work on different object instances) and data-hiding. The use of transient immutable value-objects minimizes side-effect programming.
Comparing Java and C++, it is possible in C++ to implement similar functionality (for example, a memory management model for specific classes can be designed in C++ to improve speed and lower memory fragmentation considerably), with the possible cost of extra development time and some application complexity. In Java, garbage collection is built-in and virtually invisible to the developer. That is, developers may have no notion of when garbage collection will take place as it may not necessarily correlate with any actions being explicitly performed by the code they write. Depending on intended application, this can be beneficial or disadvantageous: the programmer is freed from performing low-level tasks, but at the same time loses the option of writing lower level code.
Why garbage collection?
Garbage collection
relieves programmers from the burden of freeing allocated memory. Knowing when
to explicitly free allocated memory can be very tricky. Giving this job to the
JVM has several advantages. First, it can make programmers more productive.
When programming in non-garbage-collected languages the programmer can spend
many late hours (or days or weeks) chasing down an elusive memory problem
Classes: public, protected
and private
Almost every thing is a class in Java, except for primitives such
as ints, chars, doubles, etc. And all classes(reference types according to the
lang spec) are derived from Object.
The cornerstone of most OO programing languages are classes. So
I'd expect you to understand them before using the AWT.
Java has four types of access levels and one unamed default one:
Ø
public: Accessible everywhere.
Ø
private: Accessible only within the class
Ø
protected: Accessible to those within the same file(package)
and/or derived classes.
Ø
private protected: Acessible to those within the class and derived
classes. This is analogous to C++'s protected member access. Introduced
in JDK beta 2.
The default access level is very similar to
protected.
Exceptions Handling
When an error occurs within a method, the method creates an object
and hands it off to the runtime system. The object, called an exception object, contains
information about the error, including its type and the state of the program
when the error occurred. Creating an exception object and handing it to the runtime
system is called throwing an exception.
After a method throws an exception, the runtime system attempts to find something to handle it. The set of possible "somethings" to handle the exception is the ordered list of methods that had been called to get to the method where the error occurred. The list of methods is known as the call stack.
1. Exception is an error event that can happen during the execution of a program and disrupts its normal flow. Java provides a robust and object oriented way to handle exception scenarios, known as Java Exception HandlingChecked exceptions: A checked exception is an exception that is typically a user error or a problem that cannot be foreseen by the programmer. For example, if a file is to be opened, but the file cannot be found, an exception occurs. These exceptions cannot simply be ignored at the time of compilation.
2. Runtime
exceptions: A runtime exception is an exception that occurs that probably
could have been avoided by the programmer. As opposed to checked exceptions,
runtime exceptions are ignored at the time of compilation.
Errors: These
are not exceptions at all, but problems that arise beyond the control of the
user or the programmer. Errors are typically ignored in your code because you
can rarely do anything about an error.
The throws/throw
Keywords:
If a
method does not handle a checked exception, the method must declare it using
the throwskeyword. The throws keyword appears at the end of a method's
signature.
You
can throw an exception, either a newly instantiated one or an exception that
you just caught, by using the throw keyword. Try to understand the
different in throws and throw keywords.
Multithreading
Java provides built-in support for multithreaded
programming. A multithreaded program contains two or more parts that can run
concurrently. Each part of such a program is called a thread, and each thread
defines a separate path of execution.
A multithreading is a specialized form of
multitasking. Multithreading requires less overhead than multitasking
processing.
Multithreading enables you to write very efficient
programs that make maximum use of the CPU, because idle time can be kept to a
minimum.
Stages are explained here:
1. New: A new thread begins its life cycle in the new
state. It remains in this state until the program starts the thread. It is also
referred to as a born thread.
2. Runnable: After a newly born thread is started, the
thread becomes runnable. A thread in this state is considered to be executing
its task.
3. Waiting: Sometimes, a thread transitions to the
waiting state while the thread waits for another thread to perform a task. A
thread transitions back to the runnable state only when another thread signals
the waiting thread to continue executing.
4. Timed waiting: A runnable thread can enter the timed
waiting state for a specified interval of time. A thread in this state
transitions back to the runnable state when that time interval expires or when
the event it is waiting for occurs.
5. Terminated: A runnable thread enters the terminated
state when it completes its task or
otherwise terminates.
A thread is a lightweight subprocess, a smallest
unit of processing. It is a separate path of execution. It shares the memory
area of process.
No comments:
Post a Comment