You are on page 1of 114

Java

Java

Personal Information

Name :- Ritesh A. Gandhi

Roll No :- 05B007

STD :- T.y.B.C.A. [SEM:-5]

Subject :- Java
Java

INDEX

Chapter No. Chapter Name Page No.


1 Introduction Of Java 5
2 Java Tools 14
3 Java Enable Browsers 28
4 Installing Java 30
5 Comment With Java 35
6 Java Syntax 49
7 Array 62
8 Control Statements 68
9 Classes, Object & Methods 80
10 Inheritance 88
11 Abstract Method & Classes 93
12 Package 94
13 Interface in Java 105
14 Exception Handling 107
15 Input & Output 109
16 Applets 118
Java

1. Introduction of Java

Java as a general purpose language:


Java is an Object oriented application programming language developed by Sun
Microsystems. Java is a very powerful general-purpose programming language. It is a
stupendous programming language which is not confined to machine applications only. Java is
more than just a tool for building transportable multimedia applications. Due to its versatility,
it is a platform independent language, be it a hardware platform or any operating system.
Java programs run as quickly and efficiently as C++ programs due to the implementation of
the JVM (Java Virtual Machine). It adds to C++ in the areas of automatic memory
management. Moreover it also extends the language support for multithreaded applications.
T he Java applet API is a framework that allows Java-enabled Web browsers to manage and
display embedded Java applications within. Java applications can be executed by any software
that implements the Java run-time system. Any kind of applications can be written in Java
programming language such as any small or large applications, or any standalone application.
Java as an Object Oriented Language:
Introduction: In this section, we will discuss the OOPs concepts along with their role in
developing the java applications and programs.
OOP stands for Object Oriented Programming. This is a technique used to develop
programs revolving around the real world entities. In OOPs programming model, programs are
developed around data rather than actions and logics. In OOPs, every real life object has
properties and behavior. Which is achieved through the class and object creation. They contain
properties (variables of some type) and behavior (methods).
OOP provides a better flexibility and compatibility for developing large applications.

There are four main pillars of an Object Oriented Programming Language :


Inheritance:
Inheritance provide the facility to drive one class by another using simple syntax. You can
say that it is a process of creating new class and use the behavior of the existing class by
extending them for reuse the existing code and adding the additional features as you
need. It also use to manage and make well structured software.
Java

Encapsulation:
Encapsulation is the ability to bundle the property and method of the object and also
operate them. It is the mechanism of combining the information and providing the
abstraction as well.
Polymorphism:
As the name suggest one name multiple form, Polymorphism is the way that provide the
different functionality by the functions having the same name based on the signatures of
the methods. There are two type of polymorphism first is run-time polymorphism and
second is compile-time polymorphism.
Dynamic binding:
It is the way that provide the maximum functionality to a program for a specific type at
runtime. There are two type of binding first is dynamic binding and second is static
binding.

As the languages like C, C++ fulfills the above four characteristics yet they are not fully
object oriented languages because they are structured as well as object oriented languages. But
in case of java, it is a fully Object Oriented language because object is at the outer most level
of data structure in java. No stand alone methods, constants, and variables are there in java.
Everything in java is object even the primitive data types can also be converted into object by
using the wrapper class.
Class: A class defines the properties and behavior (variables and methods) that is shared by all
its objects. It is a blue print for the creation of objects. The primitive data type and keyword
void is work as a class object.
Object: Object is the basic entity of object oriented programming language. Class itself does
nothing but the real functionality is achieved through their objects. Object is an instance of the
class. It takes the properties (variables) and uses the behavior (methods) defined in the class.
The Encapsulation, Inheritance and Polymorphism are main pillars of OOPs. These have
been described below:
Encapsulation:
Encapsulation is the process of binding together the methods and data variables as a single
entity. It keeps both the data and functionality code safe from the outside world. It hides the
data within the class and makes it available only through the methods. Java provides different
accessibility scopes (public, protected, private ,default) to hide the data from outside. Here we
provide a example in which we create a class "Check" which has a variable "amount" to
store the current amount. Now to manipulate this variable we create a methods and to set the
value of amount we create setAmount() method and to get the value of amount we create
getAmount() method .
Java

Here is the code for "Mainclass" class :


class Check{
private int amount=0;
public int getAmount(){
return amount;
}
public void setAmount(int amt){
amount=amt;
}
}
public class Mainclass{
public static void main(String[] args){
int amt=0;
Check obj= new Check();
obj.setAmount(200);
amt=obj.getAmount();
System.out.println("Your current amount is :"+amt);
}
}

Here the data variable "amount" and methods setAmount() and getAmount() are enclosed
together with in a single entity called the "Check" class. These two methods are used to
manipulate this variable i.e. set and get the current value of amount.
Here is the output of the example:
C:\roseindia>javac
Mainclass.java

C:\roseindia>java
Mainclass
Your current amount is
:200
example:-
Inheritance:
Inheritance allows a class (subclass) to acquire the properties and behavior of another class
(superclass). In java, a class can inherit only one class (superclass) at a time but a class can
Java

have any number of subclasses. It helps to reuse, customize and enhance the existing code. So
it helps to write a code accurately and reduce the development time. Java uses extends
keyword to extend a class.

Here is the code of the example :


class A{
public void fun1(int x){
System.out.println("Int in A is :" + x);
}
}
class B extends A{
public void fun2(int x,int y){
fun1(6); // prints "int in A"
System.out.println("Int in B is :" + x " and "+y);
}
}
public class inherit{
public static void main(String[] args){
B obj= new B();
obj.fun2(2);
}
}

In the above example, class B extends class A and so acquires properties and behavior of class
A. So we can call method of A in class B.
Here is the output of the example:
C:\roseindia>javac
inherit.java

C:\roseindia>java
inherit
Int in A is :6
Int in B is :2 and 5
example:-
Polymorphism :
Polymorphism allows one interface to be used for a set of actions i.e. one name may refer to
different functionality. Polymorphism allows a object to accept different requests of a client (it
then properly interprets the request like choosing appropriate method) and responds according
to the current state of the runtime system, all without bothering the user.
Java

There are two types of polymorphism :


1. Compile-time polymorphism
2. Runtime Polymorphism

In compiletime Polymorphism, method to be invoked is determined at the compile time.


Compile time polymorphism is supported through the method overloading concept in java.
Method overloading means having multiple methods with same name but with different
signature (number, type and order of parameters).

Here is the code of the example :


class A
{
public void fun1(int x)
{
System.out.println("The value of class A is : " + x);
}
public void fun1(int x,int y){
System.out.println("The value of class B is : " + x + " and " + y);
}
}
public class polyone{
public static void main(String[] args){
A obj=new A();
// Here compiler decides that fun1(int) is to be called and "int" will be printed.
obj.fun1(2);
// Here compiler decides that fun1(int,int)is to be called and "int and int" will be printed.
obj.fun1(2,3);
}
}

Here is the output of the example:


C:\roseindia>javac
polyone.java

C:\roseindia>java
polyone
The value of class A is :
2
The value of class B is :
2 and 3

example:-
Java

In rumtime polymorphism, the method to be invoked is determined at the run time. The
example of run time polymorphism is method overriding. When a subclass contains a method
with the same name and signature as in the super class then it is called as method overriding.

class A{
public void fun1(int x){
System.out.println("int in Class A is : "+ x);
}
}

class B extends A{
public void fun1(int x){
System.out.println("int in Class B is : "+ x);
}
}

public class polytwo{


public static void main(String[] args){
A obj;

obj= new A(); // line 1


obj.fun1(2); // line 2 (prints "int in Class A is : 2")

obj=new B(); // line 3


obj.fun1(5); // line 4 (prints ""int in Class B is : 5")
}
}

Here is the output of the example:


C:\roseindia>javac
polytwo.java

C:\roseindia>java
polytwo
int in Class A is : 2
int in Class B is : 5

example:-
Java

In the above program, obj has been declared as A type. In line 1, object of class A is assigned.
Now in the next line, fun1(int) of class A will be called. In line 3, obj has been assigned the
object of class C so fun1(int) of class C will be invoked in line 4. Now we can understand that
same name of the method invokes different functions, defined in different classes, according to
the current type of variable "obj". This binding of method code to the method call is decided
at run time.

Applications and Applets:


Now a days, Java is widely used for applications and applets. The code for the application in
object format resides on the user's machine and is executed by a run-time interpreter.
Applications are stand alone and are executed using a Java interpreter. Whereas, A Java applet
produces object code which restricts local user resource access and can be normally be
interpreted within the user's browser. Applets can be very useful, user friendly programs or can
be a lot of fun. Applets are written in HTML documents and are executed from within a Java
empowered browser such as Inter Explorer or Netscape. For instance, whenever you pull up any
web page, the Java code is embedded within HTML code. On the contrary any program which is
not embedded within HTML code is pertained to as an application

Peculiarities of Java ...:


Platform Independent: The concept of Write-once-run-anywhere (known as the Platform
independent) is one of the important key feature of java language that makes java as the most
powerful language. Not even a single language is idle to this feature but java is more closer to
this feature. The programs written on one platform can run on any platform provided the
platform must have the JVM.
Simple: There are various features that makes the java as a simple language. Programs are
easy to write and debug because java does not use the pointers explicitly. It is much harder to
write the java programs that can crash the system but we can not say about the other
programming languages. Java provides the bug free system due to the strong memory
management. It also has the automatic memory allocation and deallocation system.
Object Oriented: To be an Object Oriented language, any language must follow at least the
four characteristics.
Inheritance : It is the process of creating the new classes and using the behavior
of the existing classes by extending them just
to reuse the existing code and adding the additional features as
needed.
Encapsulation: : It is the mechanism of combining the information and providing
the abstraction.
Java

Polymorphism: : As the name suggest one name multiple form, Polymorphism is


the way of providing the different functionality by
the functions having the same name based on the signatures of the
methods.
Dynamic binding : Sometimes we don't have the knowledge of objects about their
specific types while writing our code. It is the way of providing the
maximum functionality to a program about the specific type at runtime.

As the languages like Objective C, C++ fulfills the above four characteristics yet they are not
fully object oriented languages because they are structured as well as object oriented
languages. But in case of java, it is a fully Object Oriented language because object is at the
outer most level of data structure in java. No stand alone methods, constants, and variables are
there in java. Everything in java is object even the primitive data types can also be converted
into object by using the wrapper class.
Distributed: The widely used protocols like HTTP and FTP are developed in java. Internet
programmers can call functions on these protocols and can get access the files from any
remote machine on the internet rather than writing codes on their local system.
Interpreted: We all know that Java is an interpreted language as well. With an interpreted
language such as Java, programs run directly from the source code.
The interpreter program reads the source code and translates it on the fly into computations.
Thus, Java as an interpreted language depends on an interpreter program.
The versatility of being platform independent makes Java to outshine from other languages.
The source code to be written and distributed is platform independent.
Another advantage of Java as an interpreted language is its error debugging quality. Due to
this any error occurring in the program gets traced. This is how it is different to work with
Java.
Robust: Java has the strong memory allocation and automatic garbage collection mechanism.
It provides the powerful exception handling and type checking mechanism as compare to other
programming languages. Compiler checks the program whether there any error and interpreter
checks any run time error and makes the system secure from crash. All of the above features
makes the java language robust.
Secure: Java does not use memory pointers explicitly. All the programs in java are run under
an area known as the sand box. Security manager determines the accessibility options of a
class like reading and writing a file to the local disk. Java uses the public key encryption
system to allow the java applications to transmit over the internet in the secure encrypted
form. The bytecode Verifier checks the classes after loading.
Architecture- Neutral: The term architectural neutral seems to be weird, but yes Java is an
architectural neutral language as well. The growing popularity of networks makes developers
think distributed. In the world of network it is essential that the applications must be able to
migrate easily to different computer systems. Not only to computer systems but to a wide
variety of hardware architecture and Operating system architectures as well. The Java
compiler does this by generating byte code instructions, to be easily interpreted on any
machine and to be easily translated into native machine code on the fly. The compiler
generates an architecture-neutral object file format to enable a Java application to execute
Java

anywhere on the network and then the compiled code is executed on many processors, given
the presence of the Java runtime system. Hence Java was designed to support applications on
network. This feature of Java has thrived the programming language.
Portable: The feature Write-once-run-anywhere makes the java language portable provided
that the system must have interpreter for the JVM. Java also have the standard data size
irrespective of operating system or the processor. These features makes the java as a portable
language.
Performance: Java uses native code usage, and lightweight process called threads. In the
beginning interpretation of bytecode resulted the performance slow but the advance version of
JVM uses the adaptive and just in time compilation technique that improves the performance.
Multithreaded: As we all know several features of Java like Secure, Robust, Portable,
dynamic etc; you will be more delighted to know another feature of Java which is
Multithreaded.
Java is also a Multithreaded programming language. Multithreading means a single program
having different threads executing independently at the same time. Multiple threads execute
instructions according to the program code in a process or a program. Multithreading works
the similar way as multiple processes run on one computer.
Multithreading programming is a very interesting concept in Java. In multithreaded programs
not even a single thread disturbs the execution of other thread. Threads are obtained from the
pool of available ready to run threads and they run on the system CPUs. This is how
Multithreading works in Java which you will soon come to know in details in later chapters.
Dynamic: While executing the java program the user can get the required files dynamically
from a local drive or from a computer thousands of miles away from the user just by
connecting with the Internet.
Java

2. Java Tools

Byte Code

Byte code is a term that denotes a form of intermediate code, a binary representation of an
executable program designed to be executed by an interpreter or virtual machine rather than
by hardware. Instructions of the byte code may be arbitrarily complex as it is processed by
software, but are nonetheless often analogous to machine instructions. Like the object
modules different parts may often be stored in separate files, but loaded dynamically during
execution.

The name byte code defines java instruction set which has one-byte opcodes followed by
optional parameters. Intermediately representations like byte code may result as the output by
programming language implementations to make the interpretation easier, or it may be used to
reduce hardware and operating system dependence by allowing the same code to run on
different platforms. We can execute the Byte code either directly on a virtual machine or it
may be further compiled into machine code for better performance.
Byte codes are nothing but the constants, compact numeric codes and references that encode
the result of parsing and semantic analysis of things like type, scope and nesting depths of
program objects, therefore allowing much better performance comparing to direct
interpretation of source code.

Java Compiler
A Java Compiler javac is a computer program or set of programs which translates java source code into
java byte code

To commence with Java programming, we must know the significance of Java Compiler.
When we write any program in a text editor like Notepad, we use Java compiler to compile it.
A Java Compiler javac is a computer program or set of programs which translates java source
code into java byte code.
The output from a Java compiler comes in the form of Java class files (with .class extension).
The java source code contained in files end with the .java extension. The file name must be
the same as the class name, as classname.java. When the javac compiles the source file
Java

defined in a .java files, it generates bytecode for the java source file and saves in a class file
with a .class extension.
The most commonly used Java compiler is javac, included in JDK from Sun Microsystems.
Following figure shows the working of the Java compiler:

Once the byte code is generated it can be run on any platform using Java Interpreter (JVM). It
interprets byte code (.class file) and converts into machine specific binary code. Then JVM
runs the binary code on the host machine.
Using java compiler to compile java file:
Following example shows how a Compiler works. It compiles the program and gives the
Syntax error, if there is any. Like in this example, we haven't initialized 'a' and we are using it
in the next statement as 'int c=a+b'. That is why its showing a syntax error.
class A
{
public static void
main(String[] args)
{
int a;
int b=2;
int c=a+b;
System.out.println(c);
}
}
Output of program:
C:\Program
Files\Java\jdk1.6.0_01\bin>javac A.java
A.java:6: variable a might not have been
initialized
int c=a+b;
^
Java

1 error

C:\Program Files\Java\jdk1.6.0_01\bin>

Now, lets tweak this example. In this we have initialized 'a' as 'int a =2'. Hence, no syntax error
has been detected.
class A
{
public static void main(String[]
args)
{
int a=2;
int b=2;
int c=a+b;
System.out.println(c);
}
}
Output of program:
C:\Program
Files\Java\jdk1.6.0_01\bin>javac
A.java

C:\Program
Files\Java\jdk1.6.0_01\bin>java A
4

Java Interpreter
Java interpreter translates the Java bytecode into the code that can be understood by the Operating
System

We can run Java on most platforms provided a platform must has a Java interpreter. That is
why Java applications are platform independent. Java interpreter translates the Java bytecode
into the code that can be understood by the Operating System. Basically, A Java
interpreter is a software that implements the Java virtual machine and runs Java applications.
As the Java compiler compiles the source code into the Java bytecode, the same way the Java
interpreter translates the Java bytecode into the code that can be understood by the Operating
System.
When a Java interpreter is installed on any platform that means it is JVM (Java virtual
machine) enabled platform. It (Java Interpreter) performs all of the activities of the Java run-
time system. It loads Java class files and interprets the compiled byte-code. You would be glad
to know that some web browsers like Netscape and the Internet Explorer are Java enabled.
This means that these browsers contain Java interpreter. With the help of this Java interpreter
we download the Applets from the Internet or an intranet to run within a web browser. The
Java

interpreter also serves as a specialized compiler in an implementation that supports dynamic or


"just in time," compilation which turns Java byte-code into native machine instructions.
Throughout Java programming, we'll build both, the standalone Java programs and
applets.
Sun's Java interpreter is called java. Lets learn how to start a standalone application with it.
Load an initial class and specify it. Some options can also be specified to the interpreter, and
any command-line arguments needed for the application as well:
% java [interpreter options] class name [program arguments]
The class should be specified as a fully qualified class name including the class package, if
any.
Note : Moreover, we don't include the .class file extension. Here are a few examples:
% java animals.birds.BigBird
% java test
Once the class is loaded, java follows a C-like convention and searches for the class that
contains a method called main(). If it finds an appropriate main() method, the interpreter
starts the application by executing that method. From there, the application starts additional
threads, reference other classes, and create its user interface.
Now, lets see how to go about an Applet. Although Java applet is a compiled Java code, the
Java interpreter can't directly run them because they are used as part of a larger applications.
For this we use Java Applet Viewer. It is a command line program to run Java applets. It is
included in the SDK. It helps you to test an applet before you run it in a browser. We will
learn more about it later.
Java

