Professional Documents
Culture Documents
Java Course
Java Course
active forums, Stackoverflow, open source organizations and several Java user
group to help everything.
7) Java is FREE
People like FREE things, Don't you? So if a programmer want to learn a
programming language, or a organization wants to use a technology, COST is an
important factor. Since Java is free from start, i.e. you don't need to pay anything to
create Java application. This FREE thing also helped Java to become popular among
individual programmers, and among large organizations.
8) Excellent documentation support - Javadoc
It's great piece of documentation, which tells lot of things about Java API. I think
without Javadoc documentation, Java wouldn't be as popular, and it's one of the
main reason, Why Java is best programming language. Not everyone has time and
intention to look at code to learn what a method do or how to use a class. Javadoc
made learning easy, and provide an excellent reference while coding in Java. With
advent of IDE, you don't even need to look Javadoc explicitly in browser, but you
can get all information in your IDE window itself.
9) Java is Platform Independent
In 1990s, this was the main reason of Java's popularity. Idea of platform
independence is great, and Java's tag line "write once run anywhere" was
enticing enough to attract lots of new development in Java. This is still one of the
reason of Java being best programming language, most of Java applications are
developed in Windows environment and run in UNIX platform.
10) Java is everywhere
Yes, Java is everywhere, it's on desktop, it's on mobile, it's on card, almost
everywhere and so is Java programmers. I think Java programmer out number any
other programming language professional.
Introduction
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
2
Philosophy
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.
To achieve the goals of networking support and remote code execution, Java
programmers sometimes find it necessary to use extensions such as CORBA,
Internet Communications Engine, or OSGi.
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
3
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.
Platform independence
The second characteristic, platform independence, means that programs written in
the Java language must run similarly on diverse hardware. One should be able to
write a program once and run it anywhere. This is achieved by most Java compilers
by compiling the Java language code "halfway" to bytecode (specifically Java
bytecode)simplified machine instructions specific to the Java platform. The code is
then run on a virtual machine (VM), a program written in native code on the host
hardware that interprets and executes generic Java bytecode. Further, standardized
libraries are provided to allow access to features of the host machines (such as
graphics, threading and networking) in unified ways. Note that, although there's an
explicit compiling stage, at some point, the Java bytecode is interpreted or
converted to native machine instructions by the JIT compiler. There are also
implementations of Java compilers that compile to native object code, such as GCJ,
removing the intermediate bytecode stage, but the output of these compilers can
only be run on a single architecture. Sun's license for Java insists that all
implementations be "compatible". This resulted in a legal dispute with Microsoft
after Sun claimed that the Microsoft implementation did not support the RMI and JNI
interfaces and had added platform-specific features of their own. In response,
Microsoft no longer ships Java with Windows, and in recent versions of Windows,
Internet Explorer cannot support Java applets without a third-party plug-in.
However, Sun and others have made available Java run-time systems at no cost for
those and other versions of Windows. The first implementations of the language
used an interpreted virtual machine to achieve portability. These implementations
produced programs that ran more slowly than programs compiled to native
executables, for instance written in C or C++, so the language suffered a reputation
for poor performance. More recent JVM implementations produce programs that run
significantly faster than before, using multiple techniques. The first technique is to
simply compile directly into native code like a more traditional compiler, skipping
bytecodes entirely. This achieves good performance, but at the expense of
portability. Another technique, known as just-in-time compilation (JIT), translates the
Java bytecodes into native code at the time that the program is run which results in
a program that executes faster than interpreted code but also incurs compilation
overhead during execution. More sophisticated VMs use dynamic recompilation, in
which the VM can analyze the behavior of the running program and selectively
recompile and optimize critical parts of the program. Dynamic recompilation can
achieve optimizations superior to static compilation because the dynamic compiler
can base optimizations on knowledge about the runtime environment and the set of
loaded classes. JIT compilation and dynamic recompilation allow Java programs to
take advantage of the speed of native code without losing portability. Portability is a
technically difficult goal to achieve, and Java's success at that goal has been mixed.
Although it is indeed possible to write programs for the Java platform that behave
4
consistently across many host platforms, the large number of available platforms
with small errors or inconsistencies led some to parody Sun's "Write once, run
anywhere" slogan as "Write once, debug everywhere".
Platform-independent Java is however very successful with server-side applications,
such as Web services, servlets, and Enterprise JavaBeans, as well as with Embedded
systems based on OSGi, using Embedded Java environments.
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
6
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);
}
}
7
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_CLOSEthis 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.
Comparison
8
C++
Compatibility
Java
backwards
compatible,
backwards
compatibility
with
including C
previous versions
Focus
execution efficiency
developer productivity
Freedom
Memory
arbitrary
memory
Management
possible
Code
concise expression
Type Safety
type
casting
is
access
explicit operation
restricted
greatly
Programming
procedural or object-oriented
object-oriented
Operators
operator overloading
Preprocessor
yes
no
Main Advantage
powerful
Paradigm
language
capabilities
of
Setup environment
Install latest version of JDK
Setting up the PATH:
In the Edit System Variable (or New System Variable) window, specify the
value of the PATH environment variable. Click OK. Close all remaining
windows by clicking OK.
PATH value might be C:\Program Files\Java\jdk1.8.0_11\bin
Keywords
abstract
continue
package
for
new
switch
synchronized
boolean
implements
do
if
protected
throw
instanceof
else
import
byte
assert default
private
this
goto
break double
public throws
case enum
10
return transient
interface
catch extends
strictfp
int
short try
volatile
char
const float
final
native super
Keywords Categories
Data Types (8)
1. byte is a Java primitive type.
A byte can store an integer value in the range [128, 127].
Examples:
byte b = 124;
Remarks:
The Byte class is a wrapper class for the byte primitive type. It defines
MIN_VALUE and MAX_VALUE constants representing the range of values
for this type.
2. short is a Java primitive type.
A short variable may store a 16bit signed integer.
Examples:
short number = 5;
short octalNumber = 0077;
short hexNumber = 0xff;
Remarks:
The Short class is a wrapper class for the short primitive type. It
defines MIN_VALUE and MAX_VALUE constants representing the range
of values for this type.
3. int is a Java primitive type.
A int variable may store a 32bit integer value.
Examples:
int number = 5;
int octalNumber = 00377;
int hexNumber = 0xff;
Remarks:
The Integer class is a wrapper class for the int primitive type. It defines
MIN_VALUE and MAX_VALUE constants representing the range of values
for this type.
4. long is a Java primitive type.
A long variable may store a 64bit signed integer.
Examples:
long number = 5;
long anotherNumber = 34590L;
long octalNumber = 0377;
11
ratio = .01;
diameter = 6.15;
height = 1.35E03;
// 1.35 * 103 or 1350.0
height = 1e2; // 1.0 * 102 or 0.01
Remarks:
}
Remarks:
A case block does not have an implicit ending point. A break statement is
typically used at the end of each case block to exit the switch statement.
Without a break statement, the flow of execution will flow into all following
case and/or default blocks.
A default block does not have an implicit ending point. A break statement
is typically used at the end of each case or default block to exit the switch
statement upon completion of the block.
Without a default statement, a switch statement whose argument
matches no case blocks will do nothing.
*The default access for all class members is package access, meaning
that unless a specific access control modifier is present the class members
are accessible from within any class in the same package
The for statement takes the form for (initialize; condition; increment)
The initialize statement is executed once as the flow of control enters for
statement.
The condition is evaluated before each execution of the body of the loop.
The body of the loop is executed if the condition is true.
The increment statement is executed after each execution of the body of
the loop, before the condition evaluated for the next iteration.
while (!found)
{
<statements>
}
9. do keyword specifies a loop whose condition is checked at the end of each
iteration.
Examples:
do
{
<statements>
}
while (!found);
Remarks:
10.
continue keyword is used to skip to the next iteration of a for, while,
or do loop.
Examples:
for (i=0; i<max; i++)
{
<statements>
if (<done with this iteration>)
{
continue;
}
<statements>
}
Remarks:
17
Remarks:
The opening and closing curly braces { } are part of the syntax of the try
clause and may not be omitted even if the clause contains a single
statement.
Every try block must have at least one catch or finally clause.
If a particular exception class is not handled by any catch clause, the
exception propagates up the call stack to the next enclosing try block,
recursively. If an exception is not caught by any enclosing try block, the
Java interpretor will exit with an error message and stack trace.
try {
<block that may throw different exceptions>
}
catch (FooException e){
<code to handle FooException e>
18
} catch (BarException e) {
<code to handle BarException e>
}
Remarks:
The opening and closing curly braces { } are part of the syntax of the
catch clause and may not be omitted even if the clause contains a single
statement.
If a particular exception class is not handled by any catch clause, the
exception propagates up the call stack to the next enclosing try block,
recursively. If an exception is not caught by any enclosing try block, the
Java interpretor will exit with an error message and stack trace.
try {
<code to handle exception e>
} catch (<java.lang.Exception or subclass> e) {
} finally {
<statements that execute with or without exception>
}
Remarks:
The opening and closing curly braces { } are part of the syntax of the
finally clause and may not be omitted even if the clause contains a single
statement.
If any portion of the try block is executed, the code in a finally block is
always guaranteed to be executed whether an exception occurs or not
and independent of whether the try or catch blocks contain return,
continue or break statements.
In the absence of exceptions, control flows through the try block and then
into the finally block.
If an exception occurs during execution of the try block and the
appropriate catch block contains a break, continue or return statement,
control flows through the finally block before the break, continue or return
19
occurs.
4. throw keyword is used to raise an exception.
Examples:
import java.io.IOException;
Remarks:
20
}
}
}
Remarks:
The
throws
keyword
takes
a
commaseparated
list
of
java.lang.Throwables as an argument.
Any method that throws an exception that is not a RuntimeException must
also declare the exceptions it throws using a throws modifier on the
method declaration.
The caller of a method with a throws clause is required to enclose the
method call in a trycatch block.
Remarks:
The argument following the new keyword must be a class name followed
by a series of constructor arguments in required parentheses.
The collection of arguments must match the signature of a constructor for
the class.
The type of the variable on the left side of the = must be
assignmentcompatible with the class or interface being instantiated.
Remarks:
Remarks:
String s;
if (s != null) {
<statements>
}
22
Remarks:
Method (2)
1. void keyword represents a empty(nothing, no value) type.
Examples:
public class MyClass {
public void doSomething() {
<statements>
return;
}
}
Remarks:
void may be used as the return type of a method to indicate the method does not
return a value.
2. return keyword causes a method to return to the method that called it,
passing a value that matches the return type of the returning method.
Examples:
public void myVoidMethod() {
<statements>
return;
}
Remarks:
If the method has a nonvoid return type, the return statement must have
an argument of the same or a compatible type.
24
}
2. extends keyword is used in a class or interface declaration to indicate
that the class or interface being declared is a subclass of the class or
interface whose name follows the extends keyword.
Examples:
public class Rectangle extends Polygon {
}
Remarks:
In the example above, the Rectangle class inherits all of the public
and protected variables and methods of the Polygon class.
The Rectangle class may override any nonfinal method of the Polygon
class.
A class may only extend one other class.
5. package keyword specifies the Java package in which the classes declared in a Java
source file reside.
Examples:
package com.mycompany;
public class MyClass {
}
Remarks:
6. import keyword makes one class or all classes in a package visible in the
current Java source file. Imported classes can be referened without the use of
fullyqualified class names.
Examples:
import java.io.File;
import java.net.*;
Remarks:
Many Java programmers use only specific import statements (no '*') to
avoid ambiguity when multiple packages contain classes of the same
name.
Modifiers (12)
1. public keyword is an access control modifier that may be applied to a class,
a method or a field (a variable declared in a class).
Examples:
public class MyPublicClass {
public class MyPrivateClass {
}
26
public int i;
public String myMethod() {
<statements>
}
}
Remarks:
A public class, method or field may only be referenced from any other
class or package.
package pack;
class B{
public void printMsg(){
A a = new A();
a.msg();
}
}
Remarks:
Accessing the default modifier outside the package will compile time
error.
}
static int getNumObjects() {
}
}
Remarks:
6. final keyword may be applied to a class, indicating the class may not be
extended (subclassed).
The final keyword may be applied to a method, indicating the method may
not be overridden in any subclass.
Examples:
public final class MyFinalClass {
}
public class MyClass
{
public final String myFinalMethod() {
<statements>
}
29
}
Remarks:
A class may never be both abstract and final. abstract means the class
must be extended, while final means it cannot be.
A method may never be both abstract and final. abstract means the
method must be overridden, while final means it cannot be.
Object someObj;
public String myMethod() {
<statements
>
synchronized
(someObj) {
<statements affecting someObj>
}
}
}
Remarks:
10.
volatile keyword may be used to indicate a member variable that
may be modified asynchronously by more than one thread.
31
Examples:
public class MyClass {
volatile int sharedValue;
}
Remarks:
volatile is intended to guarantee that all threads see the same value of
the specified variable.
11.
Transient keyword may be applied to member variables of a class
to indicate that the member variable should not be serialized when the
containing class instance is serialized.
Examples:
public class MyClass {
private transient String password;
}
12.
native keyword may be applied to a method to indicate that the
method is implemented in a language other then Java.
Examples:
native String getProcessorType()
Methods categories
Signature Definition: Two of the components of a method declaration comprise the
method signaturethe method's name and the parameter types.
1. instance methods (call via object)
a. It is a method which belongs to the object
b. An instance method can access static and non-static data.
c. An instance method can call static and non-static methods
Syntax :
Class obj = new Class();
obj.method();
2. static methods (call via class)
a. It is a method which belongs to the class and not to the
object(instance)
b. A static method can access only static data. It can not access nonstatic data (instance variables)
c. A static method can call only other static methods and cannot call a
non-static method from it.
d. A static method can be accessed directly by the class name and
doesnt need any object
e. Syntax : <class-name>.<method-name>
32
f.
3. normal methods ?
a. It is a method which belongs to the object
b. A normal method can access static and non-static data.
c. A normal method can call static and non-static methods.
d. A normal method did not have static, final keyword in signature.
Syntax :
Public void printData(){
// definition
}
4. abstract methods (declare in abstract class)
a. An abstract method is a method that is declared without an
implementation
b. It just has a method signature
5. accessor methods (getter )
An accessor method is used to return the value of a private or protected field. It follows a naming
scheme prefixing the word "get" to the start of the method name. For example let's add accessor
methods for name:
class Player {
protected name
//Accessor for name
public String getName() {
return this.name;
}
}
you can access the value of protected name through the object such as:
Player ball = new Player()
System.out.println(ball.getName())
6. mutator methods (setter)
A mutator method is used to set a value of a private or protected field. It follows a naming
scheme prefixing the word "set" to the start of the method name. For example, let's add mutator
fields for name:
class Player{
protected name
//Mutator for name
public void setName(String name) {
this.name= name;
}
}
now we can set the players name using:
Player ball = new Player()
ball.setName('David');
33
Example:
class Human{
public final void eat()
{
System.out.println("Human is eating");
}
}
class Boy extends Human{
// throw compile time exception
public void eat(){
System.out.println("Boy is eating");
}
public static void main( String args[]) {
Boy obj = new Boy();
obj.eat();
}
}
10.
native
What do we do with the vast amount of existing code? The trick is to use the
so-called native method interface
11.
strictfp
It makes sure that floating point calculations result precisely the same
regardless of the underlying operating system and hardware platform
Example:
public strictfp void method() {
...
}
12.
public method
A method that is public means that any class can access it. This is useful for
when the method should be accessible by your entire application
Example:
class Human{
public void eat()
{
System.out.println("Human is eating");
}
}
Public class TestHuman {
public static void main( String args[]) {
Human obj = new Human();
obj.eat();
}
}
13.
private methods
A method that is private means that only declared class can access it. There
is actually only one way a private method can be accessed: within the class
that defined them in the place.
35
Example:
class Human{
private void eat()
{
System.out.println("Human is eating");
}
}
Public class TestHuman {
public static void main( String args[]) {
Human obj = new Human();
// throw compile time exception
obj.eat();
}
}
14.protected methods
Protected methods allow the class itself to access them, classes inside of the
same package to access them, and subclasses of that class to access them.
15.
default method
No access modifier at all means that the method or variable defaults to
package protected. This means that only the same class and any class in the
same package has access.
16.
factory method (return an object)
a. instance factory method : return same object via object reference
String name = "SAFER TECH"
String name2 = name.subString(2, 6);
b. static factory method: return new Object via Class reference
Class c = Class.forName("class.path"),
Calendar cal = Calendar.getInstance()
Integer temp = Integer.valueOf(10)
c. pattern factory : return another object via object reference
Human man = LivingFactory.getHuman();
StringBuffer sb = new StringBuffer("SAFER TECH");
String text = sb.toString();
17.
synchronized method
The synchronization is mainly used to
To prevent thread interference.
To prevent consistency problem.
Here is a synchronized method syntax:
public synchronized void add(int value){
this.count += value;
}
Notice the use of the synchronized keyword in the method declaration. This
tells Java that the method is synchronized.
36
37