You are on page 1of 98

Introduction to JAVA

History of Java
Java was developed at Sun Microsystem in 1995. The history of Java can be traced back to a project called Green project in SUN. Patric Naughton, Bill Joy, James Gosling, Mike Sheridan were some of the people working on the Green project. The aim of this project was to develop software for smart consumer electronic devices such a complex remote controls.

At first developer tried using C++ to develop the software but they faced
a number of problems.

So James Gosling developed a new language, which he called Oak. A

study showed that there already was a programming language called


Oak. So they changed the name to Java. In 1994, the Internet and the World Wide Web became popular. The people at Sun realized that Java was suitable to develop applications for the Internet.
They wanted fundamentally a new way of computing, based on the power of networks and wanted the same software to run on different

computers, consumer gadgets and other devices

During that time Mosaic the First Graphical Browser was released, with this people on different types of machines and operating systems started accessing the applications available on the web.

Patrick Naughton and his colleague Jonathan Payne developed a browser in Java called WebRunner, which they later renamed as Hot Java.

Members of the Oak team realized that java would provide the required cross-platform independence from the hardware network, and the

operating system. Very soon, Java became an integral part on the web.

The New Era of Java


Java is new programming language from Sun Microsystems The elements from C, C++, and other languages, The libraries highly tuned for the Internet Environment. Java is quickly recognizable to many programmers. The statements and expressions are similar to those in many languages and, in most cases, identical to those of C or C++.

Comparison with C
Java does not have:
1. Pointer Manipulation 2. The goto statement

3. Automatic type conversion


4. Global functions variables 5. Type definitions aliases (typedefs) 6. Preprocessor

Compared with C++


Java does not have Operator overloading

Java System
1. Software Libraries accompanying the system (API) 2. Java Virtual Machine (JVM) (Platform Independent) 3. Java-Enabled Web Browser

The Java Platform

M/C code 01001


Java Program JVM Interpreter Computer

Compile

intermediate Byte Code

Platform Independent
Java Program

Compiler

Interpreter JVM

Interpreter JVM

Interpreter JVM

Windowss

Solaris

Lunix

Characteristics of Java
Simple and Powerful Architecture-Neutral Object-Oriented Portable

Distributed
High-performance Interpreted Multithreaded Robust Dynamic Security

(Application Programming Interface)

Java API
Applet classes

java. lang java. applet java. awt java. awt. event java. beans java. io java. net java. rmi

Core language classes

Graphics, window, and GUI classes Event processing classes & interfaces

Java Beans component model API


Various types of input/output classes Networking classes Remote method invocation classes Security classes JDBC SQL API for database access Various useful data classes

java. security
java. sql java. util

Java Development Kit (JDK)


javac - the complier, checks for syntactical error and converts syntax free java program into bytecode.

Java
- the Interpreter, executes the bytecode Appletviewer - used to test applets on machines which does not have java enabled web browser

Type of Java Programs


Java is of two things:
1. An Application Programming language 2. An Applet
(Platform Independent Programming)

Java Fundamentals
Structure of a JAVA program: class <Class_name> {
public static void main(String args[])

{
statements;

} }

Comments:
1. 2. A Single Comment //. A Multiline Comment /**/

3. Documentation Comment
/** */. They are used to produce a HTML file that documents the program.

Java Keywords
abstract do implements short

boolean
break byte case catch char class continue default

double
else extends final finally float for false if

import
int interface long new private protected public return

static
super switch this throw try true void while

Data Types
Keywords byte short int long Real Types float 4 Byte Size 1 2 4 8

Integer Types

double
Other Types char boolean

8
2 true or false

Identifiers
1. The Identifier name must start with an alphabet, underscore and DollerSign and can contain only alphabets, number, underscore and DollerSign($). 2. 3. 4. No space between Identifier name Java Keywords cannot be used as Identifier names. Java is a case-sensitivity, a Identifier name with

upper case letters is different from the same name with lower case letters.

Declaration of Variable and Constants


Syntax : datatype <identifiername>; Example :

float radius; //(variable);


final float PI=3.14f; //(constant)

Convention
1.

Class Name: Begins with first letter uppercase letter.


Eg: Student, StudentDetails

2.

Variable or Method name: Begin with a lowercase

letter followed by consecutive words begin with uppercase


Eg: basicSalary, netSalary Eg: isVisible(), parseInt()

3.

Constant in java are defined as Fully uppercase


Eg: PI

Operators
Operator is a Symbol which performs specific Operation

Classification of Operators
Unary Operator Operators that acts upon a single operand Binary Operator Acts upon two operand Ternary Operator Acts upon three operand