The Figure below shows the working of Java Interpreter:

.Java Debugger:
Java debugger helps in finding and the fixing of bugs in Java language programs. The Java
debugger is denoted as jdb. It works like a command-line debugger for Java classes.
jdb session
The way to start the jdb session is to have jdb launch a new JVM (Java virtual machine)
with the main class. Then the application of the main class is debugged by substituting the
command jdb in command-line. For instance, if the main class of the application is
TempClass, the following command is used to debug it:
% jdb TempClass
There is another way to use jdb i.e.to attach jdb to Java VM which is already running. There
are few options which are used to debug a VM with jdb. These are:
Java

option purpose
Enables
-Xdebug debugging
in the JVM
Loads in-
process
debugging
libraries
-Xrunjdwp:transport=dt_socket,server=y,suspend=n and
specifies
the kind of
connection
to be made
The following command will run the TempClass application to which the jdb will connect
afterwords.
% java -Xdebug -Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n
TempClass
Now the jdb will be attached to the VM in this way: % jdb -attach 8000
You can go through the basic jdb commands that the Java debugger supports.
cont
Ihis command Continues the execution of the debugged application after a breakpoint,
exception, or step.

run
Use run command to start the execution after starting jdb, and setting any necessary
breakpoints, use run command to start the execution . When jdb launches the debugged
application then only this command is available.
print
This command is used to display Java objects and primitive values. The actual value is printed
for the variables or fields of primitive types. For objects, a short description is printed. Few
examples of print command are:
print TempClass.myStaticField
print myObj.myInstanceField
print myObj.myMethod()
dump
This command is similar to print command. For objects, it is used to print the current value of
Java

each field defined in the object including Static and instance fields.
The dump command supports the same set of expressions as the print command.
Exceptions
If any kind of exception occurs in the program, the VM will print an exception trace and exits.
It will only print this exception when there isn't any catch statement in the throwing thread's
call stack.

There is another command to be used to stop the debugged applications at other thrown
exceptions. The command is catch command. For instance, "catch
java.io.FileNotFoundException" or "catch mypackage.BigTroubleException.
Also the ignore command negates the effect of a previous catch command.
help, or ?
The command which helps in displaying the list of recognized commands is the help or ?
command.

threads
This command list the threads that are currently running. The name and current status are
printed for each thread. The index is also printed that can be used for other commands, for
example:

4. (java.lang.Thread)0x1 main running


This example shows that the thread index is 4, the thread is an instance of java.lang.Thread,
the thread name is "main", and it is currently running.

thread
This command selects a thread to be the current thread. Some jdb commands are based on the
setting of the current thread. The thread index specifies the thread as explained in the threads
command above.

where
The command where is used to dump the stack of the current thread. Whereas the command
where all is used to dump the stack of all threads in the current thread group. And the where
thread index command is used to dump the stack of the specified thread.

Breakpoints
The way to use Breakpoints is to set it in jdb at line numbers or at the first instruction of a
method, for example:
stop at TempClass:14 (sets a breakpoint at the first instruction for line 14 of the source file
containing TempClass)
stop in TempClass.<init> (<init> identifies the TempClass constructor)
It is essential to specify the argument types whenever we overload any method in order to
select the proper method for a breakpoint. For example,
"TempClass.myMethod(int,java.lang.String)", or "TempClass.myMethod()".
We also use the clear command to remove breakpoints using a syntax as in "clear
TempClass:20" and the cont command continues execution.
Java

Command Line Options

Use jdb in place of the Java application launcher on the command line, it accepts most of the
same options as the java command, which includes -D, -classpath, and -X<option>.
Some more options by jdb:
-sourcepath <dir1:dir2:...>
Uses the given path in searching for source files in the specified path. If this option is not
specified, the default path of "." is used.
-attach <address>
Attaches the debugger to previously running VM using the default connection mechanism.
-launch
As soon as the jdb start sup,launch option launches the debugged application immediately.
We need not to use the run command after using this option.
-Joption
It passes option to the Java virtual machine, where option is one of the options described on
the reference page for the java application launcher. For example, -J-Xms48m sets the startup
memory to 48 megabytes.

Lets tweak an example:


public class Y {
public static int add(int a, int
b)
{
return a+b;
}
public static int sub(int a,
int b)
{
return a-b;
}
public static void main(String
args[])
{
int a = 10;
int b = 20;
int c;
c = add(a, b);
System.out.println(c);
c = sub(a, b);
System.out.println(c);
}
}

After compiling and running the above program, we will initialize the java debugger and we
will use the Stop command to out a breakpoint. After that we will use run command to start
the jdb. In the similar way we can use other commands as well.
Java

C:\javac>jdb Y
Initializing jdb ...
> stop at Y:6
Deferring breakpoint Y:6.
It will be set after the class is
loaded.
> run
run Y
Set uncaught java.lang.Throwable
Set deferred uncaught
java.lang.Throwable
>
VM Started: Set deferred
breakpoint Y:6

Breakpoint hit: "thread=main",


Y.add(), line=6 bci=0
6 return a+b;

main[1] where
[1] Y.add (Y.java:6)
[2] Y.main (Y.java:17)
main[1] methods Y
** methods list **
Y <init>()
Y add(int, int)
Y sub(int, int)
Y main(java.lang.String[])
java.lang.Object <init>()
java.lang.Object registerNatives()
java.lang.Object getClass()
java.lang.Object hashCode()
java.lang.Object
equals(java.lang.Object)
java.lang.Object clone()
java.lang.Object toString()
java.lang.Object notify()
java.lang.Object notifyAll()
java.lang.Object wait(long)
java.lang.Object wait(long, int)
Java

java.lang.Object wait()
java.lang.Object finalize()
java.lang.Object <clinit>()

Javah - Header File Generator:


In Java programming we need to implement some native methods. You must be wondering
about what's native methods.

Firstly, The native methods are in pure C code, not C++. The function prototypes are in an
object-oriented form of C which are being provided by javah , but they are still not object
methods.
Secondly, We can call native methods applications only. However due to some security
reasons, we cannot call applets from native methods.

Thirdly, native methods are platform-specific. This is the most important point to remember,
you have to build a dynamically loadable library to link your java application with the native
operating system (Windows OS, Machintosh, Linux, Unix ..). For each native platform your
application targets, a dynamically loadable library is needed to be shipped.. That means any
system-specific code has to be ported along with the java code.
On the other hand, native methods are the only way to use any system features not
provided by the Java Virtual Machine.
To implement these methods Javah generates C header and source files that are used by C
programs to reference an Object's instance variables from native source code. The name of the
header file and the structure declared within it are derived from the name of the class.
By default javah creates a header file for each class listed on the command line and puts the
files in the current directory. As stated above the name of the header file is derived from the
name of the class. If any class inside the package is passed to javah, the package name gets
prepended to both the header file name and the structure name.
Following are some options to use :
-o outputfile
This option concatenates the resulting header or source files for all the classes listed on the
command line into outputfile.
-help
Print help message for javah usage.
-d directory
This option sets the directory where javah saves the header files or the stub files. Only one of
-d or -o may be used.
-classpath path
Specifies the path javah used to look up classes. Overrides the default or the CLASSPATH
environment variable if it is set. Directories are separated by semi-colons. Thus the general
Java

format for path is:


.;<your_path>
For example:
.;C:\users\dac\classes;C:\tools\java\classes
-stubs
Causes javah to generate C declarations from the Java object file.
-verbose
Indicates verbose output and causes javah to print a message to stdout concerning the status of
the generated files.

Javadoc:
Sun Microsystems has provided a computer software tool known as Javadoc. This tool is used
to generate API documentation into HTML format from Java source code. It is interesting to
know that Javadoc is the industry standard for documenting Java classes.
Javadoc is a program that is already included in JDK. We can use Javadoc to run over the
source code to produce documentation of our classes in the HTML files . We have to tag our
code with by using some comment formats to use javadoc tag on our source code. For instance
Javadoc comments looks like this:
NOTE : To start a Javadoc comments use /** to start, and */ to end, and use tags such as
@param, @return, and @exception in between to describe the workings of a method.
The format is given below to use the Javadoc comments:
/**
* Summary of the sentence.
* information about the
* program, class, method or variable
* then the comment, using as many lines
* as necessary.
*
* zero or more tags to specify any type
* of information, such as parameters and return
* values for a method
*/

Start with comment delimiter (/*) followed by another (*). The next line starts with an asterisk
and write as many line as you want starting with an asterisk. The last line ends with the
delimiter (*/). The first sentence to start with is a "summary sentence" showing the description
of the program, class, method or variable. We can write few more lines if required, but not any
blank lines. After writting the general description, a sequence of tags follows leaving a blank
line.
Use different tags to display different situations. The example below shows a Javadoc
comment without tags that describes the variable declared immediately below it:
Java

/**
* The number of employees in a company. This variable must not be negative or greater than
200.
*/
public int numEmployees;

One interesting thing to know about Javadoc comments is that we can embed HTML tags to
format the text. For example:

/**
* <B>Java declaration</B>
*/
Lets have a look on Javadoc tags
Tag Description
@version Shows the version number of a class or method.
@author Shows the Developer name
@return Documents the return value. This tag should not
be used for constructors or methods defined with a
void return type.
@deprecated Marks a method as deprecated. Some IDEs will
issue a compilation warning if the method is
called.
@see Documents an association to another method or
class.
@param Defines a method parameter. Required for each
parameter.
@throws Documents an exception thrown by a method. A
synonym for @exception introduced in Javadoc
1.2.
@since Documents when a method was added to a class.
@exception Documents an exception thrown by a method
also see @throws.
private Displays all classes and members
use It creates class and package usage pages
Windowtitle It shows the window title of the document
Header It includes for header text of the page
Footer It includes footer text for the page
Bottom It includes bottom text for the page
Package Shows package classes and members
Java

Protected shows protected classes and members


Classpath Helps to find user class files
noindex doesn't provide the index
nohelp doesn't provide the help link
notree doesn't provide class hierarchy

To document source code developers use certain commenting styles and Javadoc tags. A Java
block comment starting with /** will begin a Javadoc comment block This comment block
will be included in the HTML. Some tags are provided in the above table which begins with
an "@" (at sign).
The Java Applet Viewer:
Applet viewer is a command line program to run Java applets. It is included in the SDK. It
helps you to test an applet before you run it in a browser. Before going any further, lets see
what an applet is?

An applet is a special type of application that's included as a part of an HTML page and can
be stored in a web page and run within a web browser. The applet's code gets transferred to the
system and then the Java Virtual Machine (JVM) of the browser executes that code and
displays the output.. So for running the applet, the browser should be Java enabled.To create
an applet, we need to define a class that inherits the Applet.
We generally use web browsers to run applets. Its not always mandatory to open a Web
browser for running an applet. There is another way as well. The other way to run an applet is
through Java applet viewer. This is a tool that acts as a test bed for Java applets. The working
of Applet viewer is a bit different from a Web browser, though they are logically same. The
Applet viewer runs on the HTML documentation, and uses embedded applet tags. The
difference in using the applet viewer and the web browser to run the applet is that the applet
viewer only deals with the applet code not the HTML cod i.e. it doesn't display HTML code.
So we should test our program in applet viewer and web browser to confirm its working.
The applet viewer command connects to the documents or resources designated by urls. It
displays each applet referenced by the documents in its own window.
The syntax for the applet viewer is:

appletviewer Options URL

Where the URL specifies the location of the applet program and the Options argument
specifies how to run the Java applet. We can use only one option -debug that starts the applet
viewer in the Java debugger. Using this option we can debug an applet.
The following program shows how to build an applet and the HTML file for it. Firstly create a
class. Then start the applet using init method. After that enter a string as str = "This is my first
applet". Use paint method to give the dimensions of the applet. Beneath that is the HTML file
which shows how to give the body for applet.
Java

import java.applet.*;
import java.awt.*;
public class Myapplet extends Applet{
String str;
public void init(){
str = "This is my first
applet";
}
public void paint(Graphics g){
g.drawString(str,
50,50);
}
}

<HTML>
<BODY>
<applet
code="Myapplet",height="200"
width="200">
</applet>
</BODY>
</HTML>
After building the program, run the applet and the applet viewer as shown below.
C:\javac> javac
Myapplet.java

C:\javac>appletviewer
Myapplet.html
When we run the applet viewer it will display the window as shown below.
Java

3. Java Enabled browsers


Java language is the most powerful language and is widely used in the web application. So the
current versions of most of the web browser are made java enabled. Mostly used java enabled
web browsers are
Internet Explorer
Netscape
HotJava
Safari
Firefox 1.0.4
Mozilla 1.6

Internet Explorer: Most commonly used Internet Explorer also abbreviated as IE is Windows
Internet Explorer developed by Microsoft in 1995 and it was included in series of Microsoft
Windows 95 operating system. Advanced version was made to support different operating
systems such as Internet Explorer for UNIX, Internet Explorer for Mac. Internet Explorer 7.0
is the recent version available for free update for Windows XP with Service Pack 2 and
Windows Server 2003 with Service Pack 1 also included Windows Vista.
Netscape: Netscape Web browser version 8.0 as the first version was first time released in 30
November 2004 and developed by Mercusial Communication. After this version 8.0.1 was
came in the market with a minor enhancement. The various version of the Netscape was based
on different technology like version 8 was based on Mozila Firefox whereas version 1 to 4
was based on Netscape Navigator and Netscape Communicator. While Netscape 6 and 7 was
based on Mozilla Application Suite.

HotJava: It is the modular version of the web browser developed by the Sun Microsystems to
support the applets. Now it is not currently used. It was nothing but the clone of the internet
Java

browser Mosaic. This browser was the three version like HotJava Browser 3.0, HotJava
Browser 1.1.5 and HotJava Browser 1.1.2 .
Safari: Safari, the web browser developed by Apple Inc. Apple release beta as the first version
June 23 2003. After this version 1.0 was released. Initially it was available as a separate
download. It was included in Mac OS X v10.3 as the default web browser. Later it was the
only browser bundled with operating system Mac OS X v10.4.
Techniques to check whether java enabled or not.
Most of the currently using browsers are java enabled. There are various ways to check
whether the browser being used is java enabled or not but generally we manually check that
whether the browser is java enabled or not. The following procedure shows how we check
whether the browser is java enabled or not.
Firefox 1.0.4: Go through just by putting the following entry in the address bar.
about : plugins
If java is installed then it will show the multiple entries under the lable "Java Plug-in". It will
also the information about the version and about whether they are installed or not.
We can also check manually by going through the following steps in the tool bar.
Click on Tools -> Options -> Web features (or Content ).
If the check box is checked, the browser us java enabled.
Mozilla 1.6: Mozilla also have the two ways manually checking, whether it is java enabled or
not.
Go to click on Help-> About Plug-ins.
If it shows nothing then java is not installed. If java is installed then it shows various plug-in
entries according to the version. The second method is that, Click on Tools -> Web
Development
. If it shows the Java Console option then java is installed otherwise it shows nothing.
Java

4. Installing Java:
Before getting started developing an application the developer must ensure that he/she is going
to develop an application by using the best tools. The combination of two features Platform
Independent and Object Oriented makes the java powerful to build the flexible application. In
old days it was difficult to develop the flexible applications by using the conventional toolsets,
java made it easy.
Due to the global utilization of java language, new tools are being developed daily and are
providing the user friendly tools to develop the flexible and powerful application that are easy
to use. Daily development of new tools are making the application easy but on the other hand
they are creating much confusion to the java developers. Some of them are illustrated below:
What is the necessity to develop a new Java application?
What browser the required to run my applet?
What tools are to be used to develop a java application?
Is there any requirement to purchase the GUI development tools (such as Microsoft
Jakarta, Borland Latte, Symantec Cafe)?
What is require to run my applet by my clients at their end?

Here we are trying to answer of all these questions as well as provide the tools to develop the
java application.
Let's start with the Java Development Kit: Sun Microsystems made some standards as open
to gain comments and suggestions at public level for the improvement and advancement of the
java language. To support Sun Solaris operating systems and 32-bit Windows (Windows 95
and Windows NT) Sun provided the implementation of the Java Virtual Machine. Sun also
provided the basic tools needed for java programming. JDK contains all the to tools to develop
a java application or an applet. JDK contains the sample application, a compiler, an interpreter,
a debugger and an appletviewer to test your code. As a beginner, we consider that neither you
Java

don't have the java development kit nor the knowledge about the installation of JDK on your
machine. So let's start from the ground level,
This link provides you the information about the latest version of the JDK. Just by clicking the
link ensure that your computer have the latest version of the JDK otherwise download the
latest version of the JDK from JavaSoft website. you have three choice to download the jdk
for the following operating systems:
1. Microsoft Windows 95 and Windows NT
2. Apple Macintosh 7.5
3. Sun Solaris 2.3, 2.4, 2.5 on SPARC-based machines or Solaris 2.5 on x86-based
machines.

The order may be different of the above three options on the site.
We can get the JDK by FTP from ftp.javasoft.com. Choices of all of the operating system
are available, and the JDK can be found in the \pub directory. Availability of JDK for all these
operating systems means that the Sun made some enhancement in JVM and deployment tools
to support all these operating systems. It is nothing for the browsers vendors this means that
they must provides some hooks to display the java applet within their windows. Now the time
is about to come when java will running on everything from cellular phone to mainframe.
JDK Installation: JDK installation instruction varies from platform to platform. So on the
basis of the instruction we divided the JDK installation into three parts depending on the
platform such as Windows, Solaris and Macintosh.
A good question arises here "If java is cross platform then for each platform why we need to
download the separate files". So the answer is that the source file once compiled can run on
any platform provided the JVM should be installed. But the key point is that the Java
Developer Kit contains a no of executive files (such as Compiler, Interpreter, Debugger and
so on) that are compiled specific to a platform. While the source code (.java files) are similar
to Windows as well as Solaris.
JDK Installation on Sun Solaris:
1. First check if you have the tarred version of JDK and then unpack the file before use just
by giving the following command.
/usr/bin/zcat JDK-1_0_2-solaris2-sparc.tar.Z | tar xf -
But you should here notice that the file is the correct file name (as the latest version may
have some changes in the name) of the file JDK-1_0_2-solaris2-sparc.tar.Z
2. A directory /java will be created after installation. Don't forget to include the java/bin to
the class path. This directory contains all the tools required to build any applications.

JDK Installation on Windows 95 and Windows NT:


1. To create a main directory that will contain all the downloaded file run the self extracting
file JDK-1_0_2-win32-x86.exe.
2. Add the directory \java\bin to the class path.
For Windows 95: You can do it by editing the path variable in your AUTOEXE.BAT file
then restart the system to affect the changes.
Java

For Windows NT: Edit the environment variable path in the Control Panel "System"
application

JDK installation on Apple Macintosh system 7.5:


1. First unpack the downloaded file JDK-1.0.2-MacOS.sea.hqx or JDK-1.0.2-
MacOS.sea.bin. If the downloaded file is in hqx format then to decompress this file use
DeHQX or BinHex4. Use Stuffit to decompress the file, if the file is in MacBinary
format.
2. To create a folder named JDK-1.0.2-mac run the installation program.
3. It is not required to set the environment variable as there are a number of environment
variables the JDK uses to compile the class. Some of them are illustrated here:

JAVA_HOME - This variable is used to store the root directory


PATH - The previously installed instructions will help you to set the path variable
correctly.
CLASSPATH - This variable is used to store the directory location of addition class files
that are used to compile the project. On PC it is separated by the semi-colons while on
UNIX colon is used to separate the list.
Don't unzip the classes.zip file without updating the CLASSPATH variable.

Testing the installation: Run the sample application included with the JDK by using the
appletviewer application. This application is located in the \bin directory of the installation.
JDK and the tools included with it are command line. To run the applet viewer in Windows 95
and Windows NT just go to the DOS prompt and go through the following steps.
If you installed the JDK into the c:\ java directory then change it to \demo\ fractal
directory just by typing the following command.
cd demo \ fractal
The applet viewer can suppose an .html file as input that contains a Java applet.

Exploring the java Developer's kit: The tools included in the JDK are contained in various
directories. Some directories are illustrated below that contains the most widely tools used to
develop the java application.
bin\ directory : The bin\ directory contains the following tools.
Compiler (javac) : This is the compiler used to compile the source (.java files) and
produces the .class file after compilation.
Interpreter (java) : This is the interpreter and is used to run the stand alone Java
application.
Java

Debugger (jdb) : This is called line tool and is used for debugging. It is the
command line tool.
Appletviewer : This tool is used to test the java applets.
JavaDoc : This tool is used to generate the documentation for a java
application.

demo\ directory : This directory contains a large number of applets that are useful to
understand "what exactly the applets are and how they are developed?"

Animator GraphLayout
ArcTest ImageMap
Blink MoleculeViewer
BarChart JumpingBox
Clock SimpleGraph
CardTest NervousText
DrawTest SpreadSheet
DitherTest SortDemo
Fractal TicTacToe
GraphicsTest WireFrame
include\ directory : This directory contains the a set of C and C++ header files. Java classes
use these files just to make the interface to C and C++ language.
lib\ directory : This directory contains the classes.zip as the primary file. This is the
combination of all the classes that together make up the JDK. Primary packages in this
directory are:
java.lang : This package is mostly used and contains the language functionality.
java.util : This is the utility package that contains a number of useful functions.
java.io : This is the input/output package and support all the java input/output operations.
java.net : Networking package support all the networking related operations.
java.applet : This package works as the base class for all the applets.
java.awt : This package supports for all the GUI based applications.

rc\ directory : This directory contains all the source files used by JDK. It will not be visible
for the Windows 95/NT users. But they can restore it by unzipping the src.zip file from the
root directory of JDK.
Java

Distributing the Java Virtual Machine: When the most user think about java, they think
about the Java applet but java is not limited to only applet. stand alone applications can be
made in java by using JDK. Windows 95/NT setup requires the following files:

java.exe
javaw.exe
javai.dll
classes.zip
awt.dll
net.dll
jpeg.dll
mmedia
mfc30.dll
msvcrt20.dll

Other Development Environment: Now Software developers have become habitual to work
with the fully graphical environments. The tools such as Microsoft Visual Basic, Borland
Delphi, Powerbuilder, and Powersoft, known as Rapid application development made easy to
use and increased the programmer productivity. Then Java came in the market. In the
beginning JDK was designed to run virtually on any platform which have the Java Virtual
Machine and to work as a basic development toolkit. Whole of the industry getting benefits
with the more powerful java tools.Microsoft, Sun, Symantec, and Borland are the
manufacturers of the most anticipated tools. Java development can be done on every operating
system that are available today.
Summary: The necessary tools required to development a java application, are available in
the Java Developer's kit (JDK). Nowadays a wide range of platforms support the Java
Development tools.

5. To Comments with Java ...

Java Comments:
To comprehend any programming language, there are several kind of comments which are
used. These comments are advantageous in the sense that they make the programmer feel
convenient to grasp the logic of the program. Although these comments are ignored by the
Java compiler, they are included in the program for the convenience of the user to understand
it. To provide the additional information about the code, use comments. These comments give
the overview of the code in the form of the information which is not available in the code
itself.
There are three types of comments used in Java. These are:
1. // text
To add a comment to the program, we can use two slashes characters i.e. //. The line starting
Java

from slashes to the end is considered as a comment. We can write only a single line comment
use these slashes. For instance

// This comment extends to the end of the line.


// This type of comment is called a "slash-slash" comment
2. /* text */
To add a comment of more than one line, we can precede our comment using /*. The precise
way to use this is to start with delimiter /* and end with delimiter */. Everything in between
these two delimiters is discarded by the Java compiler. For instance
/* This comment, a "slash-star" comment, includes multiple lines.
* It begins with the slash-star sequence (with no space between
* the '/' and '*' characters) and extends to the star-slash sequence.
*/
Slash-star comments may also be placed between any Java tokens:
int i = /* maximum integer */ Integer.MAX_VALUE;
3. /** documentation */
This is a special type of comment that indicates documentation comment. This type of
comment is readable to both, computer and human. To start the comment, use /** instead of /*
and end with */. This type of comment is a documentation which is interpreted as an official
document on how the class and its public method work. For instance
/**
* These are used to extract documentation from the Java source.
*/
Comments in String Literals
Comments occurring in string literals are not parsed as comments. Like,
String text = "/* This is not a comment */";
Unicode Characters in Comments
Remember that Java still interprets Unicode sequences within comments. For example -:

