INTRODUCTION TO JAVA
-Ashita Agrawal
INDEX
҉ Java Evolution
҉ Overview
҉ Constants, variables & data types
҉ Operators and expressions
҉ Decision making and branching
҉ Decision making and looping
҉ Classes, objects & methods
҉ Arrays, Strings and Vectors
҉ Interface
҉ Packages
҉ Multithreading
҉ Managing errors and exceptions
҉ Applet programming
Java Evolution
History of Java
The Java platform and language began as an internal project at Sun Microsystems in December 1990, providing an alternative to the C++/C programming languages.
It was originally named Oak, designed in 1991.
Main team members : Bill Joy, Patrick Naughton, Mike Sheridan, James Gosling.
Original goal : use in embedded consumer electronic appliances.
In 1994, team realized Oak was perfect for Internet.
In 1995, renamed Java, was redesigned for developing Internet applications.
Announced in May 23 in 1995 at SunWorld’95.
First non-beta release January 23 in 1996.
VERSIONS OF JAVA
JDK 1.02 (1995) … 250 classes
JDK 1.1 (1996) … 500 classes
JDK 1.2 (1998) … 2300 classes
JDK 1.3 (2000) … 2300 classes
JDK 1.4 (2002) … 2300 classes
JDK 1.5 (2004) … 3500 classes
JDK 1.6 (2006) … 3500 classes
JDK 1.7 (2011) … 3500 classes
Characteristics of Java
Simple
Object-Oriented
Distributed
Interpreted
Robust
Secure
Architecture-Neutral
Portable
Performance
Multithreaded
Dynamic
JAVA DEVELOPMENT KIT (JDK)
The java development kit comes with a collection of tools that are used or development and running Java programs. They include:
appletviewer
Javac(java compiler)
java(java interpreter)
javap(java disassembler)
javah(java for header files)
javadoc
Jdb(java debugger)
OVERVIEW
A SIMPLE JAVA PROGRM
//This program prints Welcome to Java!
public class Welcome
{
public static void main(String args[])
{
System.out.println("Welcome to Java!");
}
}
JAVA KEYWORDS
The following list shows the reserved words in Java. These reserved words may not be used as constant or variable or any other identifier names.
Abstract
Assert
Boolean
Break
Byte
Case
Catch
Char
Class
Const
Continue
Default
Do
Double
Else
Enum
Extends
Final
Finally
Float
For
Go to
If
Implements
Import
Instance of
Int
Interface
Long
Native
new
package
Private
Protected
Public
Return
Short
Static
Strictfp
Super
Switch
Synchronize
d
This
Throw
Throws
Transient
Try
Void
Volatile
while
IMPLEMENTING JAVA PROGRAM
Implementing of a java application program involves a series of
steps. They include :
Creating the program
Compiling the program
Running the program
Source code
Java compiler
Bytecode
Machine code
Interpreter
JAVA VIRTUAL MACHINE (JVM)
Java compiler produces an intermedia code known as byte code or a
machine that does not exist. This machine is called java virtual machine
(JVM)
CONSTANTS,
VARIABLES & DATA
TYPES
CONSTANTS
Constants in java refer to fixed values that do not change during execution of a
program. Java support several types of constants :
Integer constants
Real constants
Single character constants
String constants
Backslash character constants
VARIABLES
A variable is an identifier that denotes a storage location used to store a data
value.
Unlike constants, the remain unchanged during execution of a program, but a
variable may have different values at different times during execution.
A variable name can be chosen by the programmer. Eg- average, height, name,
id, etc.
DATA TYPES
Every variable in java has a data
type .
Data type specify the type and
size of values that can be stored.
TYPE CASTING
We often encounter situations where we need to store value of one type into a variable of another type. In such
situations, we must cast the value to be stored by proceeding it with the type name in parentheses.
The syntax is :
Casting is only possible from smaller type to larger type. If casting is done from larger type to smaller, eg - float to int,
there will be a loss of data.
Type variable = (type) variable2;
From To
Byte Short, char, int, long, float, double
Short char, int, long, float, double
Char int, long, float, double
Int long, float, double
Long float, double
Float double
OPERATORS AND
EXPRESSIONS
OPERATORS
Operators can be classified into a number of categories:
Arithmetic Operators
Relational Operators
Logical Operators
Assignment Operators
Increment and decrement Operators
Conditional Operators
Bitwise Operators
Arithmetic Operator
Arithmetic operators are used to construct mathematical operators as in algebra.
Java provides all arithmetic operators like algebra.
Types of arithmetic operators:
Real arithmetic
Integer arithmetic
Mixed-mode arithmetic
Operator Meaning
+ Addition
- Subtraction
/ Division
* Multiplication
% modulus
Relational Operator
Relational operators are usually used to compare two quantities.
Example: a<b or x>20
Operator Meaning
< Is less than
<=Is less than or equal
to
> Greater than
>=Is greater than or
equal to
== Equals to
!= Not equal to
Logical Operator
In addition to relational operators, java has three logical operators.
The logical operators && and || are used when we want to form compound
conditions by combining two or more relations.
Example : a>b && b>c
Operator Meaning
&& Logical AND
|| logical OR
! Logical NOT
Assignment Operator
Assignment operators are used to assign the value of an expression to a variable.
We have seen the usual assignment operator ‘=‘.
In addition java has a shorthand assignment operators which are used in the form
where v is avariable, exp is expression and op is java binary operator.
Example:
a+=1
a-=1
a*=n+1
a/=n+1
a%=b
v op= exp;
Increment and decrement operator
Java has two very useful operators not generally found in other languages. These
are the increment ( ++ ) and decrement ( -- ) operator.
The operator ++ adds 1 to the operand while operator – subtracts 1.
Conditional operator
The character pair ?: is a ternary operator available in java.
This operator is sued to construct expressions in the form
exp1 ? exp2 : exp3
Bitwise operator
Bitwise operators are used for manipulation of data at bit level.
These operators are used for testing the bits of shifting them to right or left.
Operator Meaning
& Bitwise AND
! Bitwise NOT
^ Bitwise XOR
~ One’s complement
<< Shift left
>> Sift right
>>> Shift right with zero fill
Decision making and
branching
Decision making
Types of decision making statements in java are
If
If...else
Else if ladder
Nested if
IF Statement
The general form of a simple if statement is
if (test expression){statement-block;}statement-x;
The statement-block may be a single statement or a group of statements. If the test expression is true, the statement-block will be executed; otherwise the statement-block will be skipped and the execution will jump to statement-x. remember, when the condition is true both the statement-block and the statement-x are executed in sequence.
Example:if (x == 1){y = y +10;}System.out.println(+y);
The program tests the value of x and accordingly calculates y and prints it. If x is 1 then y gets incremented by 1 else it is not incremented if x is not equal to 1. Then the value of y gets printed.
If…else Statement
The If…else Statement is an extension of the simple if statement. An if statement can be followed by an
optional else statement, which executes when the Boolean expression is false.
Syntax:
if(test expression)
{
//True-block statement;
}else
{
//False-block statement;
}
Statement-x;
Nesting of IF..Else Statements
When a series of decision are involved then we may have to use more than one if…else statement in nested form as follows:
The general syntax is
if(test condition1)
{
if(test condition2)
{ Statement1;
}
else
{ Statement2;
}
}
else
{ Statement3;
}Statement-x;
THE else if ladder
if(test condition1)
statement1;
else if(test condition2)
Statement2;
else if(test condition3)
statement3;
………….
else if(condition n)
statement n;
else
default statement;
statement x;
Switch Case
Java provides a multiple branch selection statement known as switch. This selection statement successively tests the value of an expression against a list of integer or character constants. When a match is found, the statements associated with that constant are executed.The general form of switch is:switch(expression){case value1:
//Codesegment 1case value2:
// Codesegment 2...
case valuen://Codesegment n
default://default Codesegment
}
A switch statement is used for multiple way selection that will branch to different code segments based on the value of a variable or an expression . The optional default label is used to specify the code segment to be executed when the value of the variable or expression does not match with any of the case values. if there is no break statement as the last statement in the code segment for a certain case, the execution will continue on into the code segment for the next case clause without checking the case value.
The ?; operator
The value of a variable often depends on whether a particular booleanexpression is or is not true and on nothing else. For instance one common operation is setting the value of a variable to the maximum of two quantities.
Setting a single variable to one of two states based on a single condition is such a common use of if-else that a shortcut has been devised for it, the conditional operator, ?;.
Using the conditional operator you can rewrite the above example in a single line like this: max = (a > b) ? a : b;
(a > b) ? a : b; is an expression which returns one of two values, a or b. The condition, (a > b), is tested. If it is true the first value, a, is returned. If it is false, the second value, b, is returned.
Decision making
and looping
LOOPING
• Java has three kinds of looping statements:
– the while loop
– the do loop
– the for loop
The while Statement
A while statement has the following syntax:
while ( condition )
{
statement;
}
If the condition is true, the statement is executed
Then the condition is evaluated again, and if it is still true,
the statement is executed again
The statement is executed repeatedly until the condition
becomes false
The do-while Statement
• A do-while statement (also called a do loop) has the
following syntax:
Do{
statement;
}while ( condition )
• The statement is executed once initially, and then the
condition is evaluated
• The statement is executed repeatedly until the condition
becomes false
The for Statement
A for statement has the following syntax:
5-39
for ( initialization ; condition ; increment ){
statement;
}
The initialization
is executed oncebefore the loop begins
The statement is
executed until thecondition becomes false
The increment portion is executed
at the end of each iteration
CLASSES, OBJECTS
AND METHODS
Defining a class
A class is a user defined data type with a template that serves to define its properties. The basic
form of a class definition is:
Class classname [extends superclassname]
{
[fields declaration;]
[method declaration;]
}
Classname and superclassname are any Java identifiers. The keyword extends indicates
the properties of the superclassname class because they are extended to the classname
class. This concept is known as inheritance. Fields and methods are declared inside the
body.
Constructor
A Constructor is similar to method that is used to initialize the instance variables.
The automatic initialization of the object is performed through the constructor.
Constructors have the same name as the class name. secondly, they do not specify a return
type, not even void. This is because they return the instance of the class itself.
There are two types of constructors:
• default constructor
• parameterized constructor
Methods overloading
If a class have multiple methods by same name but different parameters, it is known as
Method Overloading.
Method overloading is used when objects are required to perform similar tasks but using
different input parameters.
To create an overloaded method, all we have to do is to provide several different method
definitions in the class, all with the same name, but with different parameter lists. The
difference may either be in the number of type of arguments. This is, each parameter list
should be unique.
Inheritance
Inheritance is the concept used to share the data of one class into another class. Inheritance is
the process by which objects can acquire the properties of objects of other class. This is
achieved by deriving a new class from the existing one. The new class will have combined
features of both the classes.
Types of inheritance are:
• Single Inheritance
• Multiple Inheritance
• Multi-Level Inheritance
• Hierarchical Inheritance
• Hybrid Inheritance
‘Super’ keyword
The super is a reference variable that is used to refer immediate parent class object.
Whenever you create the instance of subclass, an instance of parent class is created
implicitly i.e. referred by super reference variable.
Usage of super Keyword
super is used to refer immediate parent class instance variable.
super() is used to invoke immediate parent class constructor.
super is used to invoke immediate parent class method.
‘Final’ keyword
Final Variables:
If we define the variables with final keyword that variables are called Final variables. These
variables doesn’t supports to reassign the constants.
Final Method:
If we define the methods as final that methods are called final methods. That methods doesn’t
supports to override in sub classes.
Final Class:
If we define the class as final that class is called Final Class. That class doesn’t supports to inherit
in another classes.
Method Overriding
If subclass (child class) has the same method as declared in the parent class, it is known as
method overriding.
Advantage of Java Method Overriding
Method Overriding is used to provide specific implementation of a method that is already
provided by its super class.
Method Overriding is used for Runtime Polymorphism
Abstract Class & method
A class that is declared with abstract keyword, is known as abstract class in java. It can
have abstract and non-abstract methods (method with body).
It cannot be instantiated.
A method that is declared as abstract and does not have implementation is known as
abstract method.
A method that is declared as abstract and does not have implementation is known as
abstract method.
The abstract class can also be used to provide some implementation of the interface. In
such case, the end user may not be forced to override all the methods of the interface.
Arrays, Strings & Vectors.
Array
An array is a group of contiguous or related data items that share a common name.
Arrays can be of any variable type.
Example: to define an array salary to represent a set of salaries of a group of employees.
salary[10];
Types of arrays:
one dimensional array
Two dimensional array
Strings
String represent a sequence of characters.
String manipulation is the most common part of many java programs.
Strings may be declared as follows:
String stringname;
Stringname = new string (“string”);
String array can be created as
String stringarrayname[ ] = new String[ ];
Methods of string class
char charAt(int index)
Returns the character at the specified index.
int compareTo(Object o)
Compares this String to another Object.
String concat(String str)
Concatenates the specified string to the end of this string.
boolean equals(Object anObject)
Compares this string to the specified object.
int indexOf(int ch)
Returns the index within this string of the first occurrence of the specified character.
int length()
Returns the length of this string.
String replace(char oldChar, char newChar)
Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
String replaceAll(String regex, String replacement
Replaces each substring of this string that matches the given regular expression with the given replacement.
String toUpperCase()
Converts all of the characters in this String to upper case using the rules of the default locale.
String toLowerCase()
Converts all of the characters in this String to lower case using the rules of the default locale.
String buffer class
String buffer is a peer class of string.
While String creates strings of fixed _length, StringBuffer creates strings of flexible length that can
be modified in terms of both length and content.
We can insert characters and substrings in the middle of a string, or append another string to the
end.
Below are some methods of StringBuffer class
Method Task
S1.setChartAt(n, ‘x’) Modifies the nth character to x.
S1.append(s2)Appends the string s2 to s1 at the end.
S1.insert(n,s2)Inserts string s2 at position n of the string.
S1.setLenght(n) Sets length of string
Vectors
Vector implements a dynamic array. It is similar to ArrayList, but with two differences:
• Vector is synchronized.
• Vector contains many legacy methods that are not part of the collections framework.
Vector proves to be very useful if you don't know the size of the array in advance or you
just need one that can change sizes over the lifetime of a program.
Interfaces and
Packages.
Interface
An interface is basically a kind of class.
Like classes, interfaces contain methods and variables but with one major difference. The difference is that interfaces define only abstract methods and final fields.
This means that interfaces do not specify any code to implement these methods and data fields contain only constants.
Example
Interface area
{
static final float pi=3.14f;
float compute (float x, float y);
void show ( );
}
Syntax for defining a interface
Interface interfacename
{
variable declaration;
methods declaration;
}
Variables in an interface are declared as follows:
static final type variablename = value;
Methods in an interface are declared as follows:
return-type methodname1 (parameter-list);
Packages
Packages are java’s way of grouping a variety of classes and interfaces together.
The grouping is usually done according to functionality.
Packages are also called as container for classes.
Java API packages
java
appletnetawtioutilLang
Naming convention
Packages can be named using the standard java naming rules. By convention, however
packages begin with lowercase letters. This makes it easy to easy for users to distinguish
packages names from class name when looking at an explicit reference to a class. We
know that all class names, again by convention, begin with an upeercase letter.
Example
double y= java. lang. Math. sqrt (x);
Package
name
method
nameclass
name
Creating packages
Creating our own package contains the following steps:
▫ Declare the package at the beginning of a file using the form package packagename;
▫ define the class that is to be put in the package and declare it public.
▫ Create a subdirectory under the directory where the main source files are stored.
▫ Store the listing as the classname .java file in the subdirectory.
▫ Compile the file. This creates .class file in the subdirectory.
Multithreading
programming
Multithreading
It is a programming concept in which a program or
a process is divided into two ore more subprograms
or threads that are executed at the same time in
parallel.
It supports execution of multiple parts of a single
program simultaneously.
The processor has to switch between different
parts or threads o a program.
It is highly efficient.
A thread is the smallest unit in multithreading.
It helps in developing efficient programs
---------------
---------------
---------------
---------------
---------------
---------------
---------------
---------------
---------------
---------------
---------------
---------------
---------------
---------------
---------------
---------------
---------------
---------------
---------------
---------------
---------------
---------------
---------------
---------------
Main Thread
switching
start
main method module
startstart
switching
Thread CThread BThread A
Creating Threads
Threads are implemented in form of objects that contain a method called run( ). The run( ) method is the heart and soul of any thread. It makes up entire body of a thread and is the only method in which the thread’s behaviour can be implemented. A typical run( ) would appear as follows:
The run( ) method should be invoked by an object o the concerned thread. This can be achieved by creating the thread and initializing it with the help of another thread method called start( ).
A new thread can be created in two ways:
i. By creating a thread class
ii. By converting a class to a thread
Public void run ( ){...........................}
Life cycle of a Thread
A thread can be in one of the five states.
The life cycle of the thread in java is controlled by JVM. The java thread states are as follows:
o New
o Runnable
o Running
o Non - Runnable (Blocked)
o Terminated
1. New
The thread is in new state if you create an instance of Thread class but before the invocation of start() method.
2. Runnable
The thread is in runnable state after invocation of start() method, but the thread scheduler has not selected it to be the running thread.
3. Running
The thread is in running state if the thread scheduler has selected it.
4. Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently not eligible to run.
5. Terminated
A thread is in terminated or dead state when its run() method exits.
Stopping and Blocking a thread
Whenever we want to stop a thread
from running further, we may do so
by calling the stop( ) method.
aThread.stop( );
This statement causes the thread to
move to the dead state.
A thread can also be temporarily
suspended or blocked form entering
into The runnable and subsequently
running state by using either oF the
following thread methods:
− Sleep( )
− Suspend( )
− Wait( )
STOPPING BLOCKING
Thread Priority
In Java, Each thread has a priority.
Priorities are represented by a number between 1 and 10.
In most cases, thread scheduler schedules the threads according to their priority (known as pre-
emptive scheduling).
But it is not guaranteed because it depends on JVM specification that which scheduling it
chooses.
3 priorities are:
• MIN_PRIORITY = 1
• NORM_PRIORITY = 5
• MAX_PRIORITY = 10
Synchronization
Synchronization in java is the capability of control the access of multiple threads to any shared
resource.
Java Synchronization is better option where we want to allow only one thread to access the
shared resource.
The synchronization is mainly used to
• To prevent thread interference.
• To prevent consistency problem.
Managing Errors and Exceptions
Errors
Errors are the wrongs that can make a program go wrong.
Types of errors:
1. Compile time
error
• Missing semicolons
• Missing brackets
• Misspelling of identifiers and keywords
• Missing double quotes in strings
• Use of undeclared variables
• Use of = in place of == operator
• And so on
2. Run time error
• 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
• Converting invalid string to a number
• Attempting to use a negative size for an array
• Passing a parameter that is not valid range or value for the method
• And many more
Exception
An exception is a condition that is caused by a run-time error in the program. When the java interpreter encounters an error such as dividind by zero, it creates an exception object and throw it.
If the exception object is not caught and handled properly, the interpreter will display an error message. And will terminate the program.
If we want the program to continue with the execution f the remaining code, then 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 mechanism is to provide a means to detect and report an “exceptional circumstance” so that the appropriate action can be taken. The mechanism suggests incorporation of a separate error handling code that performs the following tasks:
1) Find the problem
2) Inform that an error has occurred
3) Receive the error information
4) Take corrective actions
Common java exceptions
a) Arithmetic Exception
b) Array Index Out Of Bounds Exception
c) File Not Found Exception
d) IO Exception
e) Null Pointer Exception
f) Number Format Exception
g) Out Of Memory Exception
h) Security Exception
i) Stack Overflow Exception
j) String Index Out Of Bounds Exception
Syntax of exception handling code
Try Block
Statement that causes an exception
Catch Block
Statement that handles the exception
Throws exception object
Exception object
creator
Exception handler
Multiple Catch statements
.............
.............
Try
{
statement;
}
catch (exception-type-1 e)
{
statements;
}
Catch (exception-type-2 e)
{
statements;
}
.
.
.
catch (exception-type-n e)
{
statements;
}
‘finally’ keyword
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.
When a finally block is defined, this is guaranteed
to execute, regardless of wheter or not in
exception is thrown.
try
{
statement;
}
Catch (.........)
{
statement;
}
finally
{
statement;
}
Throwing our own exception
There may be times when e need to throw our own exception. We can do this by keyword throw.
Example: throw new ArithmeticException( );
Throw new Throwable subclass;
Applet programming
Applet
An applet is a special Java program that can be embedded in HTML documents.
It is automatically executed by (applet-enabled) web browsers.
In Java, non-applet programs are called applications.
Building applet code
Import java. Awt. *;
Import java. Applet. *;
........
........
Public class appletclassname extends applet
{
.............
.............
public void paint (graphics g)
{
...........
}
..........
}
Chain of classes inherited by applet class
Java. lang. Object
Java. awt. component
Java. awt. Container
Java. awt. Panel
Java. applet. Applet
Applet life cycle
The changes in state of applet life is shown in the following state transition diagram
Born
Running Idle
Dead End
Stopped
Destroyed
Exit browser
Begin
(Load applet)Initialization
Display
paint()
start() stop()
start() destroy()
Commonly used methods of Graphics
class:
public abstract void drawString(String str, int x, int y): is used to draw the specified string.
public void drawRect(int x, int y, int width, int height): draws a rectangle with the specified width and height.
public abstract void fillRect(int x, int y, int width, int height): is used to fill rectangle with the default color and specified width and height.
public abstract void drawOval(int x, int y, int width, int height): is used to draw oval with the specified width and height.
public abstract void fillOval(int x, int y, int width, int height): is used to fill oval with the default color and specified width and height.
public abstract void drawLine(int x1, int y1, int x2, int y2): is used to draw line between the points(x1, y1) and (x2, y2).
public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer): is used draw the specified image.
public abstract void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle): is used draw a circular or elliptical arc.
public abstract void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle): is used to fill a circular or elliptical arc.
public abstract void setColor(Color c): is used to set the graphics current color to the specified color.
public abstract void setFont(Font font): is used to set the graphics current font to the specified font.