Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 37

Why you should learn Java Programming Language?

Why Java is best


Programming language?
Here is my list of 10 reasons, which I tell anyone who asks my opinion about
learning Java, and whether Java is a best programming language in terms of
opportunities, development and community support.
1) Java is Easy to learn
Many would be surprised to see this one of the top reason for learning Java, or
considering it as best programming language, but it is. If you have a steep learning
curve, it would be difficult to get productive in a short span of time, which is the
case with most of professional project. Java has fluent English like syntax with
minimum magic characters e.g. Generics angle brackets, which makes it easy to
read Java program and learn quickly. Once a programmer is familiar with initial
hurdles with installing JDK and setting up PATH and understand How Classpath
works, it's pretty easy to write program in Java.
2) Java is an Object Oriented Programming Language
Another reason, which made Java popular is that it's an Object Oriented
Programming language. Developing OOPS application is much easier, and it also
helps to keep system modular, flexible and extensible. Once you have knowledge of
key OOPS concept like Abstraction, Encapsulation, Polymorphism and Inheritance,
you can use all those with Java. Java itself embodies many best practices and design
pattern in it's library. Java is one of the few close to 100% OOPS programming
language
3) Java has Rich API
One more reason of Java programming language's huge success is it's Rich API and
most importantly it's highly visible because come with Java installation.
4) Powerful development tools e.g. Eclipse , NetBeans
Believe it or not, Eclipse and NetBeans has played a huge role to make Java one of
the best programming languages. Coding in IDE is a pleasure, especially if you have
coded in DOS Editor or Notepad. They not only helps in code completion but also
provides powerful debugging capability, which is essential for real world
development. Integrated Development Environment (IDE) made Java development
much easier, faster and fluent. It's easy to search, refactor and read code using
IDEs.
Apart from IDE, Java platform also has several other tools e.g.. Maven and ANT for
building Java applications, decompilers, JConsole, Visual VM for monitoring Heap
usage etc.
5) Great collection of Open Source libraries
Open source libraries ensures that Java should be used everywhere. Apache,
Google, and other organization has contributed lot of great libraries, which makes
Java development easy, faster and cost effective. There are framework like Spring,
Struts, Maven, which ensures that Java development follows best practices of
software craftsmanship, promotes use of design patterns and assisted Java
developers to get there job done.
6) Wonderful community support
Community is the biggest strength of Java programming language and platform. No
matter, how good a language is, it wouldn't survive, if there is no community to
support, help and share their knowledge. Java has been very lucky, it has lots of
1

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

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.

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.

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 neededin 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 valueobjects 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.
5

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.

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.

Comparison
8

C++
Compatibility

Java

backwards

compatible,

backwards

compatibility

with

including C

previous versions

Focus

execution efficiency

developer productivity

Freedom

trusts the programmer

imposes some constraints to the


programmer

Memory

arbitrary

memory

Management

possible

Code

concise expression

Type Safety

type

casting

is

access

memory access only through objects

explicit operation
restricted

only compatible types can be cast

greatly
Programming

procedural or object-oriented

object-oriented

Operators

operator overloading

meaning of operators immutable

Preprocessor

yes

no

Main Advantage

powerful

Paradigm

language

capabilities

of

feature-rich, easy to use standard


library

Setup environment
Install latest version of JDK
Setting up the PATH:

From the desktop, right click the My Computer icon.


Choose Properties from the context menu.
Click the Advanced system settings link.
Click Environment Variables. In the section System Variables, find the
PATH environment variable and select it. Click Edit. If the PATH environment
variable does not exist, click New.
9

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

Set the JAVA_HOME Variable

Once you have the JDK installation path:


Right-click the My Computer icon on your desktop and select Properties.
Click the Advanced system settings link, then click the Environment
Variables button.
Under System Variables, click New.
Enter the variable name as JAVA_HOME.
Enter the variable value as the installation path for the Java Development Kit.
Click OK.
JAVA_HOME value might be C:\Program Files\Java\jdk1.8.0_11

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

static void class finally long


while

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

long hexNumber = 0xffl;


Remarks:
The Long class is a wrapper class for the long primitive type. It
defines MIN_VALUE and MAX_VALUE constants representing the range
of values for this type.

5. float is a Java primitive type.