/* This is a comment. \u002a\u002f


String statement = "This is a comment.";

and is lexically equivalent to

/* This is a comment. */
String statement = "/* This is a comment. */";
(The '*' character is Unicode 002A and the '/' character is Unicode 002F).

This also applies to newline characters in slash-slash comments.


For example:

//This is a single line comment \u000a This is code


That is because the \u000a is the Unicode for a new line, here the compiler thinks that you
Java

have added a new line.


This may be useful when declaring more than one thing on a line and you still wish to use //
type comments
int x = 0; //X is the value of the carr \u000a int y=0; //Y is the intrest

Java Keywords:
There are few keywords in Java programming language. Remember, we cannot use these
keywords as identifiers in the program. The keywords const and goto are reserved though,
they are not being currently used.

The brief description of each one of the keyword is given below.


abstract:
When a class is not to be instantiated, use abstract keyword but rather extended by other
classes. This keyword is used to in a method declaration to declare a method without
providing the implementation.
assert:
To make the assumed value of a condition explicit, assert keyword is used. An
AssertionError is thrown if the condition is not true.

boolean:
This keyword is used to pertain to an expression or variable that can have only a true or false
value.

byte:
This is an an 8-bit integer. This keyword is used to declare an expression, method return value,
or variable of type byte.

case:
This keyword is used to defines a group of statements. The value defined by the enclosing
switch statement should match with the specified value.

catch:
This keyword is used to handle the exceptions that occur in a program preceding try keyword.
When the class of the thrown exception is assignment compatible with the exception class
declared by the catch clause then only the code is executed.

char:
This Java keyword is used to declare an expression, method return value, or variable of type
character.
Java

class:
This keyword is used to define the implementation of a particular kind of object.

const:
This keyword has been deprecated from Java programming language.

continue:
This keyword is used for the continuation of the program at the end of the current loop body.

default:
If the value defined by the enclosing switch statement does not match any value specified by a
case keyword in the switch statement, default keyword is used to define a group of statements
to begin the execution.

do:
Used to declare a loop that will iterate a block of statements. The loop's exit condition is
specified with the while keyword. The loop will execute once before evaluating the exit
condition.

double:
A 64-bit floating point value. A Java keyword used to declare an expression, method return
value, or variable of type double-precision floating point number.

else:
This keyword is used to test the condition. It is used to define a statement or block of
statements that are executed in the case that the test condition specified by the if keyword
evaluates to false.

enum:
Enumerations extend the base class Enum.This Java keyword is used to declare an enumerated
type.

extends:
To specify the superclass in a class declaration, extends keyword is used. It is also used in an
interface declaration to specify one or more superinterfaces.

final:
It is used to define an entity once that cannot be altered nor inherited later. Moreover, a final
class cannot be subclassed, a final method cannot be overridden, and a final variable can occur
at most once as a left-hand expression. All methods in a final class are implicitly final.

finally:
This keyword is used when the finally block is executed after the execution exits the try block
and any associated catch clauses regardless of whether an exception was thrown or caught.
break:
Used to resume program execution at the statement immediately following the current
Java

enclosing block or statement. If followed by a label, the program resumes execution at the
statement immediately following the enclosing labeled statement or block.
Java Data Types:
Data type defines a set of permitted values on which the legal operations can be
performed.
In java, all the variables needs to be declared first i.e. before using a particular variable, it
must be declared in the program for the memory allocation process. Like
int pedal = 1;
This statement exists a field named "pedal" that holds the numerical value as 1. The value
assigned to a variable determines its data type, on which the legal operations of java are
performed. This behavior specifies that, Java is a strongly-typed programming language.

The data types in the Java programming language are divided into two categories and can be
explained using the following hierarchy structure :

Primitive Data Types


Reference Data Types

Primitive Data Types

The primitive data types are predefined data types, which always hold the value of the same
data type, and the values of a primitive data type don't share the state with other primitive
values. These data types are named by a reserved keyword in Java programming language.
There are eight primitive data types supported by Java programming language :
byte
The byte data type is an 8-bit signed two's complement integer. It ranges from -128 to127
(inclusive). This type of data type is useful to save memory in large arrays.. We can also use
byte instead of int to increase the limit of the code. The syntax of declaring a byte type
variable is shown as:
byte b = 5;
short
The short data type is a 16-bit signed two's complement integer. It ranges from -32,768 to
Java

32,767. short is used to save memory in large arrays. The syntax of declaring a short type
variable is shown as:
short s = 2;

int
The int data type is used to store the integer values not the fraction values. It is a 32-bit signed
two's complement integer data type. It ranges from -2,147,483,648 to 2,147,483,647 that is
more enough to store large number in your program. However for wider range of values use
long. The syntax of declaring a int type variable is shown as:
int num =
50;
long
The long data type is a 64-bit signed two's complement integer. It ranges from
-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. Use this data type with larger
range of values. The syntax of declaring a long type variable is shown as:
long ln =
746;
float
The float data type is a single-precision 32-bit IEEE 754 floating point. It ranges from
1.40129846432481707e-45 to 3.40282346638528860e+38 (positive or negative). Use a float
(instead of double) to save memory in large arrays. We do not use this data type for the exact
values such as currency. For that we have to use java.math.BigDecimal class. The syntax of
declaring a float type variable is:
float f = 105.65;
float f = -5000.12;
double
This data type is a double-precision 64-bit IEEE 754 floating point. It ranges from
4.94065645841246544e-324d to 1.79769313486231570e+308d (positive or negative). This
data type is generally the default choice for decimal values. The syntax of declaring a double
type variable is shown as:
Double d = 6677.60;
char
The char data type is a single 16-bit, unsigned Unicode character. It ranges from 0 to 65,535.
They are not integral data type like int, short etc. i.e. the char data type can't hold the numeric
values. The syntax of declaring a char type variable is shown as:
char caps = 'c';

boolean
The boolean data type represents only two values: true and false and occupy is 1-bit in
the memory. These values are keywords in Java and represents the two boolean states: on or
Java

off, yes or no. We use boolean data type for specifying conditional statements as if, while, do,
for. In Java, true and false are not the same as True and False. They are defined constants of
the language. The syntax of declaring a boolean type variable is shown as:
boolean result =
true;
The ranges of these data types can be described with default values using the following table:
Default
Data Value
Size (in bits) Minimum Range Maximum Range
Type (for
fields)
Occupy 8 bits
Byte 0 -128 +127
in memory
Occupy 16 bits
Short 0 -32768 +32767
in memory
Occupy 32 bits
Int 0 -2147483648 +2147483647
in memory
Occupy 64 bits
Long 0L -9223372036854775808 +9223372036854775807
in memory
Occupy 32-bit
1.40129846432481707e-
Float 0.0f IEEE 754 3.40282346638528860e+38
45
floating point
Occupy 64-bit
4.94065645841246544e-
double 0.0d IEEE 754 1.79769313486231570e+308d
324d
floating point
Occupy 16-bit,
unsigned
Char '\u0000' 0 to 65,535
Unicode
character
Occupy 1- bit
boolean false NA NA
in memory
When we declare a field it is not always essential that we initialize it too. The compiler sets a
default value to the fields which are not initialized which might be zero or null. However this
is not recommended.
Integer Data Types

So far you would have been known about these data types. Now lets take an Integer data
type in brief to better understand:
As we have told that an integer number can hold a whole number. Java provides four different
primitive integer data types that can be defined as byte, short, int, and long that can store
both positive and negative values. The ranges of these data types can be described using the
following table:
Java

Size (in
Data Type Minimum Range Maximum Range
bits)
Occupy 8
Byte bits in -128 +127
memory
Occupy 16
Short bits in -32768 +32767
memory
Occupy 32
Int bits in -2147483648 +2147483647
memory
Occupy 64
-
Long bits in +9223372036854775807
9223372036854775808
memory

Examples of floating-point literals are:


0
1
123
-42000

Floating-point numbers
A floating-point number represents a real number that may have a fractional values i.e. In the
floating type of variable, you can assign the numbers in an in a decimal or scientific notation.
Floating-point number have only a limited number of digits, where most values can be
represented only approximately. The floating-point types are float and double with a
single-precision 32-bit IEEE 754 floating point and double-precision 64-bit IEEE 754 floating
point respectively. Examples of floating-point literals are:
10.0003
48.9
-2000.15
7.04e12

Java Literals:
By literal we mean any number, text, or other information that represents a value. This means
what you type is what you get. We will use literals in addition to variables in Java statement.
While writing a source code as a character sequence, we can specify any value as a literal such
as an integer. This character sequence will specify the syntax based on the value's type. This
will give a literal as a result. For instance
Java

int month = 10;


In the above statement the literal is an integer value i.e 10. The literal is 10 because it directly
represents the integer value.
In Java programming language there are some special type of literals that represent numbers,
characters, strings and boolean values. Lets have a closer look on each of the following.
Number Literals
Number literals is a sequence of digits and a suffix as L. To represent the type as long integer
we use L as a suffix. We can specify the integers either in decimal, hexadecimal or octal
format. To indicate a decimal format put the left most digit as nonzero. Similarly put the
characters as ox to the left of at least one hexadecimal digit to indicate hexadecimal format.
Also we can indicate the octal format by a zero digit followed by the digits 0 to 7. Lets tweak
the table below.

Decimal integer literal of type


659L
long integer
Hexadecimal integer literal of
0x4a
type integer
Octal integer literal of type
057L
long integer

Character Literals
We can specify a character literal as a single printable character in a pair of single quote
characters such as 'a', '#', and '3'. You must be knowing about the ASCII character set. The
ASCII character set includes 128 characters including letters, numerals, punctuations etc.
There are few character literals which are not readily printable through a keyboard. The table
below shows the codes that can represent these special characters. The letter d such as in the
octal, hex etc represents a number.
Escape Meaning
\n New line
\t Tab
\b Backspace
\r Carriage return
\f Formfeed
\\ Backslash
Single
\'
quotation mark
Double
\"
quotation mark
\d Octal
Java

\xd Hexadecimal
Unicode
\ud
character
It is very interesting to know that if we want to specify a single quote, a backslash, or a
nonprintable character as a character literal use an escape sequence. An escape sequence uses
a special syntax to represents a character. The syntax begins with a single backslash character.
Lets see the table below in which the character literals use Unicode escape sequence to
represent printable and nonprintable characters both.

Capital letter
'u0041'
A
'\u0030' Digit 0
'\u0022' Double quote "
'\u003b' Punctuation ;
'\u0020' Space
Horizontal
'\u0009'
Tab

Boolean Literals
The values true and false are also treated as literals in Java programming. When we assign a
value to a boolean variable, we can only use these two values. Unlike C, we can't presume that
the value of 1 is equivalent to true and 0 is equivalent to false in Java. We have to use the values
true and false to represent a Boolean value. Like
boolean chosen = true;
Remember that the literal true is not represented by the quotation marks around it. The Java
compiler will take it as a string of characters, if its in quotation marks.

