You are on page 1of 17

Programming in Java Lecture Notes Chapter 1

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

// A program to print the sum of two numbers


public class sum
{
public static void main(String args[]) {
int a=5, b=2;
int c=a+b;
System.out.println(“sum=”+c);
}
}
5. Data types:
 Integers: Java defines four integer types; byte, short, int and long. Byte is the smallest singed
integer type of 8-bit, short is a signed 16-bit type and is least used, int is signed 32-bit type
and most commonly used and long is a signed 64-bit type.
 Floating-point types: Floating point numbers, also known as real numbers are used when
evaluating expression that require fractional portion. It includes „float‟ and „double‟.
Programming in Java Lecture Notes Chapter 1

 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

^ Logical XOR (exclusive OR)


|| Short-circuit OR
&& Short-circuit AND
! Logical unary NOT
&= AND assignment
|= OR assignment
^= XOR assignment
?: Ternary if-then-else
 Relational Operators: The relational operators determine the relationship that one operand has
to the other. They determine equality and ordering. The relational operators are shown here:
Operator Result
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to

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

Some of the example of objects are as follows:


Physical Objects:
 Automobiles in traffic flow
 Countries in Economic model
 Air craft in traffic control system.
Computer user environment objects.
 Window, menus, icons etc
Data storage constructs.
 Stacks, Trees etc
Human entities:
 employees, student, teacher etc.
Geometric objects:
 point, line, Triangle etc.
Objects mainly serve the following purposes:
 Understanding the real world and a practical base for designers
 Decomposition of a problem into objects depends on the nature of problem.
10.Classes :
A class is a collection of objects of similar type. For example manager, peon, secretary, clerk
are member of the class employee and class vehicle includes objects car, bus, etc. It defines a
data type, much like a struct in C programming language and built in data type (int char, float
etc). It specifies what data and functions will be included in objects of that class. Defining class
does not create attributes and behaviors. Person Class may have attributes: Name, Age, Sex etc.
and behaviors: Speak(), Listen(), Walk(), etc.
Vehicle Class may have attributes: Name, model, color, height etc. and behaviors: Start(), Stop(),
Accelerate() etc.
When class is defined, objects are created as
<classname> <objectname> ;
If employee has been defined as a class, then the statement
employee manager;
Will create an object manager belonging to the class employee.
Each class describes a possibly infinite set of individual objects, each object is said to be an
instance of its class and each instance of the class has its own value for each attribute but shares the
attribute name and operations with other instances of the class.

The following point gives the idea of class:


 A class is a template that unites data and operations.
Programming in Java Lecture Notes Chapter 1

 A class is an abstraction of the real world entities with similar properties.


 Ideally, the class is an implementation of abstract data type.
11.Inheritance, Interfaces, Packages:
I. Packages: The package is both a naming and a visibility control mechanism. We can define
classes inside a package that are not accessible by code outside that package. Packages are
the Java's way of grouping a variety of classes together. The main reason for using packages
is to guarantee the uniqueness of class names.
 Defining a Package
To create a package, we use the 'package command as the first statement in a Java source file. Any
classes declared within that file will belong to the specified package. If we omit the package
statement, the class names are put into the default package, which has no name. The general form of
the package statement:
package packagename;
 Importing Packages
Java includes the import statement to bring certain classes, or entire packages, into visibility. The
general form of the import statement:
package MyPack;
public class Balance
{
String name;
double bal;
public Balance(String n, double b)
{
name = n;
bal = b;
}
public void show()
{
System.out.println(name + ":" + bal);
}
}

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

The output of this program is shown here:


callback called with 42

12. Exception handling:


Error
It is common to make mistakes while developing as well as typing a program. A mistake
might lead to an error causing the program to produce unexpected results. An error may produce an
incorrect output or may terminate the execution of the program abruptly of even may cause the
system to crash. It is therefore important to detect and manage properly all the possible error
conditions in the program so that the program will not terminate or crash during execution.

Types of errors
Errors are broadly classified into two categories:

- Compile time errors


- Run-time errors

Compile time errors

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.

Run time errors

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:

- 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
- Converting invalid string to a number
- Accessing a character that is out of bounds of a string
- And so on.

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

action can be taken.

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.

The general syntax of exception handling block is:


try
{
// block of code to monitor for errors
}
catch( Exception_type1 exob)
{
//exception handler for exception type1
}
catch( Exception_type2 exob)
{
//exception handler for exception type2
}
// ............................ finally
{
//block of code to be executed before try block ends
}
Here, exception type is the type of exception that has occurred.

Exception type
Programming in Java Lecture Notes Chapter 1

Fig: exception hierarchy


All exception types are subclasses of the built-in class Throwable. Thus Throwable is at the top of
the exception class hierarchy. Immediately below Throwable are two subclasses that partition
exceptions into two distinct branches: error and exception. There is an important subclass of
exception, called RuntimeException. The other branch called error, which define exceptions that
are not expected to be caught under normal circumstances by the program.

Using try and catch


The code that may generate exception is enclosed within try block. Immediately following try
block, include a catch clause that specifies the exception type that you wish to catch.
Program which includes try and catch block that processes the ArithmeticException
generated by the division-by-zero error.

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.");
}

System.out.println("Outside try and catch block");


}
}
Output
Division by zero.
Outside try and catch block
Multiple catch clauses
In some cases, more than one exception could be raised by a single piece of code. To handle this
Programming in Java Lecture Notes Chapter 1

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

System.out.println("Y= " +y);


}

}
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

if(z < 0.01) {


throw new MyException("Number is too small");
}
}
catch( MyException e)
{
System.out.println("Caught my Exception");
System.out.println(e.getMessage());
}
finally
{
System.out.println("I am always here");
}
}
}
Output
Caught my Exception Number is too small I am always here

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

You might also like