Operators
Arithmetic Operator (Binary) Relational Operator (Binary) Logical Operator (Binary) Conditional Operator (Ternary)

Assignment Operator (Binary)


Increment / Decrement Operator (Unary) Comma Operator (Binary)

Bit-Wise Operator (Binary)

Arithmetic Operator - Binary


Operators Meaning + Addition Example a+b Result 5+2=7

* / %

Subtraction Multiplication Division Modulo

a-b a*b a/b a%b

5-2=3 5*2=10 5/2=2 or 2.5 5%2=1

Expression
An Expression consists of variables and constants separated by operators.

Eg: a+b;
a+b/c;

Operator Priority
Left to Right ( ) ++,-- (Right to Left) *,/,% +,-

Type Casting
Converting from one data type to another data type Implicit Type Casting (Automatic) Explicit Type Casting (Programmer)

Implicit Type Casting


Conversion is taking place automatically during program execution and is referred to automatic type or implicit conversion

Operand1 int int

Operand2 int long

Result int long

float float

int double

float double

Explicit Type Casting


Variable declared in specific data type can be converted into the required data type Syntax:

Variable = (typecast) expression;


Example: int a,b,c; float f; f= (float) (a+b)/c;

Relational Operator
Which are used to compare the values of operands to produce a logical value either true or false Which is used make a decision for real world problem
True =1 False=0

Relational Operators
Operators < <= > >= Meaning Less than Less than or equal to Greater than Greater than or equal to Example a<b a<=b a>b a>=b Result If a=2,b=5 True True False False

!=
==

Not equal to
Equality

a!=b
a==b

True
False

Logical Operators
Which are used to evaluate more than one relational expressions Which is also used to make a decision either true or false

Operator
&& || !

Meaning
AND OR Not

Example
A&&B A||B !A

Logical Operator
Example
A True True B True False A&&B True False A||B True True

False
False

True
False

False
False

True
False

Conditional Operator
The operator that act upon three operands are called as Conditional Operator or Ternary Operator. This operator is used to check either one only true or false statement. Which is used to make a decision Syntax: Exp1 ? Exp2 : Exp3; If Exp1 is true, Exp2 will execute If Exp1 is false , Exp3 will execute

Example
{ int a=5,b=3,big; big=(a>b) ? a : b ;

printf(Biggest of two nos = %d,big);


} Output: Biggest of two nos = 5

Assignment Operator (=)


The operator that is used to assign the result of an expression to a variable is called as an Assignment Operator.

Syntax: Variable= constant; Variable1=variable; Variable=expression;

Example a=10; a=b; a=a+b;

Types of Assignment Operator


Normal Assignment a=a+b; Short Assignment

a+=b; (fast)
Invalid Assignment Const=var Exp=var 10=a a+b=a

Increment(++)/Decrement (--) Operator


Increment by 1 or Decrement by 1 with current value. Types

Post Increment and Decrement


Pre Increment and Decrement

Post Increment and Decrement operator


Syntax:

Increment
Var++;

Example
int a=10; a++; Output: 11

Decrement
Var--;

Example
int b=20; b--; Output: 19

Pre Increment and Decrement operator


Syntax: Increment Example Decrement Example

++Var;

int a=10; ++a


Output: 11

--Var;

Int b=20; --b;


Output: 19

Difference between Post and Pre increment


Post Increment int x,y; x=10; y=x++; ( The value of x is assign to y ie: y=10, then x will be increment x=11) Pre Increment int x,y; x=10; y=++x; ( The value of x will be increment x=11 then assign to y ie: y=11)

Output:
x=11 y=10

Output:
x=11 y=11

Comma Operator(,)
Which is used to link the related Expressions together

Example: without Comma int a; int b; int c; a=10; b=20 c=a+b

Example: with comma


int a,b,c;

c=(a=10,b=20,a+b);

Bitwise Operators
These operators are used to perform operations in terms of binary. Ex: int a=5, b=3
Operators
& |

Meaning
Bitwise AND Bitwise OR

Example
a&b a|b

Output
1 7

~
^ >> <<

Bitwise NOT
Exclusive OR (XOR) Right Shift Left Shift

~a
a^b a>>2 a<<2

65350
6 1 20

Control Statements
By default, the statements in the program are executed sequentially. The control statements alter the execution of statements

depending upon the conditions


Which are used to make a decision for real world problems

Types
Simple if if .. else Multiple else if or else if ladder Nested if switch break or continue

Simple if
It is used to execute block of statements if the condition is true, otherwise it will skip the if block Syntax: if(condition)

True

False

Execute block of statements; -----------------;

