Unit - I
Unit - I
Java Features
Java is a high level language looks much similar to C, C++ but it offers many
unique features that are not available in most of modern programming language.
Java language has the following features.
Java compiler converts the source code into intermediate byte code instructions
.Java Interpreter converts these bytes codes into machine executable statements.
Thus we can say java is both compiled and interpreted language. The two steps of
compilation and interpretation allow for extensive code checking and improved
security
Platform Independence
1
Java programs are capable of running on all platforms hence java programs
possess Write-Once-Run-Anywhere feature
Object Oriented
Java is purely an object oriented language. In Java no coding outside of class
definitions is allowed, including the main() function. Java supports an extensive
class library available in the core language packages.
Robust
Java is a robust language. It provides the following facilities to ensure reliable
code
• Built in Exception Handling
• Strong type checking both at compile and runtime.
• Local variables must be initialized
Security
Java is a highly secured language. Java programs will run only within the Java
Virtual Machine (JVM) sandbox thus threats from malicious programs is
minimized. Java does not support pointers hence direct memory access is not
allowed. Java supports a built in security manager that determines what resources
a class can access such as reading and writing to the local disk.
Automatic Memory Management
Dynamic Binding
Java is a dynamic language. The linking of data and methods occurs only at run
time. In java new classes can be loaded even when the program is on execution.
High Performance
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.
Multithreaded
In java it possible to write programs to handle multiple tasks simultaneously. To
write such programs you have to create light weight processes called “Threads” in
java. The threads thus created can be executed simultaneously. Multithreaded
programs are useful when you write programs for networking and multimedia.
2
Java Environment
JAVA COMPILER
BYTE CODE
JAVA INTERPRETOR
MACHINE CODE
Execution Process
The byte code produced by the java compiler for the JVM is common to all
platforms hence byte code is platform independent.
Writing java source code is similar to writing a source code in C++ but with some
variations. Writing Java source code is dealt in detail in subsequent chapters. Now
let’s start our discussion by writing a simple java program.The following is a
simple java program. The source code is written in the file named “Welcome.java”
3
class Welcome
{
public static void main(String args[])
{
// The following line is used to display a line of text
System.out.println(“Welcome to Java world “);
}
}
To compile this program you have to use the “javac” compiler. The syntax to
compile is
javac filename.java
javac welcome.java in the command prompt. This will create a class called
“welcome.class” which contains the byte code representation of the program.
To run the java program you have to use the java interpretor. The syntax to run
is
java classname
• The First line of this program has the class declaration, as mentioned earlier
every code written in java should be kept inside a class definition.
• The third line declares the main() method in java. The main() method in
java should be declared public and static .Usually the return type of the
main method is void.
• In java main() method should be declared public because main() method
should be made accessible to all other classes
• main() method is declared static because the main() method belongs to the
class not to a specific object
• System.out.println() is a statement used to display some text to the user. It
is similar to cout statement in C++.
4
Example 1:
class sum
{
public static void main(String args[])
{
int i=10,j=25;
k=i+j;
System.out.println(“THE SUM IS “+k);
}
}
In this example you have declared two integer variables i and j .The + operator
used in the System.out.println() is concatenation operator.
Introduction
But however due to the sudden explosion of Internet and similar technologies,
Sun Microsystems changed their project objectives and renamed the Oak
language into Java. In 1994 the project team developed a web browser called
“HotJava” capable of locating and running applets, a java program that can run on
a web browser.
The earlier versions of java were not so powerful but now Java has became a
common language to develop applications like on line web stores, transactions
processing, database interfaces etc., 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. This chapter explores the various fundamental
programming concepts of Java.
5
Java Tokens
• Keywords
• Identifiers
• Literals
• Operators
Keywords
The list is of keywords available in java are given below. Every keyword will
perform a specific operation in java. As mentioned in chapter 1 keywords cannot
be redefined by a programmer; further keywords cannot be used as identifier
name.
6
Identifiers
Literals
Operators
Java is a language that is rich in operators. The list of operators supported in java
is given below.
Arithmetic Operators
+ Additive operator (also used for String concatenation)
7
- Subtraction operator
* Multiplication operator
/ Division operator
% Remainder operator
Unary Operators
+ Unary plus operator; indicates positive value (numbers are positive
without this, however)
- Unary minus operator; negates an expression
++ Increment operator; increments a value by 1
-- Decrement operator; decrements a value by 1
! Logical compliment operator; inverts the value of a boolean
Conditional Operators
&& Conditional-AND
|| Conditional-OR
?: Ternary (shorthand for if-then-else statement)
Operator Precedence
Operators Precedence
8
postfix expr++ expr--
multiplicative */%
additive +-
equality == !=
bitwise exclusive OR ^
bitwise inclusive OR |
logical OR ||
ternary ?:
Expressions
9
variable=expression;
For Example
Data Types
• boolean
• byte
• short
• int
• long
• float
10
float to short) the fractional part is truncated and the conversion is done
modulo the length of the smaller type.
• double
8 bytes IEEE 754. Covers a range from 4.94065645841246544e-324d to
1.79769313486231570e+308d (positive or negative).
• char
Variables Declaration
Constants
Constants refer to values that do not change during the execution of the program.
Examples for constants are
Apart from these types of constants java also supports backslash character
constants
\b Backspace
\f Form feed
\n New Line
\r Carriage return
11
\t Horizontal tab
\\ Backslash
Note:
Java provides classes to represent simple data types like int, float etc., as class. That is
these classes warp the simple types to class types. These classes are called Wrapper
classes. Every simple data type in Java will have its corresponding wrapper class.
Thus using wrapper classes you can convert the string to the corresponding
simpler type. The signature for the Integer wrapper class is
For example
• Integer.parseInt(“10”)
will convert the string “10” to integer 10. The Integer wrapper class has a static
method called parseInt to perform this job. Similarly the signature of the Double
wrapper class is
For example
• Double.parseDouble(153.18)
12
will convert the string “153.18” to double 153.18. The Double wrapper class has a
static method called parseDouble to perform this job. Similar methods are
available for all the simple types.
The command line arguments passed to program are stored in the String array
args[] . The first element is referenced as args[0] , the next element as args[1]
and so on.
Command line arguments are supplied to the program when you run the program.
For example when you run the program named “hello.java”
Example 7:
The following example accepts two command line arguments and computes the
sum of two numbers.
class sum
{
public static void main(String args[])
{
double i,j,s;
i=Double.parseDouble(args[0]);
j=Double.parseDouble(args[1]);
s=i+j;
System.out.println("The sum is "+s);
}}
13
Example 8:
The following example accepts a number ‘n’ as command line argument and
generates ‘n’ Fibonacci numbers.
class fib
{
public static void main(String args[])
{
int n;
int a=0,b=1,c;
n=Integer.parseInt(args[0]);
for(int i=0;i<n;i++)
{
c=a+b;
System.out.println("The next number is "+c);
a=b;
b=c;
}
}
}
14
Note:
The length of the command line arguments can be found using the variable length. For
example args.length
Example 9:
class count
{
public static void main(String args[])
{
int n;
n=args.length;
System.out.println("The count is "+n);
}
}
15
Output of the Program
The count is 3
Objects
Objects are the run time instance of a class. Classes describe objects. Many
objects can be instantiated from one class. Objects of different classes can be
created, used, and destroyed in the course of executing a program.
Objects in java are created using the “new” operator. For example to create an
object for the GUI class we follow the given syntax.
OR
A class can contain variables. The variables added to the class are called instance
variables. Variables are declared in the java classes as mentioned below.
class product
{
int prod_id;
String prod_name;
double price;
}
Methods in Java determine the messages an object can receive. Methods in Java
can be created only as part of a class. A method can be called only for an object,
You call a method for an object by naming the object followed by a period (dot),
followed by the name of the method and its argument list, for example:
16
objectName.methodName(arg1, arg2, arg3)
The signature of a method comprises the method name and parameter list. The
combined name and parameter list for each method in a class must be unique.
The Syntax to declare a method in java is
//method body
• Return Type: The return type is either a valid Java type (primitive or class)
or void if no value is returned. If the method declares a return type, every
exit path out of the method must have a return statement.
• Method Name: The method name must be a valid Java identifier
• Parameter List: The parentheses following the method name contain zero
or more type/identifier pairs that make up the parameter list. Each
parameter is separated by a comma. Also, there can be zero parameters.
There are a number of optional modifiers that you can use when declaring a
method. They are listed in the following table:
Modifier Description
17
The method requires that a monitor (lock) be obtained
synchronized
by calling code before the method is executed.
Now, consider the product class created previously, we can add two methods
getDetails() and displayDetails() to the class.
class product
{
int prod_id;
double price;
void getDetails(int a,String b,double c)
{
prod_id=a;
price=c;
}
void displayDetails()
{
System.out.println(“Product id is “+prod_id);
System.out.println(“Price is “+price);
}
}
Example 1:
class Calculator
int n1,n2,res;
n1=x1;
n2=x2;
18
void add()
res=n1+n2;
void sub()
res=n1-n2;
int mul()
res=n1*n2;
return res;
double div()
return n1/n2;
class Mainprg
cal.setData(20,10);
19
cal.add();
cal.sub();
int y=cal.mul();
double d=cal.div();
The Sum is : 30
The Difference is : 10
Constructors
Constructors are special type of methods that are invoked when we create objects
for the classes. Constructers will have the same name as that of the class.
Constructors and methods differ in two important aspects of the signatures. They
are
• Modifiers
• Return types
Like methods, constructors can have any of the access modifiers: public,
protected, private, or none (often called friendly). However constructors cannot be
made abstract, final, native, static, or synchronized.
20
Methods can have any valid return type, or no return type, in which case the
return type is given as void. Constructors cannot take any return type, even void.
Example 2:
class Calculator
int n1,n2,res;
n1=x1;
n2=x2;
void add()
res=n1+n2;
void sub()
res=n1-n2;
int mul()
21
res=n1*n2;
return res;
double div()
return n1/n2;
class Mainprg
cal.sub();
int y=cal.mul();
double d=cal.div();
The Sum is : 30
The Difference is : 10
22
Access Specifiers
An access specifier in java determines which data member, which method can be
used by other classes. Java supports three access specifiers and a default access
specifier. Access specifiers are also known as access modifiers. The three access
specifiers supported in Java are
Only objects of the same class can have access rights to a method or data
member declared as private. A method or a data member can be declared as
private by prefixing it with the keyword private. For example
//method body
A data member or a method declared as public can be accessed by all classes and
their objects. To declare a data member or a method as public prefix the
declaration with the keyword public. For example
//method body
23
Data members, methods that are declared protected are accessible by that class
and the inherited subclasses. Methods and variables can be declared as protected
by prefixing the declaration with the protected keyword.
//method body
Default Access
Method Overloading
Example 3:
class numbers
24
void sum(int x,int y)
int z=x+y;
int r=x+y+z;
class test
25
Output of the Program
In this program the method sum is overloaded. From the main method when we
call the sum method the corresponding the overloaded version of the sum method
is called.
Constructer Overloading
Example 4:
class dimension
int x1,y1;
x1=0;
y1=0;
26
}
dimension(int a)
x1=a;
y1=0;
dimension(int a,int b)
x1=a;
y1=b;
void display()
System.out.println(“ x1 is :“+x1);
System.out.println(“ y1 is :“+y1);
class Mainprg
d1.display();
27
d2.display();
d3.display();
x1 is : 10
y1 is : 50
x1 is : 10
y1 is : 0
x1 is : 0
Static Data Members
y1 is : 0
Each object of a given class has its own copy of all the data defined by the class.
Sometimes it is desirable for all the objects of a particular class to share data. In
Java this can be achieved by defining the corresponding class members as static
using the keyword static. Since static variables are common all the instances of
the class, static variables can also be called as class variables.
• for a static data member there will be only one copy of the class member
shared by all objects of the class.
• A static data member is like a global variable, but has class-level scope.
static int x;
Static Methods
Like static variables , static methods are called without the object. The differences
between a static methods and non-static methods are as follows.
28
• A static method can access only static data and can call only other static
methods. A non-static member function can access all of the above
including the static data member.
• A static method can be called, even when a class is not instantiated, a non-
static member function can be called only after instantiating the class as an
object.
• A static method cannot have access to the 'this' keyword.
• A static method cannot have access to the ‘super’ keyword.
Example 5:
class test
k++;
return k;
j--;
return j;
class static_test
29
{
int a=static_test.increment(10);
int b=static_test.decrement(20);
Incremented Value is : 11
Decremented Value is : 19
In Java class libraries many static methods are found. For example in java.lang
package, we have a class called “Math” all the methods declared in the Math class
are static.
Example 6:
This program makes use of some static methods available in Math class.
class Math_test
System.out.println(“Sin 30 is “+Math.sin(30));
30
System.out.println(“Log value for 88.87 is “+Math.log(88.87));
Sin 30 is -0.9880316240928618
31
In keyword extends is used to implement inheritance in Java. In Java the
following forms of class inheritance is supported.
• Single Inheritance
• Multilevel Inheritance
• Hierarchical Inheritance.
Example 7:
class rectangle
int l;
int b;
rectangle(int x,int y)
l=x;
b=y;
void rect_area()
32
class cube extends rectangle
int h;
super(x,y);
h=z;
void cube_volume()
class Mainprg
c.rect_area();
c.cube_area();
33
Volume of the Cube is 6000
Super Keyword
Java uses a unique keyword called “super” to call the super class constructers. In
the previous example we have used super keyword to pass parameters to the
super class constructer from the sub class constructer. The following is the syntax
of super keyword
super() (or)
super(parameter list)
Multilevel Inheritance
class super1
------
------
------
34
------
------
------
Example 8:
//Super Class
class data1
int a;
data1(int x)
a=x;
//Sub Class1
35
{
int b;
data2(int x,int y)
super(x);
b=y;
//Sub Class2
int c;
super(x,y);
c=z;
void compute()
//Main Program
class Mainclass
36
public static void main(String args[])
d.compute();
Method Overriding
Example 9:
class Circle
{
double radius;
Circle(double r)
{
radius =r;
}
double getArea()
{
return Math.PI*radius*radius;
}
}
class Cylinder extends Circle
{
double length;
37
Cylinder(double radius, double l)
{
super(radius);
length=l;
}
double getArea()
{
return 2* Math.PI*radius*radius +2*Math.PI*radius*length;
}
}
class Areaprg
double res;
res=cy.getArea();
When the overriden method getArea() is invoked for an object of the Cylinder
class, the new overridden version of the method is called and not the old
definition from the superclass Circle.
38
However, if we want to find the area of both circle and cylinder then we have to
instantiate both the classes and invoke the getArea() method.
c.getArea();
c.getArea();
We have already learnt the usage of super keyword in invoking the super class
constructer. Super keyword can also be used to call super class method
overridden by the subclass method. The previous program is modified with the
help of super keyword.
Example 10:
class Circle
{
double radius;
Circle(double r)
{
radius =r;
}
double getArea()
{
return Math.PI*radius*radius;
}
}
class Cylinder extends Circle
39
{
double length;
Cylinder(double radius, double l)
{
super(radius);
length=l;
}
double getArea()
{
return 2* super.getArea() +2*Math.PI*radius*length;
}
}
class Areaprg
double res;
res=c.getArea();
res=cy.getArea();
40
Example 11:
The Coding given below illustrates the use of super keyword to refer superclass
variables.
class data1
int a;
data1(int x)
a=x;
//Sub Class1
int b;
data2(int x,int y)
super(x);
b=y;
void display()
System.out.println(“Value of a is “+super.a);
System.out.println(“Value of b is “+b);
41
}
class Mainprg
d.display();
Value of a is 10
Value of b is 20
Abstract methods are those that will have only method declaration without any
implementation. Hence we can say abstract methods are incomplete methods. A
42
method in java can be declared as abstract by prefixing its declaration with the
keyword abstract. For example
The implementations for these abstract methods are provided by overriding the
abstract method using a subclass.
Abstract class is a class that is declared as abstract. An abstract class will have
one or more abstract methods. Abstract classes cannot be instantiated but it can
be inherited by other subclasses. These subclasses will provide the
implementation of all the abstract methods present in the parent class however, if
not, the corresponding subclass must be declared abstract. Here is an example of
a abstract class and its corresponding subclass.
Example 12:
int l;
Shape()
l=10;
int b;
43
Rect()
b=10;
r.area();
Java supports an important keyword called Final. The keyword Final is used in
three different context. Final keyword can be used along with
• Variables
• Methods
• Classes
44
Final keyword when used with a variable, it becomes a constant. To declare a
variable as a “Final” prefix the keyword Final along with the variable declaration.
For example
When a method declaration is prefixed with the “Final” keyword the method
cannot be overridden by the subclass method. Thus method overriding can be
prevented. For example
//body of th method
When a class is declared as “Final” then the class cannot be subclassed. Hence it
prevents inheritance. For example
Note:
A Final class can inherit other classes. For example the statement
is perfectly valid.
45
Finalizer Methods
Before an object is garbage collected, the runtime system calls it’s finalize ()
method. The purpose of finalize () method is to release system resources before
the object gets garbage collected. The signature of finalize method is given below.
46