A float variable may store a singleprecision floating point value.
Examples:
float ratio = .01;
float diameter = 6.15;
float height = 1.35E03; // 1.35 * 103 or 1350.0
float height = 1e2;
// 1.0 * 102 or 0.01
6. double is a Java primitive type.
A double variable may store a doubleprecision floating point value.
Examples:
double
double
double
double

ratio = .01;
diameter = 6.15;
height = 1.35E03;
// 1.35 * 103 or 1350.0
height = 1e2; // 1.0 * 102 or 0.01

7. char is a Java primitive type.


A char variable can store a single Unicode character.
Examples:
char delimiter = ';';
Remarks:

The following char constants are available:


o \b Backspace
o \f Form feed
o \n Newline
o \r Carriage return
o \t Horizontal tab
o \' Single quote
o \" Double quote
o \" Backslash
o \xxx The Latin1 character with the encoding xxx. The \x
and \xx forms are legal but may lead to confusion.
o \uxxxx The Unicode character with the hexadecimal encoding
xxxx.
The Character class includes useful static methods for dealing with
12

char variables, including isDigit(), isLetter(), isWhitespace() and


toUpperCase().char values are unsigned.
8. boolean is a Java primitive type.
A boolean variable may take on one of the values true or false.
Examples:
boolean valid = true;
Remarks:

A boolean variable may only take on the values true or false.


A boolean may not be converted to or from any numeric type.
The Boolean class is a wrapper class for the boolean primitive type.

Flow control (10)


1. if keyword indicates conditional execution of a block. The condition must
evaluate to a boolean value.
Examples:
if (condition)
{
<statements>
}
Remarks:

Expressions containing boolean operands can contain only boolean


operands.

2. else keyword is always used in association with the if keyword in an ifelse


statement. The else clause is optional and is executed if the if condition is
false.
Examples:
if (condition){
<statements>
} else {
<statements>
}
13

Remarks:

An if statement may have an optional else clause containing code that is


executed if the condition is false.
Expressions containing boolean operands can contain only boolean
operands.

3. switch statement is used to select execution of one of multiple code blocks


based on an expression.
Examples:
int arg = <some value>;
switch (arg) {
case 1:
<statements> break;
case 2:
<statements> break;
default:
<statements> break;
}
Remarks:

The switch condition must evaluate to a byte, char, short or int.


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.

4. case is used to label each branch in a switch statement.


Examples:
int arg = <some value>;
switch (arg) {
case 1:
<statements> break;
case 2:
<statements> break;
default:
<statements> break;
14

}
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.

5. *default keyword is used to label the default branch in a switch statement.


Examples:
int arg = <some value>;
switch (arg) {
case 1:
<statements> break;
case 2:
<statements> break;
default:
<statements> break;
}
Remarks:

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

6. break keyword is used to prematurely exit a for, while, or do loop or to mark


the end of a case block in a switch statement.
Examples:
for (i=0; i<max; i++) {
if (<loop finished early>) {
break;
}
}
15

int arg = <some value>;


switch (arg) {
case 1:
<statements>
break;
case 2:
<statements>
break;
default:
<statements>
break;
}
Remarks:

break always exits the innermost enclosing while, for, do or switch


statement.

7. for keyword specifies a loop whose condition is checked before each


iteration.
Examples:
int i;
for (i=0; i<max; i++)
{
<statements>
}
Remarks:

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.

8. While keyword specifies a loop that is repeated as long as a condition is true.


Examples:
16

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:

The body of a do loop is always executed at least once.


The semicolon after the condition expression is always required.

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:

continue always skips to the next iteration of the innermost enclosing


while, for or do statement.

17

Exception handling (5)