----------------;
} Normal statements;

If .. Else Statement
Used to Evaluate True block or False block statements If the if condition is true it will execute true block otherwise, execute else block statements Syntax: if(condition) True { Execute true block statements; -----------------; False ----------------; } else { Else block statements; }

Multiple else if Statements


Used to evaluate Series of Conditions If we have to use more than one if-else statement, we have to create Multiple else if statements.

Syntax:
if(condition 1)

else if(condition 3) { Execute 3rd block statements; } else {

Execute 1st true block statements; } else if(condition 2) { Execute 2nd block statements; }

final block statements;


}

Nested If statements
One condition followed by another condition

Syntax:
if(condition1)
{ if(condition2) { Inner if statements; } else { Inner else statements; } }

else
{ Outer else statement; }

Note for else statement


Else should be followed by if statement Else should not take condition

Else will execute only if the immediate if statement false


Else is optional

Switch Statement
Switch statement allows us to make a decision from a number of choices. It is used to execute a block of statements depending on the value of a variable or an expression Syntax: Switch(int var or char var) { case constant1 : statement(s); -----------; case constant2 : statement(s); case constant3 : statement(s); default: default statement(s); }

Points to be noted for switch statement


Only one variable can be tested with the available case statements It should be either integer or character variable Float, double, long type variables cannot be used as cases.

Default statement will execute only none other than case is match
Default statement may appear any where inside the switch statement

Default is optional

Loop Control Structures


A block of statements are executed repeatedly until a condition false is called as a loop. Types while loop do..while loop

for loop

Three steps of looping process


Initialization of the counter Test for a specified condition for execution of the statements in the loop Increment or Decrement the counter

While loop
Syntax: Initialize loop counter; while(condition)

{
Statement(s); Increment or decrement loop counter; }

do..while loop
The do..while loop is similar to while loop except that the dowhile loop test the condition at the end of the loop. Hence, the loop will be executed at least once if the condition not satisfied. While loop will executed only if the condition is satisfied.

Syntax:
do { Statements(s); -------------; }while(condition);

For loop
For loop allows us to specify three steps about the loop in a single line Syntax: for(initialization;condition;increment/decrement) { Statements(s); } Note: The condition specified in the loop should eventually become false at one point, otherwise the loop will become infinite loop

Break and Continue


1. The break keyword exit from switch or inner loop
of a program 2. Continue is similar to break, except that instead

exit from loop, it continue the next iteration.

Arrays
An array is an object that stores a list of items continuously of same data type. An array is used to store data continuously in the memory of the computer.

The individual values in the array are called as elements. Each array element is referred by specifying the array name, followed by a number within the square braces[],referred as an index or subscript.

Types of Arrays
Single Dimension Array Multi Dimension Array

Single Dimension Array


Declaration
Array Initialization: Syntax : data-type array-name[] = {value1, value2,..... }; Eg: int a[]= {10,20,50,67,77}

Creating array with size


Syntax:
datatype array-name [] = new datatype[size]; Eg: 1) int a[] = new int[5]; or 2) int[] a = new int[5]; or 3) int a[]; -------------------; -------------------; a[]= new int[5]; new keyword creates an instance of an array

Two Dimension Array:


Declaration : Syntax: datatype array_name[][] = new datatype[rowsize][col.size];

Eg:

int a[][]= new int[3][3];

Methods
Method Declaration
access-specifier static returntype methodName(argument list) { Local variable declaration; Executable part; return (expression); }

Type of Declarations
1. 2. 3. 4. Method with arguments and with return type Method without arguments and with return type Method with arguments and without return type Method without arguments and without return type

Object Oriented Programming (OOPs)


It simplifies the development of large and complex software
systems and helps in the production of softwares, Which is Modular, Reusable, Scalable and Security. The object oriented approach centers around modeling the real world problems in terms of objects.

OOP's Concept
The object-oriented model is based on three important concepts namely

1. Encapsulation, 2. Inheritance and 3. Polymorphism

Encapsulation
1. A mechanism that binds together code and the data where code manipulates the data, and keep both safe from outside interference and misuse. Encapsulation is a protective wall that prevents the code and data from being randomly accessed by other code defined outside the wall. The concept of hiding the non-essential details from the user is called Encapsulation.

2.

3.

Eg: Consider an Automobile. The information about the engine is hidden from the user.

Inheritance
Is a process of creating a New Class with the properties of an Existing Class, along with the additional characteristics unique to the new class. The new class obtains the properties of the existing class.