Floating-point literals
Floating-point numbers are like real numbers in mathematics, for example, 4.13179, -0.000001.
Java has two kinds of floating-point numbers: float and double. The default type when you
write a floating-point literal is double.
Type Size Range Precision
name bytes bits approximate in decimal digits
Java

float 4 32 +/- 3.4 * 1038 6-7


double 8 64 +/- 1.8 * 10308 15
A floating-point literal can be denoted as a decimal point, a fraction part, an exponent
(represented by E or e) and as an integer. We also add a suffix to the floating point literal as D,
d, F or f. The type of a floating-point literal defaults to double-precision floating-point.
The following floating-point literals represent double-precision floating-point and floating-
point values.
6.5E+32 (or Double-precision
6.5E32) floating-point literal
Double-precision
7D
floating-point literal
.01f Floating-point literal
String Literals
The string of characters is represented as String literals in Java. In Java a string is not a basic
data type, rather it is an object. These strings are not stored in arrays as in C language. There
are few methods provided in Java to combine strings, modify strings and to know whether to
strings have the same value.
We represent string literals as
String myString = "How are you?";
The above example shows how to represent a string. It consists of a series of characters inside
double quotation marks.
Lets see some more examples of string literals:

"" // the empty string


"\"" // a string containing "
"This is a string" // a string containing 16 characters
"This is a " + // actually a string-valued constant expression,
"two-line string" // formed from two string literals
Strings can include the character escape codes as well, as shown here:
String example = "Your Name, \"Sumit\"";
System.out.println("Thankingyou,\nRichards\n");

Null Literals
The final literal that we can use in Java programming is a Null literal. We specify the Null
literal in the source code as 'null'. To reduce the number of references to an object, use null
literal. The type of the null literal is always null. We typically assign null literals to object
reference variables. For instance

s = null;

An this example an object is referenced by s. We reduce the number of references to an object


Java

by assigning null to s. Now, as in this example the object is no longer referenced so it will be
available for the garbage collection i.e. the compiler will destroy it and the free memory will
be allocated to the other object. Well, we will later learn about garbage collection.

Operators and Expressions:


Operators:
Operators are such symbols that perform some operations on one or more operands. Operators
are used to manipulate primitive data types. Once we declare and initialize the variables, we
can use operators to perform certain tasks like assigning a value, adding the numbers etc.
Java operators can be classified into different categories as shown:
1. Simple Assignment Operators
2. Arithmetic Operators
3. Unary Operators
4. Equality and Relational Operators
5. Conditional (Logical) Operators
6. Bitwise and Bit Shift Operators
Java Bitwise AND " &" Operator
Java bitwise NOT "~" operator
Java bitwise XOR "^" operator
Java bitwise OR " |" operator
Java Left Shift "<<" Operator
Java Right Shift ">>" Operator
Java unsigned right shift ">>>"operator
Java Truth-Table

7. Type Operators

Expressions:
In Java, an expression is like a statement without a terminator ( i.e. statement = expression
+ ; ). It is made up of variables, operators, and method invocations, which are defined in
accordance to the syntax of the language. The overall coding in a Java program is achieved
through the expressions ( which may have single or multiple operations) . In all cases, a single
evaluated value is obtained irrespective of composition of the multiple expressions. The
evaluation of an expressions is determined by the order of precedence of the operators.

Few of the examples of expressions are:


int number = 2
arr[0] = 10
Java

int abc = a + (++b)* ((c / a)* b)

System.out.println("Hi,How are you") // a compound expression


After executing an expression, a value is returned by an expression, it's data type depends on
the elements used in the expression
Java also allows you to build the compound expression.

There are three purposes for defining an expression :


To compute values.
To assign values to variables.
To control the flow of execution.

Operator Precedence:
Operator Precedence :
In Java, Operator Precedence is an evaluation order in which the operators within an
expression are evaluated on the priority bases. Operators with a higher precedence are applied
before operators with a lower precedence.
For instance, the expression "4 + 5 * 6 / 3" will be treated as "4 + (5 * (6 / 3))" and 14 is
obtained as a result.
When two operators share an operand then operator with the higher precedence gets evaluated
first. However, if the operators have the equal precedence in the same expression then that
expression will be evaluated from left to right except the assignment operators.
For example a = b = c = 15 is treated as a = (b = (c = 15)).

The table below shows the list of operators that follow the precedence.

Operators Precedence
array index &
[] ( )
parentheses
access object .
postfix expr++ expr--
++expr --expr +expr
unary
-expr ~ !
multiplicative * / %
additive + -
Java

bit shift << >> >>>


relational < > <= >= instanceof
equality == !=
bitwise AND &
bitwise exclusive
^
OR
bitwise inclusive
|
OR
logical AND &&
logical OR ||
ternary ?:
= += -= *= /=
assignment %= &= ^= |= <<=
>>= >> >=

Lets see an example that evaluates an arithmetic expression according to the precedence
order.

class PrecedenceDemo{
public static void main(String[] args){
int a = 6;
int b = 5;
int c = 10;
float rs = 0;
rs = a + (++b)* ((c / a)* b);
System.out.println("The result is:" + rs);
}
}

The expression "a+(++b)*((c/a)*b)" is evaluated from right to left. Its evaluation order
depends upon the precedence order of the operators. It is shown below:

a + (+
(++b)
+b)*((c/a)*b)
a+ (+
(c/a)
+b)*((c/a)*b)
a + (++b)*((c/a)*
(c/a)*b
b)
a + (++b)*((c/a)*
(++b)*((c/a)*b)
b)
A+(++b)*((c/a)*b) a+(++b)*((c/a)*b)
Java

Output of the Program:


C:\nisha>javac
PrecedenceDemo.java

C:\nisha>java
PrecedenceDemo
The result is: 42.0

6. Java Syntax ...

Classes in Java:
Class : Whatever we can see in this world all the things are a object. And all the objects are
categorized in a special group. That group is termed as a class. All the objects are direct
interacted with its class that mean almost all the properties of the object should be matched
with it's own class. Object is the feature of a class which is used for the working on the
particular properties of the class or its group. We can understand about the class and object
like this : we are all the body are different - different objects of the human being class. That
means all the properties of a proper person relates to the human being. Class has many other
features like creation and implementation of the object, Inheritance etc.
In this Program you will see how to use the class, object and it's methods. This program uses
the several values of several defined variables for getting the Area and Perimeter of the Square
and Rectangle by calling the different functions from the different classes through the several
objects created for the several class. In this program there are two classes has been used except
the main class in which the main function is declared. First class is square which is used for
getting the Area and Perimeter of the square and another class is rectangle which is used for
getting the Area and Perimeter of the Rectangle. All the functions in the square and rectangle
class are calling with different - different arguments two times for getting the Area and
Perimeter of square and rectangle for two different sides. This program gives us the Area and
Perimeter for the different sided Square and Rectangle separately. Full running code is given
with the example :

Here is the code of the program : Next page


class square{
Java

int sqarea(int side){


int area = side * side;
return(area);
}
int sqpari(int side){
int pari = 4 * side;
return(pari);
}
}
class rectangle{
int rectarea(int length,int breadth){
int area = length * breadth;
return(area);
}
int rectpari(int length,int breadth){
int pari = 2*(length + breadth);
return(pari);
}
}
public class ObjectClass{
public static void main(String args[]){
int sarea1,sarea2,pari1,pari2;
int rectarea1,rectarea2,rectpari1,rectpari2;
square sq = new square();
rectangle rect = new rectangle();
int a=20;
System.out.println("Side of first square = " + a);
sarea1 = sq.sqarea(a);
pari1 = sq.sqpari(a);
System.out.println("Area of first square = " + sarea1);
System.out.println("Parimeter of first square = " + pari1);
a = 30;
System.out.println("Side of second square = " + a);
sarea2 = sq.sqarea(a);
pari2 = sq.sqpari(a);
System.out.println("Area of second square = " + sarea2);
System.out.println("Parimeter of second square = " + pari2);
int x = 10, y = 20;
System.out.println("Length of first Rectangle = " + x);
System.out.println("Breadth of first Rectangle = " + y);
rectarea1 = rect.rectarea(x,y);
rectpari1 = rect.rectpari(x,y);
System.out.println("Area of first Rectangle = " + rectarea1);
System.out.println("Parimeter of first Rectangle = " + rectpari1);
x = 15;
y = 25;
System.out.println("Length of second Rectangle = " + x);
System.out.println("Breadth of second Rectangle = " + y);
rectarea2 = rect.rectarea(x,y);
rectpari2 = rect.rectpari(x,y);
System.out.println("Area of second Rectangle = " + rectarea2);
System.out.println("Parimeter of first Rectangle = " + rectpari2);
}
}
Java

Descriptions of the program:


Object : Objects are the basic run time entity or in other words object is a instance of a class .
An object is a software bundle of variables and related methods of the special class. In the
above example the sq is the object of square class and rect is the object of the rectangle class.
In real-world objects share two characteristics: They have all state and behavior. For example,
The squares have state such as : sides and behaviors such as its areas and perimeters.
Rectangles have state such as: length, breadth and behavior such as its areas and perimeters. A
object implements its behavior with methods of it's classes. A method is a function
(subroutine) associated with an object.
Syntax for the Object :
class_name object_name = new class_name();

Output of the program :

C:\chandan>javac
ObjectClass.java
C:\chandan>java ObjectClass
Side of first square = 20
Area of first square = 400
Parimeter of first square = 80
Side of second square = 30
Area of second square = 900
Parimeter of second square = 120
Length of first Rectangle = 10
Breadth of first Rectangle = 20
Area of first Rectangle = 200
Parimeter of first Rectangle = 60
Length of second Rectangle = 15
Breadth of second Rectangle =
25
Area of second Rectangle = 375
Parimeter of first Rectangle = 80

Constructor: Every class has at least one it's own constructort. Constructor creates a instance
for the class. Constructor initiates (initialize) something related to the class's methods.
Constructor is the method which name is same to the class. But there are many difference
between the method (function) and the Constructor.
Java

In this example we will see that how to to implement the constructor feature in a class. This
program is using two classes. First class is another and second is the main class which name is
Construct. In the Construct class two objects (a and b) are created by using the overloaded
another Constructor by passing different arguments and calculated the are of the different
rectangle by passing different values for the another constructor.

Here is the code of the program :


class another{
int x,y;
another(int a, int b){
x = a;
y = b;
}
another(){
}
int area(){
int ar = x*y;
return(ar);
}
}
public class Construct{
public static void main(String[] args)
{
another b = new another();
b.x = 2;
b.y = 3;
System.out.println("Area of rectangle : " + b.area());
System.out.println("Value of y in another class : " + b.y);
another a = new another(1,1);
System.out.println("Area of rectangle : " + a.area());
System.out.println("Value of x in another class : " + a.x);
}
}

Output of the program :


Java

C:\chandan>javac Construct.java

C:\chandan>java Construct
Area of rectangle : 6
Value of x in another class : 3
Area of rectangle : 1
Value of x in another class : 1

Constructor Overloading: Here, you will learn more about Constructor and how
constructors are overloaded in Java. This section provides you a brief introduction about the
Constructor that are overloaded in the given program with complete code absolutely in
running state i.e. provided for best illustration about the constructor overloading in Java.
Constructors are used to assign initial values to instance variables of the class. A default
constructor with no arguments will be called automatically by the Java Virtual Machine
(JVM). Constructor is always called by new operator. Constructor are declared just like as we
declare methods, except that the constructor don't have any return type. Constructor can be
overloaded provided they should have different arguments because JVM differentiates
constructors on the basis of arguments passed in the constructor.
Whenever we assign the name of the method same as class name. Remember this method
should not have any return type. This is called as constructor overloading.
We have made one program on a constructor overloading, after going through it the concept of
constructor overloading will get more clear. In the example below we have made three
overloaded constructors each having different arguments types so that the JVM can
differentiates between the various constructors.
The code of the program is given below:
Java

public class ConstructorOverloading


{
public static void main(String args[])
{
Rectangle rectangle1=new Rectangle(2,4);

int areaInFirstConstructor=rectangle1.first();

System.out.println(" The area of a rectangle in first constructor is:"


+ areaInFirstConstructor);

Rectangle rectangle2=new Rectangle(5);

int areaInSecondConstructor=rectangle2.second();

System.out.println(" The area of a rectangle in first constructor is:"


+ areaInSecondConstructor);

Rectangle rectangle3=new Rectangle(2.0f);

float areaInThirdConstructor=rectangle3.third();
System.out.println(" The area of a rectangle in first constructor is:"
+ areaInThirdConstructor);

Rectangle rectangle4=new Rectangle(3.0f,2.0f);

float areaInFourthConstructor=rectangle4.fourth();
System.out.println(" The area of a rectangle in first constructor is:"
+ areaInFourthConstructor);
}
}
class Rectangle
{
int l, b;
float p, q;
public Rectangle(int x, int y)
{
l = x;
b = y;
}

public int first(){


return(l * b);
}
public Rectangle(int x){
l = x;
b = x;
}
public int second(){
return(l * b);
}
public Rectangle(float x){
Java

p = x;
q = x;
}
public float third(){
return(p * q);
}
public Rectangle(float x, float y){
p = x;
q = y;
}
public float fourth(){
return(p * q);
}
}

Output of the program is given below:

C:\java>java
ConstructorOverloading
The area of a rectangle in first
constructor is : 8
The area of a rectangle in first
constructor is : 25
The area of a rectangle in first
constructor is : 4.0
The area of a rectangle in first
constructor is : 6.

Hello world (First java program):


Java is a high level programming language and it is used to develop the robust application.
Java application program is platform independent and can be run on any operating System.
Writing Hello World program is very simple. To write the Hello world program you need
simple text editor like note pad and jdk must be install in your machine for compiling and
running. Hello world program is the first step of java programming language. Be careful
when you write the java code in your text pad because java is a case sensitive programming
language.
Java

For Example
hello world !=(not equal to) Hello World
Write the following code into your note pad to run the Hello World program .
class HelloWorld {
public static void main(String[] args){
System.out.println("Hello World!");
}
}
Save the file and Please remember the location where you save your file. In this example we
have saved the file in the "C:\javatutorial\example" directory. The file name should be match
the class name and to save the file give the .java extension. e.g. HelloWorld.java

Compiling and Running the program


Now open the command prompt to compile the HelloWorld.java program. Go to the directory
where you have saved the file ( in our case C:\javatutorial\example>) and issue the following
command to compile the program:
C:\javatutorial\example>javac HelloWorld.java
javac is a compiler in the java Language. Java compiler change the programming Language
into machinery language. So that the java virtual can understand it. Once the compilation is
successful a new file will be created with the name HelloWorld.class. To run the program
issue the following command on command prompt:
C:\javatutorial\example>java HelloWorld
You will see the following result on the command prompt.
Hello World!
Here is the screen shot of the above steps:
Java