1. try keyword is used to enclose blocks of statements that might throw
exceptions.
Examples:
try {
<code to handle exception e>
} catch (<java.lang.Exception or subclass> e) {

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.

2. catch keyword is used to define exception handling blocks in trycatch or


trycatchfinally statements.
Examples:
try {
<code to handle exception e>
} catch (<java.lang.Exception or subclass> e) {

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.

3. finally keyword is used to define a block that is always executed in a


trycatchfinally statement. A finally block typically contains cleanup code
that recovers from partial execution of a try block.
Examples:

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;

public class MyClass


{
public method readFile(String filename) throws IOException{
<statements>
if (error) {
throw new IOException("error reading file");
}
}
}

Remarks:

The throw statement takes a java.lang.Throwable as an argument. The


Throwable is propagated up the call stack until it is caught by an
appropriate catch block.

5. throws keyword may be applied to a method to indicate the method raises


particular types of exceptions.
Examples:
import java.io.IOException;

public class MyClass


{
public method readFile(String filename) throws IOException{
<statements>
if (error) {
throw new IOException("error reading file");

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.

Object level (4)


1. new keyword is used to create a new instance of a class.
Examples:
String sName = new String();
Float fVal = new Float(0.15);

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.

2. super keyword refers to the superclass of the class.


Examples:

public class MyClass {


public MyClass(String arg)
{
super(arg);
}
21

public String myStringMethod() {


return super.otherStringMethod();
}
}

Remarks:

super as a standalone statement represents a call to a constructor of the


superclass.
super.<methodName>() represents a call to a method of the superclass.
This usage is only necessary when calling a method that is overridden in
this class in order to specify that the method should be called on the
superclass.

3. Instanceof keyword is used to determine the class of an object.


Examples:
if (node instanceof TreeNode) {
<statements>
}

Remarks:

In the example above, if node is an instance of the TreeNode class or is an


instance of a subclass of TreeNode, the instanceof expression evaluates to
true.

4. Null is a Java reserved word representing no value.


Examples:
Integer i;
i = null;

String s;
if (s != null) {
<statements>
}
22

Remarks:

Assigning null to a nonprimitive variable has the effect of releasing the


object to which the variable previously referred.
null cannot be assigned to variables of primitive types (byte, short, int,
long, char, float, double, boolean)

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;
}

public String myStringMethod() {


String s = "my response";
return s;
23

public int myIntMethod() {


int i = 5;
return i;
}

Remarks:

If the method has a nonvoid return type, the return statement must have
an argument of the same or a compatible type.

Source file (6)


1. class keyword is used to declare a new Java class, which is a collection of
related variables and/or methods.
Classes are the basic building blocks of objectoriented programming. A
class typically represents some realworld entity such as a geometric Shape
or a Person. A class is a template for an object. Every object is an instance of
a class.
To use a class, you instantiate an object of the class, typically with the new
operator, then call the classes methods to access the features of the class.
Examples:
public class Rectangle {
float width; float height;

public Rectangle(float w, float h) {


width = w; height = h;
}
public float getWidth() {
return width;
}
public float getHeight(){
return height;
}

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.

3. interface keyword is used to declare a new Java interface, which is a


collection of methods.
Interfaces are a powerful feature of the Java language. Any class may
declare that it implements one or more interfaces, meaining it implements
all of the methods defined in those interfaces.
Examples:
public interface IPolygon {
public float getArea();
public int getNumberOfSides();
public int getCircumference();
}
Remarks:

Any class that implements an interface must provide implementations for


all methods in that interface.
A single class may implement multiple interfaces.

4. implements keyword is used in a class declaration to indicate that the


class being declared provides implementations for all methods declared
in the interface whose name follows the implements keyword.
Examples:
public class Truck implements IVehicle {
// implement all IVehicle methods
}
Remarks:
25

In the example above, the Truck class must provide implementations


for all methods declared in the IVehicle interface.
The Truck class is otherwise independent; it may declare additional
methods and variables and may extend another class.
A single class may implement multiple interfaces.

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:

The package statement, if present, must be the first noncomment text in


a Java source file.
In the example above, the fullyqualified class name of the MyClass class
is com.mycompany.MyClass.
If a Java source file does not contain a package statement, the
classes defined in the file are in the default package.

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.

2. protected 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 {
protected class MyPrivateClass{
}
protected int i;
protected String myMethod() {
<statements>
}
}
Remarks:

A protected class, method or field may be referenced from within the


class in which it is declared, any other classes in the same package, and
any subclasses regardless of the package in which a subclass is declared.

3. *default (non-modifier) If you don't use any modifier, it is treated as


default by-default. The default modifier is accessible only within package.
Examples:
package pack;
class A{
void msg(){System.out.println("Hello");}
}
27

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.

4. private 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 {
private class MyPrivateClass {
}
private int i;
private String myMethod(){
<statements>
}
}
Remarks:

A private (inner) class, method or field may only be referenced from


within the class in which it is declared. It is not visible outside the
class or to subclasses.

5. static keyword may be applied to an inner class (a class defined within


another class), method or field (a member variable of a class).
Examples:
public class MyPublicClass {
public final static int MAX_OBJECTS
= 100; static int _numObjects = 0;
static class MyStaticClass {
28

}
static int getNumObjects() {
}
}
Remarks:

In general, the static keyword means that the entity to which it is


applied is available outside any particular instance of the class in which
the entity is declared.
A static (inner) class may be instantiated and reference by other classes
as though it were a toplevel class.
In the example above, code in another class could instantiate the
MyStaticClass class by qualifying it's name with the containing class
name, as MyClass.MyStaticClass.
A static field (member variable of a class) exists once across all instances
of the class.
A static method may be called from outside the class without first
instantiating the class. Such a reference always includes the class
name as a qualifier of the method call. In the example above code
outside the MyClass class would invoke the getNumObjects() static
method as MyClass.getNumObjects().
The pattern:
public final static <type> varName = <value>;
is commonly used to declare class constants that may be used from
outside the class. A reference to such a constant is qualified with the class
name. In the example above, another class could reference the
MAX_OBJECTS constant as MyClass.MAX_OBJECTS

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.

7. abstract keyword may modify a class or a method. An abstract class can be


extended (subclass) but cannot be instantiated directly.
An abstract method is not implemented in the class in which it is
declared, but must be overridden in some subclass.
Examples:
public abstract class MyClass {
}
public abstract String myMethod();
Remarks:

A class with an abstract method is inherently abstract and must be


declared abstract.
An abstract class cannot be instantiated.
A subclass of an abstract class can only be instantiated if it
implements all of the abstract methods of its superclass. Such classes
are called concrete classes to differentiate them from abstract classes.
If a subclass of an abstract class does not implement all of the abstract
methods of its superclass, the subclass is also abstract.
The abstract keyword cannot be applied to methods that are static,
private or final, since such methods cannot be overridden and therefore
cannot be implemented in subclasses.

8. synchronized keyword may be applied to a method or statement block and


provides protection for critical sections that should only be executed by one
thread at a time.
Examples:
public class MyClass {
public synchronized static String mySyncStaticMethod() {
}
public synchronized String mySyncMethod(){
}
}
public class MyOtherClass {
30

Object someObj;
public String myMethod() {
<statements
>
synchronized
(someObj) {
<statements affecting someObj>
}
}
}
Remarks:

The synchronized keyword prevents a critical section of code from being


executed by more than one thread at a time.
When applied to a static method, as with MySyncStaticMethod in the
examples above, the entire class is locked while the method is being
executed by one thread at a time.
When applied to an instance method, as with MySyncMethod in the
examples above, the instance is locked while being accessed by one
thread at at time.
When applied to an object or array, the object or array is locked while the
associated code block is executed by one thread at at time.
9. strictfp keyword restricts floating-point calculations to ensure portability.
Examples:
public strictfp class MyFPclass {
// ... contents of class here ...
}

public class Myclass {


public strictfp void MyFPMethod(){
// ... contents of methd here ...
}
}
Remarks:

It can be used on classes, interfaces and non-abstract methods.


When applied to a method, it causes all calculations inside the method to
use strict floating-point math.
When applied to a class, all calculations inside the class use strict
floating-point math.

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.

A static method cannot refer to this or super keywords in anyway

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

7. overridden (sub class change functionality)


Declaring a method in subclass which is already present in parent class known as method
overriding.
Example:
class Human{
public void eat()
{
System.out.println("Human is eating");
}
}
class Boy extends Human{
public void eat(){
System.out.println("Boy is eating");
}
public static void main( String args[]) {
Boy obj = new Boy();
obj.eat();
}
}
Here Boy class extends Human class. Both the classes have a common method void eat(). Boy
class is giving its own implementation to the eat() method or in other words it is overriding the
method eat().
8. overloaded (different signature)
Method Overloading is a feature that allows a class to have two or more methods having same
name, if their argument lists are different
Argument lists could differ in
I.
Number of parameters.
II.
Data type of parameters.
III.
Sequence of Data type of parameters.
Method overloading is also known as Static Polymorphism.
Example:
class DisplayOverloading {
public void disp(char c) {
System.out.println(c);
}
public void disp(char c, int num) {
System.out.println(c + " "+num);
}
}
class Sample {
public static void main(String args[]) {
DisplayOverloading obj = new DisplayOverloading();
obj.disp('a');
obj.disp('a',10);
}
}
9. final
Stop to override method in sub classes
34

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

You might also like