Polymorphism
Is a feature that allows one Interface to be used for a general class of action. More generally, the concept of polymorphism is often expressed by the phrase "one interface, multiple methods". This means one common name for a method with different parameters. In Java , there are two types of polymorphism:
1. Method Overloading (Compile) 2. Method Overriding (Runtime)

Class
A class is a prototype that defines the Data and Code common to all objects of a particular kind. A class defines the structure and behavior of the objects.

The elements of a class are called members.


The code that acts on the data is called method. The data defined by the class is called variables.

Object
An instance of class Copy of class or Real time entity of a class. It is a variable, which is used to access the instance variables and methods of class

new Operator
The new operator creates a single instance of a named class and returns a reference to that object. Syntax:

class-name Objectname=new class-name( );


Eg: Box mybox = new Box();

Reference Variable
Box mybox; //declare reference to object

mybox = new Box();


//allocate memory for a box object

Dot Operator
The dot notation is used to obtain the value of the instance variable. <object Reference> . <variable name>

<objectReference> . <method name>

Eg: obj.a=10; obj.sum();

Access Specifier
Public:
The members, which are declared as a public, can be accessed by any method in the outside of the class. A Member Data or Methods can only be accessed by the methods of the same class. The private instance variable is not accessible from the outside of the class.

Private :

Protected:
Note:

The protected access specifiers have been deal with Inheritance and packages in java.

In Java, default access specifies is NoAccessSpecifier, not a public

Static Keyword
The static modifier can be applied to

variables, methods and even to a strange

kind of code that is not a part of a method.


Static features are associated with a class rather than being associated with an individual instance of a class

static Variable
Via a reference to any instance(object) of the class Via the classname.

eg: objectname.var=value; classname.var=value;

Static Method
They can only call other static methods
They must only access static data. They cannot refer to this or super in any way

Method Overloading
In a class more than one method can have same method name.
All the methods distinct in three ways. 1. The number of arguments should be distinct. 2. Types of argument should be distinct. 3. Sequence of argument should be distinct.

Constructor
A Constructor is a special kind method that determines how an object is initialized when created.
Rules for constructing Constructor:1. Constructor name and class name must be equal. 2. Constructor should be in public 3. Constructor has no return type. But it may be have argument. 4. When we create an object of the class, constructor will be invoke automatically. 5. Constructors can also be Overloaded

Types
Default Constructor: Parameterised Constructor Overloading Constructors

Inheritance
It is a process of creating new class from an existing class. The existing class is called as Base class (or) super class. created class is called derived class. The newly

as subclass or

Syntax
class<sub-class-name> extends <super-class-name> { instance variable; + methods(); }

Types
Single Inheritance. Multilevel Inheritance

Hierarchical Inheritance
Multiple Inheritance ( for Interfaces only)

Method Overriding
In a multilevel inheritance, when a method in a subclass as the same name and type signature as a method in its super class, then the method in subclass is said to override the method in the

superclass

Abstract Class
There are situations in which we will want to define a super class that declares the structure of a given abstraction without providing a complete implementation of every altered. You can require that certain method to be overwrite in the future To declare an abstract method, the function declaration should be preceded by abstract keyword. Any class that contains one or more abstract methods must also be declared as abstract class.

Syntax
abstract class A { abstract public int arith(int a, int b); public int sum(int a,int b) { return (a+b); } } Note: Abstract Class Cannot be instantiate (cannot create object.)

Final Modifiers
Final variable
cannot be modified

Final Class
cannot inherited

Final Method
cannot override

this keyword
The this keyword is used inside any instance method to refer to the current object. The value of this refers to the object on which the

current method has been called. The this


keyword can be used where a reference to an object of the current class type is required

Note: Methods declared with the keyword


static (class methods) cannot use this.

Interfaces
An Interface is a collection of methods without implementation. An interface can also include variable declaration.

Defining an interface:
interface interface-name { variables+methods; }

Implementing interfaces
Once an interface has been defined, one or more classes can implement that interfaces. To implement the interface, include the implements keyword in a class definition and then create a method defined by the interface.

Syntax
class class-name implements interface-name { }

Note: An interface cannot be instantiate

Points to be Note for classes and Interfaces


A class can extends another class A interface can extends another interface A class can implements more than one interfaces Note:
An interface cannot extends or implements a class

Exception Handling
An exception is an event that occurs during the execution of a program that disturbs the normal flow of instructions Exceptions are erroneous events like Division by Zero, Opening a File that Does Not Exist etc. A Java exception is an object describes an exceptional condition that has occurred in a piece of code. Error handling becomes necessarily when you develop applications that need to cause of unexpected situations

try .. catch block


try {
Statements; -----------------; ------------------; } catch(Exception object) { Exception code; -----------; }