Professional Documents
Culture Documents
1. History of java:
The concept of developing java programming language was proposed by James Gosling,
Patrick Naughton and Mike Sheridan, the member of green project, at sun microsystem in 1991.This
language was initially called “Oak” but more people contributed to the design and evolution of this
language. The primary motivation for the development of this language was the need for platform
independent (i.e. architecture neutral) language that could be used to produce code that would run
different environments. Java derives much of its character from c and c++.
2. Introduction to Java:
Java is one of the most widely used object oriented programming language which is used
from software development to web development. It is purely object-oriented programming language.
The two main components of java platform are Java API, which is library of java command lines and
the JVM (Java Virtual Machines) that interprets the java code into machine code.
3. Features of Java:
Simple: It was designed to be easy to use and learn. In Java, there are a small number of
clearly defined ways to perform a given task.
Object-oriented: It is purely object-oriented programming language. Everything is defined
inside the class in the java. Even the main method is defined inside the class. It deals with
class and object. Class is a user defined datatype which contains entire set of data and code
(method) to manipulate the data. It is the collection of objects of similar type. Objects are the
basic runtime entities in object oriented system. It is an instance of class programming
problem is analyzed in terms of object and nature of communication between them. When a
program is executed, object interacts with each other by sending messages without knowing
details of their data or code.
Platform independent (Architecture neutral): It is platform independent programming
language. It has ability to run the same program on different system and easily move from
one computer to another computer. The java compiler generates a bytecode, which is
machine independent and can run on any environment (or platform) that contains the Java
Virtual Machine (JVM). JVM is an interpreter for bytecode.
Highly secure: Java is highly secured programming language. Every java program is run
within JVM which prevents the program from generating side effects outside the system. In
java bytecode verifier examines the bytecode to ensure that they are valid and do not affect
the system. Various access restriction (such as private, public) are enforced in java which
provides security.
Compiled and Interpreted: It is both compiled and interpreted language. The compiler
generates a byte code from java source code. The byte code is machine independent code
which is able to run on any machine that has JVM. JVM interprets the bytecode and
generates machine code that can be directly executed by machine which is running the java
program.
Java is highly case sensitive language.
Programming in Java Lecture Notes Chapter 1
Robust: It means reliable. Java checks the code at compile time to find out errors early and
also checks the code at run-time. Java is robust because it protects our computer from bad
program, provides portability and automatic memory management and garbage collection.
4. Implementation of java programs:
Creating a java program (source code): Type the java code using editor
such as notepad, netbeans, eclipse, etc. and then save it on a secondary
storage device with .java extension.
Compiling a java program into bytecodes: Use javac command to
compile a program. The compiler converts the java source code into
bytecodes. The bytecodes are platform independent and hence are portable.
The bytecodes are .class files.
Loading a program into memory: The class loader loads the .class files
from disk to primary memory before it executes.
Bytecode verification and execution: The bytecode verifier examines the
bytecodes and then JVM interprets the bytecode and generates machine code
which runs in specific machine.
Example:
public class simple
{
public static void main(String args[]) {
System.out.println(“hello world”);
w o r ld ”)
}
}
To run this program, we need to save it as simple.java and compile it as below; javac
simple.java
It generates simple.class (bytecode) file. To interpret this we use, java simple
Finally, this program gives the output
hello world
Characters: The datatype that is used to store characters is „char‟ which is 16-bit type.
Boolean: Boolean is simple type & it is represented by datatype ”Boolean”. It contains only
two possible values true or false.
6. Variables:
Variables are the name of memory space used to store values during program execution. A
variable is defined by a combination of a data type, an identifier (variable name) and an optional
initializer that contains value. It‟s syntax is,
datatype variable=value;
To declare more than one variable of the specified type, we can use a comma.
Example:
Int a; //declaration of variable a
Int b=2;c=3; //initialization of variable b & c with values 2 and 3 respectively
Dynamic initialization of variable: Dynamic initialization of variable means that we can initialize
the variables using expression. The value of the dynamic variable changes during compile time if the
values in the expression changes.
WAP that demonstrate the concept of dynamic initialization of variables
class MainClass {
public static void main(String args[]) {
double a = 3.0, b = 4.0;
// c is dynamically initialized
double c = Math.sqrt(a * a + b * b);
System.out.println("Hypotenuse is " + c);
}
}
This program consists of three local variables a, b and c. The first two a and b are initialized by
constants. However, c is initialized dynamically to the result of the expression calculated by the sqrt
function defined inside Math class.
7. Operators:
Basic arithmetic operators: Basic arithmetic operators includes addition (+), subtraction (-),
multiplication (*), division (/). These can be applied to both integer & floating point type.
Modulus operator: Modulus operator returns remainder of a division operator. It can be applied
to both integer & floating point type.
Arithmetic assignment operator: Arithmetic assignment operator can be combined with an
assignment operator which are called arithmetic assignment operator. It includes addition
assignment (+=), subtraction assignment (- =), multiplication assignment (* =), division
assignment (/ =), modulus assignment (% =).
Increment & decrement: The ++ and –are increment and decrement operators. The increment
operator increases its operand by one and decrement operator decreases its operand by one.
Boolean Logical Operators: The Boolean logical operators operate only on Boolean operands.
All of the binary logical operators combine two Boolean values to form a resultant Boolean
value.
& Logical AND
| Logical OR
Programming in Java Lecture Notes Chapter 1
8. Array
An array is a group of contiguous or related data items that share a common name. It stores a
collection of values of same type.
Obtaining an array is a two-step process:
I. We must declare an array variable of the desired type as:
datatype arrayvariablename[];
or
datatype[] arrayvariablename;
eg: int a[];
or
int[] a;
II. We must allocate the memory that will hold the array, using new operator and assign it to the
array variable as:
arrayvariablename = new type[size];
eg; a=new int[10];
The array declaration can also be done in a single step as:
datatype arrayvariablename[] = new datatype[size];
The elements in the array allocated by new will automatically be initialized to zero. Once we
have allocated an array, we can access a specific element in the array by specifying its index
within the square brackets. All the indexes start at zero.
Example:
class Array {
public static void main(String args[]) {
int month_days[];
month_days = new int[12];
month_days[0] = 31;
month_days[1] = 28;
Programming in Java Lecture Notes Chapter 1
month_days[2] = 31;
month_days[3] = 30;
month_days[4] = 31;
month_days[5] = 30;
month_days[6] = 31;
month_days[7] = 31;
month_days[8] = 30;
month_days[9] = 31;
month_days[10] = 30;
month_days[11] = 31;
System.out.println("April has " + month_days[3] + " days.");
}
}
It is possible to combine the declaration of the array variable with the allocation of the
array itself, as shown here:
int month_days[] = new int[12];
9. Objects
Objects are the entities in an object oriented system through which we perceive the world
around us. We naturally see our environment as being composed of things which have
recognizable identities & behavior. The entities are then represented as objects in the program.
They may represent a person, a place, a bank account, or any item that the program must handle.
For example Automobiles are objects as they have size, weight, color etc as attributes (ie data)
and starting, pressing the brake, turning the wheel, pressing accelerator pedal etc as operation
(that is functions).
Object: Account
Object: Student
Data
Data
Account number
Name
Account Type
Date of birth
Name
Marks Functions
Deposit()
Functions Withdraw()
Total() Enquire()
Average()
Display()
Programming in Java Lecture Notes Chapter 1
import MyPack.*;
class TestBalance
{
public static void main(String args[])
{
Balance test = new Balance("Hari", 1000.3);
test.show();
}
}
Creating subpackage
To create a subpackage the syntax is:
package packagename.subpackagename.*;
Programming in Java Lecture Notes Chapter 1
II. Inheritance
Inheritance is the process by which a class inherits the property of another class. The class which is
being inherited is known as the super class (or base class) and the class that inherits the property is
known sub class (or derived class). To inherit the content of superclass, the base class uses the
extends keyword. Java provides multilevel inheritance but does not support multiple inheritance.
Example:
class A
{
int i, j;
void showij()
{
System.out.println("i and j: " + i + " " + j);
}
}
class B extends A
{
int k;
void showk()
{
System.out.println("k: " + k);
}
void sum()
{
System.out.println("i+j+k: " + (i+j+k));
}
}
class SimpleInheritance
{
public static void main(String args[])
{
B subOb = new B();
subOb.i = 7;
subOb.j = 8;
subOb.k = 9;
System.out.println("Contents of subOb: ");
subOb.showij();
subOb.showk();
System.out.println("Sum of i, j and k in subOb:");
subOb.sum();
}
}
The output from this program is shown here:
Contents of subOb:
i and j: 7 8
k: 9
Sum of i, j and k in subOb:
i+j+k: 24
Programming in Java Lecture Notes Chapter 1
III. Interfaces
Using the keyword interface, we can specify what a class must do, but not how it does it. Interfaces
are syntactically similar to classes, but they lack instance variables, and their methods are declared
without any body. Once it is defined, any number of classes can implement an interface. Also, one
class can implement any number of interfaces. To implement an interface, a class must create the
complete set of methods defined by the interface. However, each class is free to determine the details
of its own implementation.
Defining an Interface
An interface is defined much like a class. The general form of an interface:
interface interfacename
{
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
type varname1 = value;
type varname2 = value; //
...
return-type method-nameN(parameter-list);
type varnameN = value;
}
interfacename is the name of the interface, and can be any valid identifier. The methods that are
declared have no bodies. They end with a semicolon after the parameter list. Each class that includes
an interface must implement all of the methods. Variables can be declared inside of interface
declarations. All methods and variables are implicitly public.
Example:
interface Callback
{
void callback(int param);
}
Implementing Interfaces
Once an interface has been defined, one or more classes can implement that interface. To
implement an interface, include the implements clause in a class definition, and then create the
methods defined by the interface. The general form of a class that includes the implements clause
is:
class classname implements interface
{
// class-body
}
If a class implements more than one interface, the interfaces are separated with a comma. The
methods that implement an interface must be declared public.
Here is a small example class that implements the Callback interface shown earlier.
class Client implements Callback
{
public void callback(int p)
Programming in Java Lecture Notes Chapter 1
{
System.out.println("callback called with " + p);
}
void nonIfaceMeth()
{
System.out.println("Classes that implement interfaces " +
"may also define other members, too.");
}
}
It is both permissible and common for classes that implement interfaces to define additional
members of their own. For example, the following version of Client implements callback( )
and adds the method nonIfaceMeth( ):
The following example calls the callback( ) method via an interface reference variable:
class TestIface
{
public static void main(String args[])
{
Client c = new Client();
c.callback(42);
}
}
Types of errors
Errors are broadly classified into two categories:
Those errors that encounter at compilation time are known as compile time errors. All syntax errors
will be detected and displayed by the java compiler and therefore these errors are known as compile
Programming in Java Lecture Notes Chapter 1
time errors. Whenever the compiler displays an error, it will not create the .class file. It is therefore
necessary that all the errors should be fixed before successfully compile and run the program. Most
of the compile time errors are due to typing mistakes. The most common compile time errors are:
- Missing semicolon
- Missing (or mismatch of) brackets in classes and methods
- Misspelling of identifiers and keywords
- Missing double quotes in string
- Use of undeclared variables
- Incompatible types in assignment/initialization
- Bad reference to objects
- And so on.
All the errors that encounter at run time are known as run time errors. During runtime errors 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. Most
common runtime errors are:
Exceptions
An exception is a condition that is caused by a runtime error in the program. When the Java
interpreter encounters an error such as dividing an integer by zero, it creates an exception object and
throws (i.e., inform us that an error has occurred).
If the exception object is not caught and handled properly, the interpreter will display an error
message and will terminate the program. To continue the program execution, we should try to catch
the exception object thrown by the error condition and then display an appropriate message for
taking corrective actions. This task is known as exception handling. The purpose of exception
handling is to provide a means to detect and report an exceptional circumstance so that appropriate
Programming in Java Lecture Notes Chapter 1
Java exception handling is managed by five keywords: try, catch, throw, throws and finally
Program statements that may generate exception are contained within try block. If an exception
occurs within the try block, it is thrown. Those statements that are used to catch those exceptions are
kept in catch block and handled in some relational manner. System generated exceptions are
automatically thrown by the java runtime 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.
Any code that absolutely must be executed before a method returns is put in a finally block.
Exception type
Programming in Java Lecture Notes Chapter 1
class Exception
{
public static void main(String args[])
{
int a,b;
try
{
b = 0;
a = 12/b;
System.out.println(" Inside try block");// this will not be printed
}
catch(ArithmeticException e)//catch division by zero error
{
System.out.println("Division by zero.");
}
type of situation, we can specify two or more catch clauses, each catching a different type of
exception. When an exception is thrown, each catch statement is inspected in order, and the first one
whose type matches that of the exception is executed. After one catch statement executes, the others
are bypassed and execution continues after the try/catch block.
Syntax;
try
{
Statements;
}
catch (exception_type1 e)
{
Statements;
}
catch (exception_type2 e)
{
Statements;
}
………….
………..
catch (exception_typeN e)
{
Statement;
}
Write a program that demonstrate the concept of multiple catch blocks class MultipleCatch
{
public static void main(String args[])
{
int a[] = {5,10}; int b = 5;
try
{
int x = a[2]/(b-a[1]);
catch(ArithmeticException e)
{
System.out.println("Division by zero");
Programming in Java Lecture Notes Chapter 1
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index error");
}
catch(ArrayStoreException e)
{
System.out.println("Wrong data type");
}
int y = a[1]/a[0];
}
Output
Array index error
Y=2
finally statement
Java supports another statement known as finally statement that can be used to handle an exception
that is not caught by any of the previous catch statements. finally block can be used to handle any
exception generated within a try block. It may be added immediately after the try block or after the
last catch block.
try
{
……….
………
}
finally
{
………..
………..
}
Or try
{
………..
Programming in Java Lecture Notes Chapter 1
………..
}
catch(………)
{
…………
…………
}
catch( ......... )
{
………..
………..
}
finally
{
………….
…………
}
throw
When we would like to throw our own exceptions, we can do this by using the keyword throw. The
general syntax of throw is as:
throw new throwableinstance;
Here, throwableinstance must be an object of type Throwable or a subclass of throwable. The flow
of execution stops immediately after the throw statement, any subsequent statements are not
executed.
Program that demonstrate the concept of throw
import java.lang.Exception;
class MyException extends Exception
{
MyException(String message)
{
super(message);
}
}
class TestMyException
{
public static void main(String args[])
{
int x = 5, y = 1000; try
{
float z = (float) x / (float) y;
Programming in Java Lecture Notes Chapter 1
throws clause
The throws keyword appears at the end of a method's signature. A throws clause lists the types of
exceptions that a method might throw.
The general form of a method declaration that includes a throws clause:
type method-name(parameter-list) throws exception-list
{
// body of method
}
Example showing the throws clause:
class ThrowsDemo {
static void throwOne() throws IllegalAccessException {
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
try {
throwOne();
} catch (IllegalAccessException e) {
System.out.println("Caught " + e);
}
}
}
Output:
Inside throwOne
caught java.lang.IllegalAccessException: demo