Java Notes
Java Notes
The term Java actual refers to more than just a particular language like C or Pascal. Java
encompasses several parts, including :
1 A high level language ? the Java language is a high level one that at a glance
looks very similar to C and C++ but offers many unique features of its own.
2 Java bytecode - a compiler, such as Sun's javac, transforms the Java language
source code to bytecode that runs in the JVM.
3 Java Virtual Machine (JVM) ? a program, such as Sun's java, that runs on a
given platform and takes the bytecode programs as input and interprets them just
as if it were a physical processor executing machine code.
Sun provides a set of programming tools such as javac, java and others in a bundle that
it calls a Java Software Development Kit for each version of the language and for
different platforms such as Windows, Linux, etc.. Sun also provides a runtime bundle
with just the JVM when the programming tools are not needed.
Note that because of the open nature of Java (see below), any or all of these parts can be
replaced by non-Sun components. For example, just as many different languages can
create machine code for a given processor, compilers of other languages have been
created that output bytecode to run in the JVM. Similarly, many JVMs have been written
by groups outside of Sun.
In this book and web course, when we use the term Java we are referring to the the high
level language unless noted otherwise. Also, those packages that come with the SDK for
a given version will be referred to as comprising the core language for that version, as
distinguished from optional or third party packages
History of Java
Around 1990 James Gosling , Bill Joy and others at Sun Microsystems began developing
a language called Oak. The wanted it primarily to control microprocessors embedded in
consumer items such as cable set-top boxes,VCR's, toasters, and also for personal data
assistants (PDA).
To serve these goals, Oak needed to be:
4 Platform independent (since multiple manufacturers involved)
5 Extremely reliable
6 Compact.
However, as of 1993, interactive TV and PDA markets had failed to take off. Then the
Internet and Web explosion began, so Sun shifted the target market to Internet
applications and changed the name of the project to Java.
By 1994 Sun's HotJava browser appeared. Written in Java in only a few months, it
illustrated the power of applets, programs that run within a browser, and also the
capabilities of Java for speeding program development.
Riding along with the explosion of interest and publicity in the Internet, Java quickly
received widespread recognition and expectations grew for it to become the dominant
software for browser and consumer applications.
However, the early versions of Java did not possess the breadth and depth of capabilities
needed for client (i.e. consumer) applications. For example, the graphics in Java 1.0
seemed crude and clumsy compared to mature software developed with C and other
languages.
Applets became popular and remain common but don't dominate interactive or
multimedia displays on web pages. Many other "plug-in" types of programs also run
within the browser environment.
So Java has not succeeded at development of consumer applications. However, Java's
capabilities grew with the release of new and expanded versions (see below) and it
became a very popular language for development of enterprise, or middleware,
applications such as on line web stores, transactions processing, database interfaces, and
so forth.
Java has also become quite common on small platforms such as cell phones and PDAs.
Java is now used in several hundred cell phone models. Over 600 million JavaCards,
smart cards with additional features provided by Java, have been sold as of the summer of
2004.
Features
Here we list the basic features that make Java a powerful and popular programming
language:
7 Platform Independence
8 The Write-Once-Run-Anywhere ideal has not been achieved (tuning for
different platforms usually required), but closer than with other languages.
9 Object Oriented
10 Object oriented throughout - no coding outside of class definitions,
including main().
12 Compiler/Interpreter Combo
13 Code is compiled to bytecodes that are interpreted by a Java virtual
machines (JVM) .
14 This provides portability to any machine for which a virtual machine has
been written.
15 The two steps of compilation and interpretation allow for extensive code
checking and improved security.
16 Robust
17 Exception handling built-in, strong type checking (that is, all data must be
declared an explicit type), local variables must be initialized.
24 Security
25 No memory pointers
26 Programs runs inside the virtual machine sandbox.
27 Array index limit checking
28 Code pathologies reduced by
29 bytecode verifier - checks classes after loading
30 class loader - confines objects to unique namespaces. Prevents
loading a hacked "java.lang.SecurityManager" class, for
example.
31 security manager - determines what resources a class can access
such as reading and writing to the local disk.
32 Dynamic Binding
33 The linking of data and methods to where they are located, is done at run-
time.
34 New classes can be loaded while a program is running. Linking is done on
the fly.
35 Even if libraries are recompiled, there is no need to recompile code that
uses classes in those libraries.
This differs from C++, which uses static binding. This can result in fragile
classes for cases where linked code is changed and memory pointers then
point to the wrong addresses.
36 Good Performance
37 Interpretation of bytecodes slowed performance in early versions, but
advanced virtual machines with adaptive and just-in-time compilation and
other techniques now typically provide performance up to 50% to 100%
the speed of C++ programs.
38 Threading
39 Lightweight processes, called threads, can easily be spun off to perform
multiprocessing.
40 Can take advantage of multiprocessors where available
41 Great for multimedia displays.
42 Built-in Networking
43 Java was designed with networking in mind and comes with many classes
to develop sophisticated Internet communications.
Features such as eliminating memory pointers and by checking array limits greatly help
to remove program bugs. The garbage collector relieves programmers of the big job of
memory management. These and the other features can lead to a big speedup in program
development compared to C/C++ programming.
Java Version
Since its introduction, Sun has released a new version of the Java language every two
years or so. These new versions brought enhancements, new capabilities and fixes to
bugs. Below is a timeline of the different versions of the basic, or Standard Edition (SE),
of Java along with some of the new features that each one introduced. This edition
contains the core language packages (the name for code libraries in Java) and is aimed for
desktop programming.
44 1995: Version 1.0 of the Java Development Kit (JDK) was released for free by
Sun.
45 8 packages with 212 classes
46 Netscape 2.0-4.0 included Java 1.0.
47 Microsoft and other companies licensed Java.
73 EmbeddedJava - based on Java 1.1 for 32 bit system with about 512kb
each for ROM and RAM. Individual packages, classes and even methods
in the core language can be thrown out to make room.
74 PersonalJava - based on Java 1.1.8 for larger systems with 2MB ROM
and more than 1MB RAM.
First, start your editor. You can launch the Notepad editor from the Start menu by
selecting Programs > Accessories > Notepad. In a new document, type in the following
code:
/**
* The HelloWorldApp class implements an application that
* simply prints "Hello World!" to standard output.
*/
class HelloWorldApp {
public static void main(String[] args) {
System.out.println("Hello World!"); // Display the string.
}
}
Save the code in a file with the name HelloWorldApp.java. To do this in Notepad, first
choose the File > Save As menu item. Then, in the Save As dialog box:
Using the Save in combo box, specify the folder (directory) where you'll save your
file. In this example, the directory is java on the C drive.
In the File name text field, type "HelloWorldApp.java", including the quotation
marks.
From the Save as type combo box, choose Text Documents (*.txt).
In the Encoding combo box, leave the encoding as ANSI
Java defines eight simple types of data: byte, short, int, long,
char, float, double, and Boolean .These can be put in four groups
Integer:
This groups include byte,short,int, and long which are for whole
valued signed numbers.
Floating:
Characters:
Boolean:
Variables
The variable is the basic unit of starage in a java program.A
variable is defined by the combination of an identifier, a type ,
and an optional initilizer.
Declaring Variables
Syntax
Datatype identifier1=value,identifier2=value,………;
Eg:
int a,b,c;
double pi=3.14159;
Operators
Java provides a rich operator environment.Most of the operators
can be divided into the foolowing four groups
arithmetic,bitwise,relational, and logical.Java also defines some
additional operators that handle certain special sitautions
Arithmetic Operators
Operator Result
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
++ Increment
+= Addition assignment
-= Subtration assigment
*= Multiplication assigment
/= Division assignment
%= Modulus assignment
-- Decrement
Bitwise Operators
Relational Operators
Operator Result
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equl to
Logical Operators
Assignment Opreator
Syntax
Variable=value/expression;
Eg
int a,b,c;
a=10;
b=20;
c=a+b;
Control Statements
A programming language uses control statements to cause the flow
of execution and branch based on changes to the state of a
program.They are
a. if
if statement control the flow of execution according
to a condition
Syntax
if(condition)
{
Statement block;
}
b.if …….. else
Syntax
If(Condition)
{
true block statement;
}
else
{
false block statement;
}
c. switch statement
Syntax
Switch(expression/value)
{
Case value1:
Statement block1;
Case value2:
Statement block2;
.
.
.
.
.
Case valuen:
Statement blockn;
}
2. Looping Statements
The looping statements repeats the statement block until the condtion become false
Java supports three types of looping satements they are.
a. while loop
The while loop repeats a statement or block while its controlling expression is true.
Syntax
While (condition)
{
Statement block;
b. do…while
The do….while loop executes its body at least once , because its conditional
expression is at the buttom of the loop.So do….while loop is called exit control
statement.
Syntax
do
{
Statement block;
} while(condition);
c. for
The for loop is also called entry controlled loop statement
Syntax
for(initilization;condition;iteration)
{
Statement block;
}
For loop execute its statement block until the condtion become false.
Array
An array is a group of values that have a common variable name and identified each value by a
number called array
Subscript or array index.Arrays of any type can be created and may have one or more
dimensions.
Syntax
eg
Multidimensional array
In Java, multidimensional arrays are actually arrays of arrays.To declare a multidimensional array
variable,specify each additional index using another set of square brackets
Syntax
Eg
String Handling
Strings as built in objects allows java to provide a full complement of features that make string
handling convenient.For example java has methods to compare two strings ,search for a
substring ,concatenate two strings ,and change the case of letters with in a string. When you
create a string object , you are creating a string that cannot be cahnged.That is once a string
object has been created , you cannot change the characters that comprise that string
Character Extraction
The String class provides a number of ways in which characters can be extracted from a String
object.
charAt()
To extract a single character from a String, you can refer directly to an individual character via the
charAt() method
Syntax
charAt(int where)
eg
char ch;
ch=”abc”.charAt(1)
String Comparison
The string class includes several methods that compare strings or substrings with in strings.
Syntax
Here, str is the String object being compared with the invoking String object.It returns true if the
strings conatin the same characters in the same order, and false otherwise.The comparision is
case sensitive
Syntax
Here , str is the String object beign compared with the invoking String object.
CompareTo()
For sorting applications, you need to know is less than, equal to , or greater than the next.A string
is less than another if it comes before the other in dictionary order. A string is greater than
another if it comes after the other in dictionary order.The string method comareTo() servers this
purpose.
Syntax
Here, str is the String being compared with the invoking String.
Value Meaning
The method toLowerCase() converts all the characters in a string from uppercase to
lowercase.The toUpperCase() method converts all the characters in a string from lowercase to
uppercase.
Syntax
String toLowerCase()
String toUpperCase()
Reverse
You can reverse the characters within a string buffer object using reverse()
StringBuffer reverse()
Exception Handling
A java exception is an object that describes an exceptional condition that has occurred in a piece
of code
When an execeptional condition arises , an object representing that exception is created and
thrown in the method that caused the error.Java exception handling is managed via five keywords
try,catch,throw,throws and finally.Program statements that you want to moniter for exceptions are
conatined within a try block.If an exception occurs within the try block, it is thrown.Your code can
catch this exception using catch and handle it in some ratinonal manner.System generated
exceptions are automatically thrown by the java run time system.To manually throw an
exception , use the keyword throw.Any exception that is thrown out of a method must be specified
as such by a throws clause.
Syntax
try
{
.
.
.
.
.
finally
{
Sometimes, a program may compile successfully creating the .class file but may not run properly.
Such programs may produce wrong results due to wrong logic or may terminate due to errors such as
stack overflow. Most common run-time errors are: » Dividing an integer by zero
* Accessing an element that is out of the bounds of an array » Trying to store a
value into an array of an incompatible class or type
* Trying to cast an instance of a class to one of its subclasses
* Passing a parameter that is not in a valid range or value for a method
* Trying to illegally change the state of a thread
* Attempting to use a negative size for an array
* Using a null object reference as a legitimate object reference to access a method or a variable
* Converting invalid string to a number
* Accessing a character that is out of bounds of a string
* And many more
Thread
Java language provides buit in support for multithreaded programming . A multithreaded program
contains two or more parts that contains two or more parts that can run concerrently.Each part of
such a program is called thread, and each thread defines a seprate path of execution.So
mutithreading is a specilized form of multitasking.
When a java program starts up , one thread begings running immediately.This is usally called the
main main thread of your program, because it is the one that is executed when your program
begins
The thread class defines several methods that help manage threads. They are
class classname
{
member variable declaration;
member function declaration;
};
Syntax
classname objectvariable;
Objectvariable.classmember
The member functions can be defined in the class and can access outside of the
class.
Syntax for function defanition
Syntax
Classobject.functionname();
Constructor
Constructor is a special member function who’s task is to initilize obejct of a
class.A Constructor name is same as class name.Constructor does not not
support return type and they are two types they are
1. Parametarized constructor
2. Default constructor
Parametrarized Constructor
The constructor which receive value by using parameter variable are called
parametarized constructor
Syntax
Default construtor
Construtor which does not recive value from calling section is called default
constructor
Classname()
{
construtor body;
}
Inheritance
Single Inheritance
Multiple Inheritance
Hierarchical Inheritance
Multilevel Inheritance
Defining a subclass
Class subclassname
{
variables declaration;
methods declaration;
}
The keyword extends signifies that the properties of the superclassname are
extended to the subclassname.The subclass will now contain its own variables
and methods as well those of the superclass.This kind of situation occurs when
we want to add some more properties to an existing class without actually
modifing it.
Defining a superclass
The keyword extends signifies that the properties of the superclassname are
extended to the subclassname.The subclass will now contain its own variables
and methods as well those of the superclass.This kind of situation occurs when
we want to add some more properties to an existing class without actually
modifing it.
Intrefaces
Interface interfacename
{
variable declartion;
methods declartion;
}
Extending Interfaces
Syntax
Implementing Interfaces
Syntax
Syntax