In this lesson you have learned how to write and then test the Hello World! java program.
Under Standing the HelloWorld Program:
Class Declaration:
Class is the building block in Java, each and every methods & variable exists within the class
or object. (instance of program is called object ). The public word specifies the accessibility of
the class. The visibility of the class or function can be public, private, etc. The following code
declares a new class "HelloWorld" with the public accessibility:
public class HelloWorld {
The main Method:
The main method is the entry point in the Java program and java program can't run without
main method. JVM calls the main method of the class. This method is always first thing that is
executed in a java program. Here is the main method:
public static void main(String[] args) {
......
.....
}
{ and is used to start the beginning of main block and } ends the main block. Every thing in
the main block is executed by the JVM.
The code:
System.out.println("Hello, World");
prints the "Hello World" on the console. The above line calls the println method of System.out
class.
Java

The keyword static:


The keyword static indicates that the method is a class method, which can be called without
the requirement to instantiate an object of the class. This is used by the Java interpreter to
launch the program by invoking the main method of the class identified in the command to
start the program.
Variables:
Data type: The type of value that a variable can hold is called data type. When we declare a
variable we need to specify the type of value it will hold along with the name of the variable.
This tells the compiler that the particular variable will hold certain amount of memory to store
values. For example, in the lines of code above num is int type and takes two bytes to hold the
integer value, bol is a boolean type and takes one bit to hold a boolean value .
Some common types of data types are used in the programming languages called as the
primitive types like characters, integers, floating point numbers etc. These primitive data
types are given below where size represents the memory size it takes, For example, boolean
takes a value "true"/"false" in 1 bit memory. It takes value "false" if not initialized (in the
case of non-local variables)

Java Primitive Data Types


Data Type Description Size Default Value
boolean true or false 1-bit false
char Unicode Character 16-bit \u0000
byte Signed Integer 8-bit (byte) 0
short Signed Integer 16-bit (short) 0
int Signed Integer 32-bit 0
long Signed Integer 64-bit 0L
float Real number 32-bit 0.0f
double Real number 64-bit 0.0d
In this section, you will learn about Java variables. A variable refers to the memory location
that holds values like: numbers, texts etc. in the computer memory. A variable is a name of
location where the data is stored when a program executes.
The Java contains the following types of variables:
1. Instance Variables (Non-static fields): In object oriented programming, objects store
their individual states in the "non-static fields" that is declared without the static
keyword. Each object of the class has its own set of values for these non-static variables
so we can say that these are related to objects (instances of the class).Hence these
variables are also known as instance variables. These variables take default values if not
initialized.
Java

2. Class Variables (Static fields): These are collectively related to a class and none of the
object can claim them its sole-proprietor . The variables defined with static keyword are
shared by all objects. Here Objects do not store an individual value but they are forced to
share it among themselves. These variables are declared as "static fields" using the
static keyword. Always the same set of values is shared among different objects of the
same class. So these variables are like global variables which are same for all objects of
the class. These variables take default values if not initialized.
3. Local Variables: The variables defined in a method or block of code is called local
variables. These variables can be accessed within a method or block of code only. These
variables don't take default values if not initialized. These values are required to be
initialized before using them.
4. Parameters: Parameters or arguments are variables used in method declarations.

Declaring and defining variables


Before using variables you must declare the variables name and type. See the following
example for variables declaration:
int num; //represents that num is a variable that can store value of int type.
String name; //represents that name is a variable that can store string value.
boolean bol; //represents that bol is a variable that can take boolean value (true/false);
You can assign a value to a variable at the declaration time by using an assignment operator (
= ).
int num = 1000; // This line declares num as an int variable which holds value "1000".
boolean bol = true; // This line declares bol as boolean variable which is set to the value
"true".
Literals
By literal we mean any number, text, or other information that represents a value. This means
what you type is what you get. We will use literals in addition to variables in Java statement.
While writing a source code as a character sequence, we can specify any value as a literal such
as an integer. This character sequence will specify the syntax based on the value's type. This
will give a literal as a result. For instance
int month = 10;
In the above statement the literal is an integer value i.e 10. The literal is 10 because it directly
represents the integer value.
In Java programming language there are some special type of literals that represent numbers,
characters, strings and boolean values. Lets have a closer look on each of the following.
Number Literals
Number literals is a sequence of digits and a suffix as L. To represent the type as long integer
we use L as a suffix. We can specify the integers either in decimal, hexadecimal or octal
format. To indicate a decimal format put the left most digit as nonzero. Similarly put the
characters as ox to the left of at least one hexadecimal digit to indicate hexadecimal format.
Also we can indicate the octal format by a zero digit followed by the digits 0 to 7. Lets tweak
the table below.
Java

Decimal integer literal of type


659L
long integer
Hexadecimal integer literal of
0x4a
type integer
Octal integer literal of type
057L
long integer
Character Literals
We can specify a character literal as a single printable character in a pair of single quote
characters such as 'a', '#', and '3'. You must be knowing about the ASCII character set. The
ASCII character set includes 128 characters including letters, numerals, punctuations etc. There
are few character literals which are not readily printable through a keyboard. The table below
shows the codes that can represent these special characters. The letter d such as in the octal,
hex etc represents a number.
Escape Meaning
\n New line
\t Tab
\b Backspace
\r Carriage return
\f Formfeed
\\ Backslash
Single quotation
\'
mark
Double quotation
\"
mark
\d Octal
\xd Hexadecimal
\ud Unicode character
It is very interesting to know that if we want to specify a single quote, a backslash, or a
nonprintable character as a character literal use an escape sequence. An escape sequence uses
a special syntax to represents a character. The syntax begins with a single backslash character.

Lets see the table below in which the character literals use Unicode escape sequence to
represent printable and nonprintable characters both.
'u0041' Capital letter A
'\u0030' Digit 0
'\u0022' Double quote "
'\u003b' Punctuation ;
'\u0020' Space
'\u0009' Horizontal Tab
Java

Boolean Literals
The values true and false are also treated as literals in Java programming. When we assign a
value to a boolean variable, we can only use these two values. Unlike C, we can't presume that
the value of 1 is equivalent to true and 0 is equivalent to false in Java. We have to use the
values true and false to represent a Boolean value. Like
boolean chosen = true;
Remember that the literal true is not represented by the quotation marks around it. The Java
compiler will take it as a string of characters, if its in quotation marks.

Floating-point literals
Floating-point numbers are like real numbers in mathematics, for example, 4.13179,
-0.000001. Java has two kinds of floating-point numbers: float and double. The default type
when you write a floating-point literal is double.
Type Size Range Precision
name bytes bits approximate in decimal digits
float 4 32 +/- 3.4 * 1038 6-7
308
double 8 64 +/- 1.8 * 10 15
A floating-point literal can be denoted as a decimal point, a fraction part, an exponent
(represented by E or e) and as an integer. We also add a suffix to the floating point literal as D,
d, F or f. The type of a floating-point literal defaults to double-precision floating-point.
The following floating-point literals represent double-precision floating-point and floating-
point values.

6.5E+32 (or Double-precision


6.5E32) floating-point literal
Double-precision
7D
floating-point literal
.01f Floating-point literal
String Literals
The string of characters is represented as String literals in Java. In Java a string is not a basic
data type, rather it is an object. These strings are not stored in arrays as in C language. There
are few methods provided in Java to combine strings, modify strings and to know whether to
strings have the same value.
We represent string literals as
String myString = "How are you?";
The above example shows how to represent a string. It consists of a series of characters inside
double quotation marks.
Lets see some more examples of string literals:

"" // the empty string


"\"" // a string containing "
Java

"This is a string" // a string containing 16 characters


"This is a " + // actually a string-valued constant expression,
"two-line string" // formed from two string literals
Strings can include the character escape codes as well, as shown here:
String example = "Your Name, \"Sumit\"";
System.out.println("Thankingyou,\nRichards\n");
Null Literals
The final literal that we can use in Java programming is a Null literal. We specify the Null
literal in the source code as 'null'. To reduce the number of references to an object, use null
literal. The type of the null literal is always null. We typically assign null literals to object
reference variables. For instance
s = null;
An this example an object is referenced by s. We reduce the number of references to an object
by assigning null to s. Now, as in this example the object is no longer referenced so it will be
available for the garbage collection i.e. the compiler will destroy it and the free memory will
be allocated to the other object. Well, we will later learn about garbage
collection.

7. Array

Introduction to java arrays:


In this section you will be introduced to the concept of Arrays in Java Programming language.
You will learn how the Array class in java helps the programmer to organize the same type of
data into easily manageable format.
Program data is stored in the variables and takes the memory spaces, randomly. However,
when we need the data of the same type to store in the contiguous memory allocations we use
the data structures like arrays. To meet this feature java has provided an Array class which
abstracts the array data-structure.
The java array enables the user to store the values of the same type in contiguous memory
allocations. Arrays are always a fixed length abstracted data structure which can not be altered
when required.
The Array class implicitly extends java.lang.Object so an array is an instance of Object.
Structure of Arrays
Now lets study the structure of Arrays in java. Array is the most widely used data structure in
java. It can contain multiple values of the same type. Moreover, arrays are always of fixed
length i.e. the length of an array cannot be increased or decreased.
Lets have a close look over the structure of Array. Array contains the values which are
implicitly referenced through the index values. So to access the stored values in an array we
use indexes. Suppose an array contains "n" integers. The first element of this array will be
indexed with the "0" value and the last integer will be referenced by "n-1" indexed value.
Java

Presume an array that contains 12 elements as shown in the figure. Each element is holding a
distinct value. Here the first element is refrenced by a[0] i.e. the first index value. We have
filled the 12 distinct values in the array each referenced as:
a[0]=1
a[1]=2
...
a[n-1]=n
...
a[11]=12
The figure below shows the structure of an Array more precisely.

Array Declaration
As we declare a variable in Java, An Array variable is declared the same way. Array variable
has a type and a valid Java identifier i.e. the array's type and the array's name. By type we
mean the type of elements contained in an array. To represent the variable as an Array, we use
[] notation. These two brackets are used to hold the array of a variable.
By array's name, we mean that we can give any name to the array, however it should follow
the predefined conventions. Below are the examples which show how to declare an array :-

int[] array_name; //declares an


array of integers
String[] names;
int[][] matrix; //this is an array
of arrays
Java

It is essential to assign memory to an array when we declare it. Memory is assigned to set the
size of the declared array. for example:
int[] array_name =
new int[5];

Here is an example that creates an array that has 5 elements.


public class Array
{
public static void
main(String[] args)
{
int[] a = new int[5];
}
}

Array Initialization
After declaring an array variable, memory is allocated to it. The "new" operator is used for the
allocation of memory to the array object. The correct way to use the "new" operator is
String names[];
names = new String[10];
Here, the new operator is followed by the type of variable and the number of elements to be
allocated. In this example [] operator has been used to place the number of elements to be
allocated.
Lets see a simple example of an array,
public class Sum
{
public static void main(String[] args)
{
int[] x = new int [101];
for (int i = 0; i<x.length; i++ )
x[i] = i;
int sum = 0;
for(int i = 0; i<x.length; i++)
sum += x[i];
System.out.println(sum);
}
}

In this example, a variable 'x' is declared which has a type array of int, that is, int[]. The
variable x is initialized to reference a newly created array object. The expression 'int[] = new
int[50]' specifies that the array should have 50 components. To know the length of the Array,
we use field length, as shown.
Java

Output for the given program:


C:\tamana>javac
Sum.java

C:\tamana>java
Sum
5050

C:\tamana>
Array Usage
We have already discussed that to refer an element within an array, we use the [] operator. The
[] operator takes an "int" operand and returns the element at that index. We also know that the
array indices start with zero, so the first element will be held by the 0 index. For Example :-
int month = months[4]; //get the 5th month (May)
Most of the times it is not known in the program that which elements are of interest in an
array. To find the elements of interest in the program, it is required that the program must run a
loop through the array. For this purpose "for" loop is used to examine each element in an array.
For example :-
String months[] =
{"Jan", "Feb", "Mar", "Apr",
"May", "Jun",
"July", "Aug", "Sep",
"Oct", "Nov", "Dec"};
//use the length attribute
to get the number
//of elements in an array
for (int i = 0; i <
months.length; i++ ) {
System.out.println("month:
" + month[i]);

Here, we have taken an array of months which is,


String months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "July", "Aug", "Sep", "Oct",
"Nov", "Dec"};
Now, we run a for loop to print each element individually starting from the month "Jan".
for (int i = 0; i < months.length; i++ )
In this loop int i = 0; indicates that the loop starts from the 0th position of an array and goes
upto the last position which is length-1, i < months.length; indicates the
length of the array and i++ is used for the increment in the value of i which is i = i+1.
Multi-dimensional arrays
So far we have studied about the one-dimensional and two-dimensional arrays. To store data in
more dimensions a multi-dimensional array is used. A multi-dimensional array of dimension n
is a collection of items. These items are accessed via n subscript expressions. For example, in
a language that supports it, the element of the two-dimensional array x is denoted by x[i,j].
Java

The Java programming language does not really support multi-dimensional arrays. It does,
however, supports an array of arrays. In Java, a two-dimensional array ' x' is an array of one-
dimensional array : For instance :-
int[][] x = new int[3][5];
The expression x[i] is used to select the one-dimensional array; the expression x[i][j] is ued to
select the element from that array. The first element of this array will be indexed with the "0"
value and the last integer will be referenced by "length-1" indexed value. There is no array
assignment operator.

Two-dimensional arrays
Two-dimensional arrays are defined as "an array of arrays". Since an array type is a first-class
Java type, we can have an array of ints, an array of Strings, or an array of Objects. For
example, an array of ints will have the type int[]. Similarly we can have int[][], which
represents an "array of arrays of ints". Such an array is said to be a two-dimensional array.
The command
int[][] A = new int[3][4]
declares a variable, A, of type int[][], and it initializes that variable to refer to a newly created
object. That object is an array of arrays of ints. Here, the notation int[3][4] indicates that there
are 3 arrays of ints in the array A, and that there are 4 ints in each of those arrays.
To process a two-dimensional array, we use nested for loops. We already know about for loop.
A loop in a loop is called a Nested loop. That means we can run another loop in a loop.

Notice in the following example how the rows are handled as separate objects.
Code: Java
int[][] a2 = new int[10][5];
// print array in rectangular
form
for (int r=0; r<a2.length; r++)
{
for (int c=0;
c<a2[r].length; c++) {
System.out.print(" " +
a2[r][c]);
}
System.out.println("");
}

In this example, "int[][] a2 = new int[10][5];" notation shows a two-dimensional array. It


declares a variable a2 of type int[][],and it initializes that variable to refer to a newly created
object. The notation int[10][5] indicates that there are 10 arrays of ints in the array a2, and that
there are 5 ints in each of those arrays.
Java

Copying Arrays
After learning all about arrays, there is still one interesting thing left to learn i.e. copying
arrays. It means to copy data from one array to another. The precise way to copy data from one
array to another is
public static void
arraycopy(Object source,
int
srcIndex,
Object
dest,
int
destIndex,
int
length)

Thus apply system's arraycopy method for copying arrays.The parameters being used are :-
src the source array
srcIndex start position (first cell to
copy) in the source array
dest the destination array
destIndex start position in the
destination array
length the number of array
elements to be copied
The following program, ArrayCopyDemo(in a .java source file), uses arraycopy to copy some
elements from the copyFrom array to the copyTo array.
public class ArrayCopyDemo{
public static void main(String[] args){
char[] copyFrom = {'a','b','c','d','e','f','g','h','i','j'};
char[] copyTo = new char[5];
System.arraycopy(copyFrom, 2, copyTo, 0, 5);
System.out.println(new String (copyTo));
}
}

In this example the array method call begins the copy of elements from element number 2.
Thus the copy begins at the array element 'c'. Now, the arraycopy method takes the copie
element and puts it into the destination array. The destination array begins at the first element
(element 0) which is the destination array copyTo. The copyTo copies 5 elements : 'c', 'd', 'e',
'f', 'g'. This method will take "cdefg" out of "abcdefghij", like this :
Java

8. Control Statements...

Control Statements:
We all know that the execution of the statements in a program takes place from top to bottom.
We will learn how the different kinds of statement have different effects in looping like
decision-making statements (if-then, if-then-else, switch), the looping statements (for, while,
do-while), and the branching statements (break, continue, return) in Java programming
language.
Selection

The if statement: To start with controlling statements in Java, lets have a recap over the
control statements in C++. You must be familiar with the if-then statements in C++. The if-
then statement is the most simpler form of control flow statement. It directs the program to
execute a certain section of code. This code gets executed if and only if the test evaluates to
true. That is the if statement in Java is a test of any Boolean expression. The statement
following the if will only be executed when the Boolean expression evaluates to true. On the
contrary if the Boolean expression evaluates to false then the statement following the if will
not only be executed.
Lets tweak th example below:
if (a > 1)
System.out.println("Greater than 1");
if (a < 1)
System.out.println("Less than 1");
In the above example if we declare int a = 1, the statements will show some of the valid
Boolean expressions to the if statement.
We are talking about if statements here so we can't forget the else statement here. The if
statement is incomplete without the else statement. The general form of the statement is:
if (condition)
statement1;
else
statement2;
The above format shows that an else statement will be executed whenever an if statement
evaluates to false. For instance,
if (a>1){
System.out.println("greater than 1");
}
else{
System.out.println("smaller than 1");
}
Java

Lets have a look at a slightly different example as shown below:


class compare{
public static void main(String[] args)
{
int a = 20;
int b = 40;
if (a<b){
System.out.println(a);
}
else{
System.out.println(b);
}
}
}

The above example shows that we have taken two numbers and we have to find the largest
amongst them. We have applied a condition that if a<b, print 'a' else print 'a is greater'. The
following is the output which we will get in the command prompt.
C:\javac>javac
compare.java

C:\javac>java compare
40

Iteration:
The concept of Iteration has made our life much more easier. Repetition of similar tasks is
what Iteration is and that too without making any errors. Until now we have learnt how to use
selection statements to perform repetition. Now lets have a quick look at the iteration
statements which have the ability to loop through a set of values to solve real-world
problems.
The for Statement
In the world of Java programming, the for loop has made the life much more easier. It is used
to execute a block of code continuously to accomplish a particular condition. For statement
consists of tree parts i.e. initialization, condition, and iteration.
initialization : It is an expression that sets the value of the loop control variable. It executes
only once.
condition : This must be a boolean expression. It tests the loop control variable against a
target value and hence works as a loop terminator.
iteration : It is an expression that increments or decrements the loop control variable.
Here is the form of the for loop:

for(initialization; condition; iteration){


//body of the loop
}
For example, a sample for loop may appear as follows:
Java

int i;
for (i=0; i<10; i++)
System.out.println("i = " +i);
In the above example, we have initialized the for loop by assigning the '0' value to i. The test
expression, i < 100, indicates that the loop should continue as long as i is less than 100.
Finally, the increment statement increments the value of i by one. The statement following the
for loop will be executed as long as the test expression is true as follows:
System.out.println("i = " + i);
Well, we can add more things inside a loop. To do so we can use curly braces to indicate the
scope of the for loop. Like,
int i;
for (i=0; i<10; i++) {
MyMethod(i);
System.out.println("i = " + i);
}

There is a simpler way to declare and initialize the variable used in the loop. For example, in
the following code, the variable i is declared directly within the for loop:
for (int i=0; i<100; i++)
System.out.println("i = " +i);
Lets see a simple example which will help you to understand for loop very easily. In this
example we will print 'Hello World' ten times using for loop.
class printDemo{
public static void main(String[] args){
for (int i = 0; i<10; i++){
System.out.println("Hello World!");
}
}
}
Java

Here is the output:


C:\javac>javac
printDemo.java

C:\javac>java
printDemo
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
After learning how to use a for loop, I would like to introduce another form of for loop to be
used for iteration through collection and arrays. This form has enhanced the working of for
loop. This is the more compact way to use a for loop.
Here we will take an array of 10 numbers.
int[] numbers = {1,2,3,4,5,6,7,8,9,10};

The following program, arrayDemo,displays the usage of for loop through arrays. It shows the
variable item that holds the the current value from the array.
class arrayDemo{
public static void main(String[] args){
int[] numbers = {1,2,3,4,5,6,7,8,9,10};
for (int item : numbers) {
System.out.println("Count is: " + item);
}
}
}

Here is the output of the program


C:\javac>javac
arrayDemo.java

C:\javac>java
arrayDemo
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Java

Count is: 6
Count is: 7
Count is: 8
Count is: 9
Count is: 10

Switch:
Sometimes it becomes cumbersome to write lengthy programs using if and if-else statements.
To avoid this we can use Switch statements in Java. The switch statement is used to select
multiple alternative execution paths. This means it allows any number of possible execution
paths. However, this execution depends on the value of a variable or expression. The switch
statement in Java is the best way to test a single expression against a series of possible values
and executing the code.
Here is the general form of switch statement:
switch (expression)
{
case 1:
code block1
case 2:
code block2
.
.
.
default:
code default;
}
The expression to the switch must be of a type byte, short, char, or int. Then there is a code
block following the switch statement that comprises of multiple case statements and an
optional default statement.
The execution of the switch statement takes place by comparing the value of the expression
with each of the constants. The comparison of the values of the expression with each of the
constants occurs after the case statements. Otherwise, the statements after the default
statement will be executed.
Now, to terminate a statement following a switch statement use break statement within the
code block. However, its an optional statement. The break statement is used to make the
computer jump to the end of the switch statement. Remember, if we won't use break statement
the computer will go ahead to execute the statements associated with the next case after
executing the first statement.
switch (P { // assume P is an integer variable
case 1:
System.out.println("The number is 1.");
break;
case 2:
case 4:
Java

case 8:
System.out.println("The number is 2, 4, or 8.");
System.out.println("(That's a power of 2!)");
break;
case 3:
case 6:
case 9:
System.out.println("The number is 3, 6, or 9.");
System.out.println("(That's a multiple of 3!)");
break;
case 5:
System.out.println("The number is 5.");
break;
default:
System.out.println("The number is 7,");
System.out.println(" or is outside the range 1 to 9.");
}
For example the following program Switch, declares an int named week whose value
represents a day out of the week. The program displays the name of the day, based on the
value of week, using the switch statement
class Switch{
public static void main(String[] args){
int week = 5;
switch (week){
case 1: System.out.println("monday"); break;
case 2: System.out.println("tuesday"); break;
case 3: System.out.println("wednesday"); break;
case 4: System.out.println("thursday"); break;
case 5: System.out.println("friday"); break;
case 6: System.out.println("saturday"); break;
case 7: System.out.println("sunday"); break;

default: System.out.println("Invalid week");break;


}
}
}

Output:
C:\javac>javac
Switch.java

C:\javac>java
Switch
friday
Java

In this case, "friday" is printed to standard output.


One other point to note here is that the body of a switch statement is known as a switch block.
The appropriate case gets executed when the switch statement evaluates its expression.
While and do-while:
Lets try to find out what a while statement does. In a simpler language, the while statement
continually executes a block of statements while a particular condition is true. To write a while
statement use the following form:
while (expression)
{
statement(s)
}
Lets see the flow of the execution of the while statement in steps:
1. Firstly, It evaluates the condition in parentheses, yielding true or false.
2. Secondly, It continues to execute the next statement if the condition is false and exit the
while statement.
3. Lastly, If the condition is true it executes each of the statements between the brackets and
then go back to step 1.

For example:
class Bonjour{
public static void main (String args[]){
int i = 0; // Declare and initialize loop counter
while (i < 5){ // Test and Loop
System.out.println("Bonjour "); // Say Bonjour
i = i + 1; // Increment LoopCounter
}
}
}

In the above example, firstly the condition will be checked in the parentheses, while
(i<args.length). If it comes out to be true then it will continue the execution till the last line
and will go back to the loop again. However, if its false it will continue the next statement and
will exit the while loop.
The output is as follows:
C:\vinod\xml>javac
Bonjour.java

C:\vinod\xml>java
Bonjour
Bonjour
Bonjour
Bonjour
Bonjour
Bonjour
Java

The while statement works as to for loop because the third step loops back to the top.
Remember, the statement inside the loop will not execute if the condition is false. The
statement inside the loop is called the body of the loop. The value of the variable should be
changed in the loop so that the condition becomes false and the loop terminates.
Have a look at do-while statement now.
Here is the syntax:
do
{
statement(s)
} while (expression);

Lets tweak an example of do-while loop.

class DoWhileDemo
{
public static void main (String args[])
{
int i = 0;
do{
System.out.print("Bonjour");
System.out.println(" ");
i = i + 1;
}while (i < 5);
}
}

In the above example, it will enter the loop without checking the condition first and checks the
condition after the execution of the statements. That is it will execute the statement once and
then it will evaluate the result according to the condition.
The output is as follows:
C:\javac>java
DoWhileDemo
Bonjour
Bonjour
Bonjour
Bonjour
Bonjour

C:\javac>
You must have noticed the difference between the while and do-while loop. That is the do-
while loop evaluates its expression at the bottom of the loop. Hence, the statement in the do-
while loop will be executed once.
Java

Break:
Sometimes we use Jumping Statements in Java. Using for, while and do-while loops is not
always the right idea to use because they are cumbersome to read. Using jumping statements
like break and continue it is easier to jump out of loops to control other areas of program flow.

We use break statement to terminate the loop once the condition gets satisfied.
Lets see a simple example using break statement.
class BreakDemo
{
public static void main(String[] args)
{
for (int i = 0; i < 5; i++)
{
System.out.println(i);
if (i==3)
{
break ;
}
}
}
}

In the above example, we want to print 5 numbers from 0 to 1 at first using for loop as shown.
Then we put a condition that 'if i = = 3', the loop should be terminated. To terminate the loop
after satisfying the condition we use break.
It gives the following output:

C:\javac>javac
BreakDemo.java

C:\javac>java
BreakDemo
0
1
2
3
The break statement has two forms: labeled and unlabeled. You saw the labeled form in the
above example i.e. a labeled break terminates an outer statement. However, an unlabeled
break statement terminates the innermost loop like switch, for, while, or do-while statement.
Java

Now observe the example of unlabeled form below. We have used two loops here two print
'*'. In this example, if we haven't use break statement thus the loop will continue and it will
give the output as shown below.

class BreaklabDemo1
{
public static void main(String[] args)
{
for (int i = 0; i < 10; i++) {
System.out.print("\n");
for (int j = 0; j<=i; j++)
{
System.out.print("*");
if (j==5)
{ // break;
}
}
}

Output:
C:\javac>javac
BreaklabDemo1.java

C:\javac>java
BreaklabDemo1

*
**
***
****
*****
******
*******
********
*********
**********
C:\javac>
Java

However in the following example we have used break statement. In this the inner for loop i.e.
"for (int j=0; j<=i; j++)" will be executed first and gets terminated there n then. Then the outer
for loop will be executed i.e. "for (int i=0; i<10; i++)". And it will give the output as shown
below.
class BreaklabDemo{
public static void main(String[] args){
for (int i = 0; i < 10; i++) {
System.out.print("\n ");
for (int j = 0; j<=i; j++){
System.out.print("*");
if (j==5)
break;
}
}
}
}

Output:
C:\javac>javac
BreaklabDemo.java

C:\javac>java
BreaklabDemo

*
**
***
****
*****
******
******
******
******
******
C:\javac>

continue :-

Continue statement is just similar to the break statement in the way that a break statement is
used to pass program control immediately after the end of a loop and the continue statement is
used to force program control back to the top of a loop.
Lets see the same example of break statement but here we will use continue instead of break.
The continue statement skips the current iteration of a for, while , or do-while loop. The
unlabeled form skips to the end of the innermost loop's body and evaluates the boolean
expression that controls the loop.
Java

For Instance,
class continueStatement
{
public static void
main(String[] args)
{
for (int i = 0; i < 5; i+
+) {
System.out.println(i);
if (i==3) {
continue ;
}
}
}
}

C:\javac>javac
continueStatement.java

C:\javac>java
continueStatement
0
1
2
3
4

C:\javac>

9. Class, Object and Methods:

Class, Object and Methods:


Class : Whatever we can see in this world all the things are a object. And all the objects are
categorized in a special group. That group is termed as a class. All the objects are direct
interacted with its class that mean almost all the properties of the object should be matched
with it's own class. Object is the feature of a class which is used for the working on the
particular properties of the class or its group. We can understand about the class and object
like this : we are all the body are different - different objects of the human being class. That
means all the properties of a proper person relates to the human being. Class has many other
features like creation and implementation of the object, Inheritance etc.
Java

In this Program you will see how to use the class, object and it's methods. This program uses
the several values of several defined variables for getting the Area and Perimeter of the Square
and Rectangle by calling the different functions from the different classes through the several
objects created for the several class. In this program there are two classes has been used except
the main class in which the main function is declared. First class is square which is used for
getting the Area and Perimeter of the square and another class is rectangle which is used for
getting the Area and Perimeter of the Rectangle. All the functions in the square and rectangle
class are calling with different - different arguments two times for getting the Area and
Perimeter of square and rectangle for two different sides. This program gives us the Area and
Perimeter for the different sided Square and Rectangle separately. Full running code is given
with the example:
Here is the code of the program :
class square
{
int sqarea(int side)
{
int area = side * side;
return(area);
}
int sqpari(int side)
{
int pari = 4 * side;
return(pari);
}
}

class rectangle
{
int rectarea(int length,int breadth)
{
int area = length * breadth;
return(area);
}
int rectpari(int length,int breadth)
{
int pari = 2*(length + breadth);
return(pari);
}
}

public class ObjectClass


{
public static void main(String args[])
{
int sarea1,sarea2,pari1,pari2;
int rectarea1,rectarea2,rectpari1,rectpari2;
square sq = new square();
rectangle rect = new rectangle();
int a=20;
System.out.println("Side of first square = " + a);
sarea1 = sq.sqarea(a);
pari1 = sq.sqpari(a);
Java

System.out.println("Area of first square = " + sarea1);


System.out.println("Parimeter of first square = " + pari1);
a = 30;
System.out.println("Side of second square = " + a);
sarea2 = sq.sqarea(a);
pari2 = sq.sqpari(a);
System.out.println("Area of second square = " + sarea2);
System.out.println("Parimeter of second square = " + pari2);
int x = 10, y = 20;
System.out.println("Length of first Rectangle = " + x);
System.out.println("Breadth of first Rectangle = " + y);
rectarea1 = rect.rectarea(x,y);
rectpari1 = rect.rectpari(x,y);
System.out.println("Area of first Rectangle = " + rectarea1);
System.out.println("Parimeter of first Rectangle = " + rectpari1);
x = 15;
y = 25;
System.out.println("Length of second Rectangle = " + x);
System.out.println("Breadth of second Rectangle = " + y);
rectarea2 = rect.rectarea(x,y);
rectpari2 = rect.rectpari(x,y);
System.out.println("Area of second Rectangle = " + rectarea2);
System.out.println("Parimeter of first Rectangle = " + rectpari2);
}
}

Descriptions of the program:


Object : Objects are the basic run time entity or in other words object is a instance of a class .
An object is a software bundle of variables and related methods of the special class. In the
above example the sq is the object of square class and rect is the object of the rectangle class.
In real-world objects share two characteristics: They have all state and behavior. For example,
The squares have state such as : sides and behaviors such as its areas and perimeters.
Rectangles have state such as: length, breadth and behavior such as its areas and perimeters. A
object implements its behavior with methods of it's classes. A method is a function
(subroutine) associated with an object.
Syntax for the Object :
class_name object_name = new class_name();
Java

Output of the program :

C:\chandan>javac ObjectClass.java
C:\chandan>java ObjectClass
Side of first square = 20
Area of first square = 400
Parimeter of first square = 80
Side of second square = 30
Area of second square = 900
Parimeter of second square = 120
Length of first Rectangle = 10
Breadth of first Rectangle = 20
Area of first Rectangle = 200
Parimeter of first Rectangle = 60
Length of second Rectangle = 15
Breadth of second Rectangle = 25
Area of second Rectangle = 375
Parimeter of first Rectangle = 80

Constructor: Every class has at least one it's own constructor. Constructor creates a instance
for the class. Constructor initiates (initialize) something related to the class's methods.
Constructor is the method which name is same to the class. But there are many difference
between the method (function) and the Constructor.
In this example we will see that how to to implement the constructor feature in a class. This
program is using two classes. First class is another and second is the main class which name is
Construct. In the Construct class two objects (a and b) are created by using the overloaded
another Constructor by passing different arguments and calculated the are of the different
rectangle by passing different values for the another constructor.

Here is the code of the program:


class another{
int x,y;
another(int a, int b){
x = a;
y = b;
}
another(){
}
int area(){
int ar = x*y;
return(ar);
}
}
public class Construct{
public static void main(String[] args)
{
Java

another b = new another();


b.x = 2;
b.y = 3;
System.out.println("Area of rectangle : " + b.area());
System.out.println("Value of y in another class : " + b.y);
another a = new another(1,1);
System.out.println("Area of rectangle : " + a.area());
System.out.println("Value of x in another class : " + a.x);
}
}

Output of the program :

C:\chandan>javac Construct.java

C:\chandan>java Construct
Area of rectangle : 6
Value of x in another class : 3
Area of rectangle : 1
Value of x in another class : 1
Constructor Overloading: Here, you will learn more about Constructor and how
constructors are overloaded in Java. This section provides you a brief introduction about the
Constructor that are overloaded in the given program with complete code absolutely in
running state i.e. provided for best illustration about the constructor overloading in Java.
Constructors are used to assign initial values to instance variables of the class. A default
constructor with no arguments will be called automatically by the Java Virtual Machine
(JVM). Constructor is always called by new operator. Constructor are declared just like as we
declare methods, except that the constructor don't have any return type. Constructor can be
overloaded provided they should have different arguments because JVM differentiates
constructors on the basis of arguments passed in the constructor.
Whenever we assign the name of the method same as class name. Remember this method
should not have any return type. This is called as constructor overloading.
We have made one program on a constructor overloading, after going through it the concept of
constructor overloading will get more clear. In the example below we have made three
overloaded constructors each having different arguments types so that the JVM can
differentiates between the various constructors.
Java

The code of the program is given below:


public class ConstructorOverloading
{
public static void main(String args[])
{
Rectangle rectangle1=new Rectangle(2,4);
int areaInFirstConstructor=rectangle1.first();
System.out.println(" The area of a rectangle in
first constructor is : " + areaInFirstConstructor);
Rectangle rectangle2=new Rectangle(5);
int areaInSecondConstructor=rectangle2.second();
System.out.println(" The area of a rectangle in
first constructor is : " + areaInSecondConstructor);
Rectangle rectangle3=new Rectangle(2.0f);
float areaInThirdConstructor=rectangle3.third();
System.out.println(" The area of a rectangle in first
constructor is : " + areaInThirdConstructor);
Rectangle rectangle4=new Rectangle(3.0f,2.0f);
float areaInFourthConstructor=rectangle4.fourth();
System.out.println(" The area of a rectangle in first
constructor is : " + areaInFourthConstructor);
}
}

class Rectangle
{
int l, b;
float p, q;
public Rectangle(int x, int y)
{
l = x;
b = y;
}
public int first()
{
return(l * b);
}
public Rectangle(int x)
{
l = x;
b = x;
}
public int second()
{
return(l * b);
}
public Rectangle(float x)
{
p = x;
q = x;
}

public float third()


{
Java

return(p * q);
}
public Rectangle(float x, float y){
p = x;
q = y;
}
public float fourth(){
return(p * q);
}
}

Output of the program is given below:

C:\java>java
ConstructorOverloading
The area of a rectangle in first
constructor is : 8
The area of a rectangle in first
constructor is : 25
The area of a rectangle in first
constructor is : 4.0
The area of a rectangle in first
constructor is : 6.0
10. Inheritance:

Inheritance:

To know the concept of inheritance clearly you must have the idea of class and its features like
methods, data members, access controls, constructors, keywords this, super etc.
As the name suggests, inheritance means to take something that is already made. It is one of
the most important feature of Object Oriented Programming. It is the concept that is used for
reusability purpose. Inheritance is the mechanism through which we can derived classes from
other classes. The derived class is called as child class or the subclass or we can say the
extended class and the class from which we are deriving the subclass is called the base class or
the parent class. To derive a class in java the keyword extends is used. To clearly understand
the concept of inheritance you must go through the following example.
The concept of inheritance is used to make the things from general to more specific e.g. When
we hear the word vehicle then we got an image in our mind that it moves from one place to
another place it is used for traveling or carrying goods but the word vehicle does not specify
whether it is two or three or four wheeler because it is a general word. But the word car makes
a more specific image in mind than vehicle, that the car has four wheels . It concludes from the
example that car is a specific word and vehicle is the general word. If we think technically to
this example then vehicle is the super class (or base class or parent class) and car is the
Java

subclass or child class because every car has the features of it's parent (in this case vehicle)
class.
The following kinds of inheritance are there in java.
Simple Inheritance
Multilevel Inheritance

Pictorial Representation of Simple and Multilevel Inheritance

Simple Inheritance Multilevel Inheritance

Simple Inheritance
When a subclass is derived simply from it's parent class then this mechanism is known as
simple inheritance. In case of simple inheritance there is only a sub class and it's parent class.
It is also called single inheritance or one level inheritance.
eg.
class A {
int x;
int y;
int get(int p, int q){
x=p; y=q; return(0);
}
void Show(){
System.out.println(x);
}
}

class B extends A{
public static void main(String args[]){
A a = new A();
a.get(5,6);
a.Show();
}
void display(){
System.out.println("B");
}
}
Java

Multilevel Inheritance
It is the enhancement of the concept of inheritance. When a subclass is derived from a derived
class then this mechanism is known as the multilevel inheritance. The derived class is called
the subclass or child class for it's parent class and this parent class works as the child class for
it's just above ( parent ) class. Multilevel inheritance can go up to any number of level.
e.g.
class A {
int x;
int y;
int get(int p, int q){
x=p; y=q; return(0);
}
void Show(){
System.out.println(x);
}
}
class B extends A{
void Showb(){
System.out.println("B");
}
}

class C extends B{
void display(){
System.out.println("C");
}
public static void main(String args[]){
A a = new A();
a.get(5,6);
a.Show();
}
}

Java does not support multiple Inheritance


Multiple Inheritance
The mechanism of inheriting the features of more than one base class into a single class is
known as multiple inheritance. Java does not support multiple inheritance but the multiple
inheritance can be achieved by using the interface.
In Java Multiple Inheritance can be achieved through use of Interfaces by implementing more
than one interfaces in a class.
super keyword
The super is java keyword. As the name suggest super is used to access the members of the
super class.It is used for two purposes in java.
The first use of keyword super is to access the hidden data variables of the super class
hidden by the sub class.
Java

e.g. Suppose class A is the super class that has two instance variables as int a and float b. class
B is the subclass that also contains its own data members named a and b. then we can access
the super class (class A) variables a and b inside the subclass class B just by calling the
following command.
super.member;
Here member can either be an instance variable or a method. This form of super most useful to
handle situations where the local members of a subclass hides the members of a super class
having the same name. The following example clarify all the confusions.
class A{
int a;
float b;
void Show(){
System.out.println("b in super class: " + b);
}

class B extends A{
int a;
float b;
B( int p, float q){
a = p;
super.b = q;
}
void Show(){
super.Show();
System.out.println("b in super class: " + super.b);
System.out.println("a in sub class: " + a);
}

public static void main(String[] args){


B subobj = new B(1, 5);
subobj.Show();
}
}

C:\>java B
b in super class: 5.0
b in super class: 5.0
a in sub class: 1

Use of super to call super class constructor: The second use of the keyword super in java is
to call super class constructor in the subclass. This functionality can be achieved just by using
the following command.
Java

super(param-list);
Here parameter list is the list of the parameter requires by the constructor in the super class.
super must be the first statement executed inside a super class constructor. If we want to call
the default constructor then we pass the empty parameter list. The following program
illustrates the use of the super keyword to call a super class constructor.

class A{
int a;
int b;
int c;
A(int p, int q, int r){
a=p;
b=q;
c=r;
}
}

class B extends A{
int d;
B(int l, int m, int n, int o){
super(l,m,n);
d=o;
}
void Show(){
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
}

public static void main(String args[]){


B b = new B(4,3,8,7);
b.Show();
}
}

Output:
C:\>java B
a=4
b=3
c=8
d=7
Java

11. Abstract methods and Classes:

While going through the java programming language you have learned so many times the
word abstract. In java programming language the word abstract is used with methods and
classes.
Abstract Method
An abstract method one that have the empty implementation. All the methods in any interface
are abstract by default. Abstract method provides the standardization for the " name and
signature" of any method. One can extend and implement to these methods in their own
classes according to the requirements.

e.g.
public abstract abs_value();

Abstract Class
In java programming language, abstract classes are those that works only as the parent class or
the base class. Subclasses are derived to implement the methods inherited from the abstract
class (base class). Abstract classes are not instantiated directly. First extends the base class and
then instantiate (create objects). Abstract classes are generic in nature and implement to those
methods that are used commonly by the subclasses with common implementation. Abstract
classes .
e.g.
abstract class A{
public abstract abs_value();

void show(){
System.out.println("This is an abstract class");
}
}

12. Package:-

Introduction to Java Package


Package is a mechanism for organizing a group of related files in the same directory. In a
computer system
, we organize files into
different directories according to their functionality, usability and category.
An example of package is the JDK package of SUN Java as shown below:
Java

In Java, a package is a group of related types classes and interfaces which provides access
protection and name space management to use those classes and interfaces. Apart from these,
Java also supports special kinds of classes and interfaces known as Enumerations and
Annotation, respectively.
Packaging is used to organize classes that belong to the same files or providing similar
functionality. Apart from this, it also helps the programmer to avoid class name collision when
we use the same class name as available in the another packages. For example, the Date class
of java.util package is used to access the methods of the Date class. But, if we have a class
name "Date" (user defined) in our program, its name would crash with the Date class of
java.util package. To avoid this problem, we can use Package through which the "Date"
class can be put up into another package like india.mycompany.Date without collision with
anyone.
Generally, classes in one package (or directory) have different functionality from the another
package. For example, classes in java.io package manage the Input/Output streams to read
and write data from and to files, while classes in java.net package give us the way to deal with
the network operations.

Features of a Java package


The protected members of the classes can be accessed by each other in the same package.
It resolves the naming collision for the types it contains.
A package may have the following types.
o Interfaces
o Classes
o Enumerated types
o Annotations
Java

Naming convention (Rules) for using the packages


Package names are written in all lowercase to avoid conflict with the names of classes
or interfaces.
The directory name must be same as the name of package that is created using
"package" keyword in the source file.
Before running a program, the class path must be picked up till the main directory (or
package) that is used in the program.
If we are not including any package in our java source file then the source file
automatically goes to the default package.
In general, we start a package name begins with the order from top to bottom level.
In case of the internet domain, the name of the domain is treated in reverse (prefix)
order.

Java Package Names and Directory Structure


Java Packages are usually defined using a hierarchical naming pattern in which the Package
name consists of words separated by periods. The first part of the Package name represents the
main directory in which other subpackages or classes are put up. The remaining part of the
Package name reflect the sub contents of the package. Just see the example of packages names:
Internet
Package name Subdirectory path
Domain
java.sun.com com.sun.java.text \com\sun\java\text
murach.com com.murach.orders \com\murach\orders

Lets see a general example to understand the directory structure of the package importing the
javax.swing package.
import javax.swing.*;

public class PackageDemo {


public PackageDemo(){
JOptionPane.showMessageDialog(new JFrame(),
" This is a Dialog Box component of swing ","My Message",
JOptionPane.INFORMATION_MESSAGE);

}
public static void main(String[] args){
PackageDemo obj=new PackageDemo();
}
}
Java

Output of the program:

In the above example, a Java Package "javax.swing" is a buid-in package imported from the
JFC (Java Foundation Classes). The first name of that package "javax" represents the main
package. The second part of the package name "swing" stands for the contents of the package.
All classes and interfaces reside in the swing package can be accessed according to their
functionality.
program
How to Set the Class Path:
The classpath is a user defined environment variable that is used by Java to determine where
predefined classes are located. It tells the java tools and applications where to find user-
defined classes. The syntax to set the classpath is shown as:
C:> set CLASSPATH=%classpath
%;classpath1;classpath2.....

You can set multiple path entries that are separated by semi-colons.
To make this thing more understandable, let's put the "HelloWorld" class along with its
package "mypackage" under the "C:\mainpackage" directory. Thus the directory
structure for this package is shown as:

Now we have changed the location of the package from C:\mypackage\HelloWorld.java to


C:\mainpackage\mypackage\HelloWorld.java. Then the CLASSPATH needs to be changed to
point the new location of the package mypackage accordingly shown as:
set CLASSPATH = .;C:\mainpackage;
Java

Although in such condition, Java will look for java classes from the current directory instead
of the "C:\mainpackage" directory.

Access protection in packages:


Access
Discription
protection
The classes and members specified
No in the same package are accessible
modifier to
(default) all the classes inside the same
package.
The classes, methods and member
public variables under this specifier can be
accessed from anywhere.
The classes, methods and member
variables under this modifier are
protected accessible by all subclasses,
and accessible by code in same
package.
The methods and member variables
private
are accessible only inside the class.

Access to fields in Java at a Glance:


Access By public protected default private
The class itself Yes Yes Yes Yes
A subclass in same package Yes Yes Yes No
Non sub-class in the same
Yes Yes Yes No
package
A subclass in other package Yes Yes No No
Non subclass in other
Yes No No No
package

Package categories in Java:

Java supports two types of packages as shown below in the hierarchy structure:
Java

Build-In Packages in Core Java:


Java packages can be categorized in the hierarchy structure shown as:

Packages in the Java language begin with "java" or "javax" as we can found in both
hierarchy structure shown above. Note that, the package "java" also has subpackages in which
the package "awt" is further has a subpackage called "event" that is imported to access
classes and interfaces to handle the events fired on the awt-component in a program. Thus the
the expression to import the package is shown as"
import awt.event.*;
Lets understand these java packages shown in the table, from which you can access interfaces
and classes.
Package
Description
Name
java.lang It contains essential classes that represent primitive data types
(such as int & char)
as well as more complex classes, including numerics, strings,
Java

objects, compiler,
runtime, security, and threads. This is the only package that is
automatically imported
into every Java program.
This package provides classes to manage input and output
java.io streams to read data from
and write data to files, strings, and other sources.
It contains miscellaneous utility classes, including generic data
structures, bit sets, time,
java.util date, string manipulation, random number generation, system
properties, notification,
and enumeration of data structures.
It provides an integrated set of classes to manage user interface
components such as
java.awt
windows, dialog boxes, buttons, checkboxes, lists, menus,
scrollbars, and text fields.
It provides classes for network support, including URLs, TCP
java.net sockets, UDP sockets,
IP addresses, and a binary-to-text converter.
It enables the programmer to create applets through the Applet
class. It also provides
java.applet
several interfaces that connect an applet to its document and to
resources for playing audio.
java.nio This package handles New I/O framework for Java

java.math This package includes various mathematical operations.

java.security It is used for key generation, encryption and decryption.


It is used for hierarchy of packages for platform-independent
javax.swing
rich GUI components.
It provides classes to support connectivity from JDBC to access
java.sql
databases

Create Your Own Package :-


The package to which the source file belongs is specified with the keyword package at the top
left of the source file, before the code that defines the real classes in the package.
Suppose we have a source file called "HelloWorld.java" and we want to put this file in a
package "mypackage" then the following code is written as shown in the given example:
package mypackage;
class HelloWorld {
public static void main (String args[]) {
System.out.println("Hello World!");
Java

}
}

Before running this program make sure to do the following things:


1. Create a directory "mypackage" .
2. Save the source file as "HelloWorld.java" in the created directory.
3. Set the class path as set CLASSPATH = .;C:\;
4. Go to the "mypackage" directory and compile the program as
C:\mypackage>javac
HelloWorld.java
5. Run the program.

If you try to run this program, you will get the following exceptions (or error):

C:\mypackage>java HelloWorld
Exception in thread "main" java.lang.NoClassDefFoundError: HelloWorld
(wrong name: mypackage/HelloWorld)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.access$000(Unknown Source)

This is, because the class "HelloWorld" belongs to the package "mypackage". So If we want
to run it, we have to tell the JVM about its fully-qualified class name as
(mypackage.HelloWorld) instead of its plain class name (HelloWorld). Fully-qualified class
name is the name of the java class that includes its package name.

Now run the program as shown:


C:\mypackage>java
mypackage.HelloWorld
Hello World!
The ways to Compile the Package:
Compile in the same directory: If you have a hierarchy of packages to compilation then you
can compile the package without going to the subdirectories and specifying the complete
directory path with the class . Suppose, you have a hierarchy of packages as
"india.mycompany.mainpackage.mypackage" including the class "HelloWorld" then type
the following command shown as:
Java

C:\javac
C:\india\mycompany\mainpackage\mypackage\HelloWord.java

This command will reach to the last subdirectory and compile the class "HelloWorld".
Compile into the Different Directory: On the other hand, if you want to compile the same
package available in the hierarchy manner to another directory (location) then syntax is shown
as:
C:\javac -d <target_directory>
<complete_directorypath>
Suppose, you want to save the compiled package to the location "D:\myfolder" then type the
following command shown as:
C:\javac -d D:\myfolder C:\
india\mycompany\mainpackage\mypackage\HelloWord.java

This command puts the folder "india" along with its subfolders and the class file
"HelloWorld.class" to the new location as D:\myfolder.

How to import a package:-


There are two ways so that you can use the public classes stored in package.
Declaring the fully-qualified class name. For example,

mypackage.HelloWorld helloworld = new


mypackage.HelloWorld();

Using an "import" keyword: For example,

import world.*; // we can call any public classes


inside the mypackage package
Lets see an example importing the created package into the another program file.

package importpackage;

public class HelloWorld {


public void show(){
System.out.println("This is the function of the class HelloWorld!!");
}
}
Java

In this program the package "importpackage" is created under the "c:\nisha" directory that
will be imported into another program file to call the function of the class "HelloWorld".
Now make a program file named "CallPackage" under the "c:\nisha" directory importing
the package "importpackage".

import importpackage.*;
class CallPackage{
public static void main(String[] args){
HelloWorld h2=new HelloWorld();
h2.show();
}
}

Out of the program:


C:\nisha\importpackage>javac
*.java

C:\nisha\importpackage>cd..

C:\nisha>javac
CallPackage.java

C:\nisha>java CallPackage
This is the function of the class
HelloWorld!!
Make sure to the directory structure for this program shown as:

Create Subpackages:-
We can also put a package inside an another package. The packages that comes lower in the
naming hierarchy are called "subpackage" of the corresponding package higher in the
hierarchy i.e. the package that we are putting into another package is called "subpackage".
The naming convention defines how to create a unique package name, so that packages that
are widely used with unique namespaces. This allows packages to be easily managed. Suppose
we have a file called "HelloWorld.java". and want to store it in a subpackage "subpackage",
which stays inside package "importpackage". The "HelloWorld" class should look
something like this:
package importpackage.subpackage;
Java

public class HelloWorld


{
public void show()
{
System.out.println("This is the function of the class HelloWorld!!");
}
}

Now import the package "subpackage" in the class file "CallPackage" shown as:
import importpackage.subpackage.*;
class CallPackage{
public static void main(String[] args){
HelloWorld h2=new HelloWorld();
h2.show();
}
}

Out of the program:


C:\nisha>javac
C:\nisha\importpackage\subpackage\HelloWorld.java

C:\nisha\importpackage\subpackage>cd..

C:\nisha\importpackage>cd..

C:\nisha>javac CallPackage.java

C:\nisha>java CallPackage
This is the function of the class HelloWorld!!
Make sure to the directory structure for this program shown as:

13. Interface in Java


Java

In this section we will learn about Interface and Marker Interfaces in Java. This tutorial will
clarify your questions "What is marker Interface?" and "Why to use Marker Interface?"
and "difference between abstract class and the interface".

Interface
In general, interface is the way just to say something to a media by using another media. Let's
take the general life example. TV Remote is the interface because it is the medium to give the
command to a TV in order to change the channels or to ON/OFF the TV. Electric switch is also
the interface's example.
But in java programming language interface is nothing but the collection of methods with
empty implementations and constants variables ( variables with static and final declarations ).
All the methods in an interface are "public and abstract" by default. Since interfaces are
abstract in nature so they can not be directly instantiated. To define the methods of an interface
the keyword "implements" is used. Interfaces are similar to abstract classes but the major
difference between these two is that interface have all the methods abstract while in case of
abstract classes must have at least one abstract method. Interface combines the two
functionality (template and multiple inheritance) of C++ language into one (in itself).
Interface Definition
visibility mode interface interfaceName{
constant variable declarations
abstract method declarations
}
e.g.
public interface RacingCar{
public void startcar (int Obj);
public void changegear (int Obj);
public void incrrace (int Obj);
public void stopcar (int Obj);
}

Marker Interface
In java language programming, interfaces with no methods are known as marker interfaces.
Marker interfaces are Serializable, Clonable, SingleThreadModel, Event listener. Marker
Interfaces are implemented by the classes or their super classes in order to add some
functionality.
e.g. Suppose you want to persist (save) the state of an object then you have to implement the
Serializable interface otherwise the compiler will throw an error. To make more clearly
understand the concept of marker interface you should go through one more example.
Suppose the interface Clonable is neither implemented by a class named Myclass nor it's any
super class, then a call to the method clone() on Myclass's object will give an error. This
means, to add this functionality one should implement the Clonable interface. While the
Clonable is an empty interface but it provides an important functionality.
Java

Difference between Interfaces and abstract classes


Some important difference between Interface and abstract classes are given here
Abstract
Features
Interface Class
Methods An interface contains An abstract class must have
all the methods with at least one method with
empty implementation. empty implementation.
Variables The variables in Abstract classes may contain
interfaces are final and both instance as well as static
static. variables.
Multiple In java multiple Abstract classes does not
Inheritance inheritance is achieved provide this functionality.
by using the interface
(by implementing
more than one
interface at a time)
Additional If we add a method to In Abstract classes we can
Functions an interface then we add a method with default
will have to implement implementation and then we
this interface by any can use it by extending the
class.. abstract class.

14. Exception Handling


Exceptions:
Exception, that means exceptional errors. Actually exceptions are used for handling errors in
programs that occurs during the program execution. During the program execution if any error
occurs and you want to print your own message or the system message about the error then
you write the part of the program which generate the error in the try{} block and catch the
errors using catch() block. Exception turns the direction of normal flow of the program control
and send to the related catch() block. Error that occurs during the program execution generate
a specific object which has the information about the errors occurred in the program.
In the following example code you will see that how the exception handling can be done in
java program. This example reads two integer numbers for the variables a and b. If you enter
any other character except number ( 0 - 9 ) then the error is caught by
NumberFormatException object. After that ex.getMessage () prints the information about the
error occurring causes.

Code of the program :


Java

import java.io.*;

public class exceptionHandle{


public static void main(String[] args) throws Exception{
try{
int a, b;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
a = Integer.parseInt(in.readLine());
b = Integer.parseInt(in.readLine());
}
catch (NumberFormatException ex){
System.out.println(ex.getMessage() + " is not a numeric value.");
System.exit(0);
}
}
}

Output of this program:


C:\vinod\xml>javac
exceptionHandle.java

C:\vinod\xml>java
exceptionHandle

For input string: "" is not a


numeric value.

An exception is an event that occurs and interrupts the normal flow of instructions. That is
exceptions are objects that store the information about the occurrence of errors. When any
kind of error or unusual condition occurs, these exceptions are being thrown. Any exception
used to occur earlier always resulted in a program crash. However, some programming
languages like java have mechanisms for handling exceptions. This is known as catching
exception in Java. The exceptions that occur in the program can be caught using try and catch
block. Remember, the program will crash if the exception would not be caught. There are
three types of exceptions in Java. These are -:

1. Checked Exceptions
2. The error
3. Runtime exception

Error and Runtime exceptions are known as unchecked exceptions. This chapter covers how to
throw an exception and catch it. A detailed explanation on the types of exceptions and the
advantages of the exceptions.

Basic I/O:
In this section we will learn about basic input and out put operations in Java. Different kinds
Java

of sources and destinations are represented by a Stream like disk files, devices, memory arrays
etc. A Stream is a sequence of data. An Input Stream is used by the program to read data
from the source. Similarly, a program uses an Output stream to write data to a destination. It
also supports different kinds of data including simple bytes, primitive data types, objects etc.
We will learn about I/O Steams and how to use them.
Concurrency:
Concurrency is generally used to perform multiple tasks simultaneously. In this section we
will learn how to write applications to perform multitasking. There are two types of units of
execution process and threads. Thread is the most important unit in concurrent programming.
There are many processes and threads which are active in a computer system. However only
one threads executes at a time even in systems that only have a single execution core.
Regular expression
The set of strings which are based on common characteristics are shared by each string in the
set. Basically, Regular expressions are are a set of strings.

This regular expression as a Java string, becomes "\\\\". That is 4 backslashes to match a single
one. As in literal Java strings the backslash is an escape character. The literal string as a single
backslash is denoted by "\\". In this chapter we will learn to create a syntax for regular
expressions and how to use them.

15. Input and Output


Introduction
The Java I/O means Java Input/Output and is a part of java.io package. This package has a
InputStream and OutputStream. Java InputStream is for reading the stream, byte stream and
array of byte stream. It can be used for memory allocation. The OutputStream is used for
writing byte and array of bytes. Here, you will know several interfaces provided by the java.io
package as follows:

Interfaces and Descriptions:


DataInput This interface can be used for reading byte stream
and reconstructing the java primitive data types.
DataOutput This interface can be used for writing the byte
stream and converting data from the java primitive
data types.
Externalizable This is written in Serializable Stream. It save and
store it's contents.
FileFilter It can be used for Filtering the Pathnames.
FilenameFilter This interface used for Filter the Filenames.
ObjectInput This interface used for reading of objects and it
extends the DataInput interface.
ObjectInputValidation This is a Callback interface. It allows the
Java

validation of objects within a graph.


ObjectOutput This interface used for writing of objects and it
extends the DataOutput interface.
ObjectStreamConstants This interface used for Constants writing into
Serialization Objects Stream.
Serializable This interface implementing in the
java.io.Serializable interface.

Classes and Descriptions:


BufferedInputStream It used for creating an internal buffer array. It
supports the mark and reset methods.
BufferedOutputStream This class used for writes byte to output stream. It
implements a buffered output stream.
BufferedReader This class provides read text from character input
stream and buffering characters. It also reads
characters, arrays and lines.
BufferedWriter This class provides write text from character
output stream and buffering characters. It also
writes characters, arrays and lines.
ByteArrayInputStream It contains the internal buffer and read data from
the stream.
ByteArrayOutputStream This class used for data is written into byte array.
This is implement in output stream class.
CharArrayReader It used for char input stream and implements a
character buffer.
CharArrayWriter This class also implements a character buffer and
it uses an writer.
DataInputStream This class reads the primitive data types from the
input stream in a machine format.
DataOutputStream This class writes the primitive data types from the
output stream in machine format.
File This class shows a file and directory pathnames.
FileDescriptor This class uses for create a FileInputStream and
FileOutputStream.
FileInputStream It contains the input byte from a file and
implements an input stream.
FileOutputStream It uses for writing data to a file and also
implements an output stream.
FilePermission It provides the permission to access a file or
directory.
Java

FileReader This class used for reading characters file.


FileWriter This class used for writing characters files.
FilterInputStream This class overrides all methods of InputStream
and contains some other input stream.
FilterOutputStream This class overrides all methods of OutputStream
and contains some other output stream.
FilterReader It reads the data from the filtered character
stream.
FilterWriter It writes data from the filtered character stream.
InputStream This class represents an input stream of bytes.
InputStreamReader It reads bytes and decodes them into characters.
LineNumberReader This class has a line numbers
ObjectInputStream This class used for recover the object to serialize
previously.
ObjectInputStream.GetField This class access to president fields read form
input stream.
ObjectOutputStream This class used for write the primitive data types
and also write the object to read by the
ObjectInputStream.
ObjectOutputStream.GetField This class access to president fields write in to
ObjectOutput.
ObjectStreamClass Serialization's descriptor for classes.
ObjectStreamField This class describes the serializable field.
OutputStream This class represents an output stream of bytes.
OutputStreamWriter It writes bytes and decodes them into characters.
PipedInputStream In this class the data bytes are written into piped
output stream. This class also connected into a
piped output stream.
PipedOutputStream This class also communicates the piped input
stream into piped output stream. It creates
communication between both.
PipedReader It is a piped character-input stream.
PipedWriter It is a piped character-output stream.
PrintStream This class adds the functionality of another
output stream.
PrintWriter This class adds the functionality of another input
stream.
PushbackInputStream It also include the another function of input
stream. Such as: "push back" or "unread" one
byte.
Java

PushbackReader This is a character stream reader and reads the


data push back into the stream.
RandomAccessFile It supports both reading and writing to a random
access file.
Reader It used for reading character stream.
SequenceInputStream It represents the logical concatenation of other
input stream.
SerializablePermission This is a serializable permission class.
StreamTokenizer It takes an input stream and parse it into
"tokens" . The token to be allowed at the read
time.
StringReader This is a character string class. It has character
read source.
StringWriter This is also a character string class. It uses to
shows the output in the buffer.
Writer It uses for writing to character stream.

Exceptions for java.io package:


CharConversionException It provides detail message in the catch
block to associated with the
CharConversionException
EOFException This exception indicates the end of file.
When the file input stream to be end then
EOFException to be occuted.
FileNotFoundException When the open file's pathname does not
find then this exception to be occured.
InterruptedIOException When the I/O operations to interrupted
from any causes then it becomes.
InvalidClassException Any problems to be created with class,
when the Serializing runtime to be
detected.
InvalidObjectException When the de-serialized objects failed then
it occurs.
IOException When the I/O operations to be failed then it
occurs.
NotActiveException The Serialization or deserialization
operations are not active then it occurs.
NotSerializableException This exception when the instance is
required to a Serializable interface.
Java

ObjectStreamException This is a supper class of all exception class.


It used for specific to Object Stream
Classes.
OptionalDataException When the reading data operations to failed
then it these exception occurs. It is
belonging to the serialized object
StreamCorruptedException It thrown when the control information that
was read form an object stream vioaltes
internal consistency checks.
SyncFaieldException The sync operation is failed then
SyncFaieldException to be occure.
UnsupportedEncodingException The Character Encoding is not supported.
UTFDataFormatException A molformed UTF-8 has been read in a data
input stream, it implemented by data input
interface.
WriteAbortedException In this exception to be thrown by the
ObjectStreamException during a write
operating.
Read Text from Standard IO: Java provides the standard I/O facilities for reading text
through either the file or keyboard in command line. This program illustrates you how to use
standard input to read the user input..
In this section, you will see how the standard I/O is used to input any thing by the keyboard or
a file. This is done using the readLine() method which is the method of the BufferedReader
class.
BufferedReader :
The BufferedReader class is the subclass of the FilterReader class. BufferedReader class
maintains the buffer and buffer state. BufferedReader class supports the read() and readLine()
method for input text from a character-input stream. The buffer size may be specified but the
default buffer size is enough for most purposes because the default buffer size of 8192 chars
can be overridden by the creator of the stream.
In this program, as you can see that the instance variable in of the BufferedReader class
which reads a single line of text from the input stream.

Here is the code of the program :


import java.io.*;

public class ReadStandardIO{


public static void main(String[] args) throws IOException{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter text : ");
String str = in.readLine();
System.out.println("You entered String : ");
System.out.println(str);
Java

}
}

Filter Files in Java: The Filter File Java example code provides the following functionalities:
Filtering the files depending on the file extension provided by the user

User provides the file extension and then program lists all the matching files found

Program accepts directory name and file extension from user and displays the files present in
the directory.
Program begins with import statement java.io.*; package, which is required for any
input/output operations.

Classes Defined in the program:


OnlyExt
The constructor of the class takes file extension as parameter and then prefix it with "*." and
assign into the global variable ext. The OnlyExt class implements FilenameFilter interface, so
we have to implement the abstract method accept() defined in the FilenameFilter interface.
The accept() method tests if a specified file should be included in a file list.
FilterFiles:
The FilterFiles contains the public static void main(String args[]), which is the
entry point of our program. The program first accepts directory name and file extension from
the user and creates the object of OnlyExt class passing file extension as constructor
parameter.

Here is the code of the program :


import java.io.*;

class OnlyExt implements FilenameFilter{


String ext;

public OnlyExt(String ext){


this.ext="." + ext;
}

public boolean accept(File dir,String name){


return name.endsWith(ext);
}
}

public class FilterFiles{


public static void main(String args[]) throws IOException{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please enter the directory name : ");
String dir = in.readLine();
System.out.println("Please enter file type : ");
Java

String extn = in.readLine();


File f = new File(dir);
FilenameFilter ff = new OnlyExt(extn);
String s[] = f.list(ff);

for (int i = 0; i < s.length; i++)


{
System.out.println(s[i]);
}
}
}

Java read file line by line: In the section you will learn how to write java program to read file
line by line. We will use the DataInputStream class to Read text File Line by Line.
Class DataInputStream
A data input stream is use to read primitive Java data types from an underlying input stream in
a machine-independent way. An application uses a data output stream to write data that can
later be read by a data input stream.
Data input streams and data output streams represent Unicode strings in a format that is a
slight modification of UTF-8. (For more information, see X/Open Company Ltd., "File
System Safe UCS Transformation Format (FSS_UTF)", X/Open Preliminary Specification,
Document Number: P316. This information also appears in ISO/IEC 10646, Annex P.) Note
that in the following tables, the most significant bit appears in the far left-hand column.

BufferedReader
Read text from a character-input stream, buffering characters so as to provide for the efficient
reading of characters, arrays, and lines.
The buffer size may be specified, or the default size may be used. The default is large enough
for most purposes.
In general, each read request made of a Reader causes a corresponding read request to be
made of the underlying character or byte stream. It is therefore advisable to wrap a
BufferedReader around any Reader whose read() operations may be costly, such as
FileReaders and InputStreamReaders. For example,
BufferedReader in
= new BufferedReader(new FileReader("foo.in"));

will buffer the input from the specified file. Without buffering, each invocation of read() or
readLine() could cause bytes to be read from the file, converted into characters, and then
returned, which can be very inefficient.
Programs that use DataInputStreams for textual input can be localized by replacing each
DataInputStream with an appropriate BufferedReader.
Java

Here is the code of java program to Read text File Line by Line:
import java.io.*;
class FileRead
{
public static void main(String args[])
{
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("textfile.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}

Create File in Java: Whenever there need to be store data, you have to create a file into some
directory. In this program, we will see how to create a file. This example takes the file name
and text data for adding into the file.
For creating a new file File.createNewFile() method has been used. This method returns a
boolean value true if the file is created otherwise return false. If the mentioned file for the
specified directory is already exist then the createNewFile() method returns the false otherwise
the method creates the mentioned file and return true. The constructor of the FileWriter class
takes the file name which has to be buffered by the BufferedWriter stream. The write()
method of BufferedWriter class is used to create the file into specified directory.
Following code write data into new file:
out.write(read_the_Buffered_file_name);
Java

Following code creates the object of FileWriter and BufferedWriter:


FileWriter fstream = new FileWriter(file_name);
BufferedWriter out = new BufferedWriter(fstream);

Here is the code of program :


import java.io.*;

public class CreateFile{

public static void main(String[] args) throws IOException{


BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Please enter the file name to create : ");
String file_name = in.readLine();
File file = new File(file_name);
boolean exist = file.createNewFile();
if (!exist)
{
System.out.println("File already exists.");
System.exit(0);
}
else
{
FileWriter fstream = new FileWriter(file_name);
BufferedWriter out = new BufferedWriter(fstream);
out.write(in.readLine());
out.close();
System.out.println("File created successfully.");
}
}
}

Copying one file to another: This example illustrates how to copy contents from one file to
another file. This topic is related to the I/O (input/output) of java.io package.
In this example we are using File class of java.io package. The File class is an abstract
representation of file and directory pathnames. This class is an abstract, system-independent
view of hierarchical pathnames. An abstract pathname has two components:
1. An optional system-dependent prefix string,
such as a disk-drive specifier, "/" for the UNIX root directory, or "\\" for a Win32 UNC
pathname, and
2. A sequence of zero or more string names.
Java

Explanation
This program copies one file to another file. We will be declaring a function called copyfile
which copies the contents from one specified file to another specified file.
copyfile(String srFile, String dtFile)

16. Applets

Introduction
Applet is java program that can be embedded into HTML pages. Java applets runs on the java
enables web browsers such as mozila and internet explorer. Applet is designed to run remotely
on the client browser, so there are some restrictions on it. Applet can't access system resources
on the local computer. Applets are used to make the web site more dynamic and entertaining.
Advantages of Applet:
Applets are cross platform and can run on Windows, Mac OS and Linux platform
Applets can work all the version of Java Plugin
Applets runs in a sandbox, so the user does not need to trust the code, so it can work
without security approval
Applets are supported by most web browsers
Applets are cached in most web browsers, so will be quick to load when returning to a
web page
User can also have full access to the machine if user allows

Disadvantages of Java Applet:


Java plug-in is required to run applet
Java applet requires JVM so first time it takes significant startup time
If applet is not already cached in the machine, it will be downloaded from internet and
will take time
Its difficult to desing and build good user interface in applets compared to HTML
technology

Life Cycle of Applet: Applet runs in the browser and its lifecycle method are called by JVM
when it is loaded and destroyed. Here are the lifecycle methods of an Applet:

init(): This method is called to initialized an applet

start(): This method is called after the initialization of the applet.


stop(): This method can be called multiple times in the life cycle of an Applet.
Java

destroy(): This method is called only once in the life cycle of the applet when applet is
destroyed.
init () method: The life cycle of an applet begins when the applet is first loaded into the
browser and called the init() method. The init() method is called only one time in the life cycle
on an applet. The init() method is basically called to read the PARAM tag in the html file. The
init () method retrieve the passed parameter through the PARAM tag of html file using get
Parameter() method All the initialization such as initialization of variables and the objects like
image, sound file are loaded in the init () method .After the initialization of the init() method
user can interact with the Applet and mostly applet contains the init() method.

Start () method: The start method of an applet is called after the initialization method init().
This method may be called multiple times when the Applet needs to be started or restarted. For
Example if the user wants to return to the Applet, in this situation the start Method() of an
Applet will be called by the web browser and the user will be back on the applet. In the start
method user can interact within the applet.
Stop () method: The stop() method can be called multiple times in the life cycle of applet like
the start () method. Or should be called at least one time. There is only miner difference
between the start() method and stop () method. For example the stop() method is called by the
web browser on that time When the user leaves one applet to go another applet and the start()
method is called on that time when the user wants to go back into the first program or Applet.

destroy() method: The destroy() method is called only one time in the life cycle of Applet
like init() method. This method is called only on that time when the browser needs to Shut
down.
Creating First Applet Example: First of all we will know about the applet. An applet is a
program written in java programming language and embedded within HTML page. It runs on
the java enabled web browser such as Netscape navigator or Internet Explorer.
In this example you will see, how to write an applet program. Java source of applet is then
compiled into java class file and we specify the name of class in the applet tag of html page.
The java enabled browser loads class file of applet and run in its sandbox.
Here is the java code of program :
import java.applet.*;
import java.awt.*;

public class FirstApplet extends Applet{


public void paint(Graphics g){
g.drawString("Welcome in Java Applet.",40,20);
}
}

Here is the HTML code of the program:


Java

<HTML>
<HEAD>
</HEAD>
<BODY>
<APPLET ALIGN="CENTER"
CODE="FirstApplet.class"
WIDTH="800"
HEIGHT="500"></APPLET>
</BODY>
</HTML>
Passing Parameter in Java Applet: Java applet has the feature of retrieving the parameter
values passed from the html page. So, you can pass the parameters from your html page to the
applet embedded in your page. The param tag(<parma name="" value=""></param>) is used
to pass the parameters to an applet. For the illustration about the concept of applet and passing
parameter in applet, a example is given below.
In this example, we will see what has to be done in the applet code to retrieve the value from
parameters. Value of a parameter passed to an applet can be retrieved using getParameter()
function. E.g. code:
String strParameter = this.getParameter("Message");

Printing the value:


Then in the function paint (Graphics g), we prints the parameter value to test the value passed
from html page. Applet will display "Hello! Java Applet" if no parameter is passed to the
applet else it will display the value passed as parameter. In our case applet should display
"Welcome in Passing parameter in java applet example." message.
Here is the code for the Java Program :
import java.applet.*;
import java.awt.*;

public class appletParameter extends Applet {


private String strDefault = "Hello! Java Applet.";
public void paint(Graphics g) {
String strParameter = this.getParameter("Message");
if (strParameter == null)
strParameter = strDefault;
g.drawString(strParameter, 50, 25);
}
}

Here is the code for the html program :

<HTML>
<HEAD>
<TITLE>Passing Parameter in Java Applet</TITLE>
</HEAD>
<BODY>
Java

This is the applet:<P>


<APPLET code="appletParameter.class" width="800"
height="100">
<PARAM name="message" value="Welcome in Passing
parameter in java applet example.">
</APPLET>
</BODY>
</HTML>
There is the advantage that if need to change the output then you will have to change only the
value of the param tag in html file not in java code.

Compile the program :


javac appletParameter.java

Output after running the program :


To run the program using appletviewer, go to command prompt and type appletviewer
appletParameter.html Appletviewer will run the applet for you and and it should show output
like Welcome in Passing parameter in java applet example. Alternatively you can also run
this example from your favorite java enabled browser.

You might also like