Professional Documents
Culture Documents
R. Ravi Kumar
Introduction to Java
2
Introduction to Java
OOPs Concepts
Need for Different Approach in Modern Programming
Since the invention of the computer, Many programming
approaches have been tried.
Modular, Top-down, Bottom-up, and Structured
Programming.
The primary motivation is to handle increasing complexity
of programs that are reliable and maintainable.
With languages such as C, Structured programming
became very popular.
As the programs grew larger, even the structured approach
failed in terms of bug-free, easy-to-maintain, and reusable
programs.
3
Introduction to Java
OOPs Concepts
Object Oriented Programming (OOP) is an approach to
program organization and development, which
attempts to eliminate some of the pitfalls of
conventional languages.
It incorporates the best features of structured
programming with several new features.
Languages that support OOP features – Smalltalk,
Objective C, C++, Ada, and Object Pascal.
The latest one added to this list is Java and C#
4
Introduction to Java
OBJECT-ORIENTED PARADIGM
OOP treats data as a critical element
Method Method
and does not allow it to flow freely
around the system. Data
It ties data more closely to the Method Method
functions that operate on it and
protects it from unintentional
modification by other functions.
OOP allows to decompose a problem in to number of
entities called Objects and build data and functions
around these entities.
Object = Data + Methods 5
Introduction to Java
OOPs Features:
Emphasis is on data rather than procedure.
Programs are divided into what are known as Objects.
Methods that are operate on the data of an object are tied
together in the data structure.
Data is hidden and cannot be accessed by external functions.
Objects may communicate with each other through methods.
New data and methods can be easily added whenever necessary.
Follows bottom-up approach in program design.
6
Introduction to Java
OOPs Definition:
Object-oriented programming is an approach that provides a
way of modularizing programs by creating partitioned memory
area for both data functions that can be used as templates for
creating copies of such modules on demand.
9
Introduction to Java
Data Abstraction and Encapsulation:
“Wrapping up of data and methods into a single unit (called
class) is known as encapsulation”
“Insulation of the data from direct access by the program is
called data hiding”
10
Introduction to Java
Inheritance:
“Inheritance is the process by which one object acquires the
properties of objects of another class”
Bird
Attributes:
Feathers
• Reusability Lay Eggs
Shape
Draw ( )
• Reusability
Circle Object Box Object Triangle Object
• Add additional features to Draw (circle) Draw (box) Draw (triangle)
an existing class without
modifying it
12
Introduction to Java
Applications of OOP:
Real-time systems
Simulation and modeling
Object-oriented database
Hypertext, hypermedia
AI and expert systems
Neural networks and parallel programming
Decision support and office automation systems
CIM/CAD/CAD system
13
Introduction to Java
JAVA Evolution:
Java was conceived by James Gosling, Patrick Naughton, Chris Warth,
Ed Frank, and Mike Sheridan at Sun Microsystems, Inc. in 1991.
Initially called “Oak” but was renamed as “Java” due to legal issues.
1992 – The team, known as Green Project team by Sun, demonstrated
the application of their new language to control a list of home
appliances.
1993 – Due to popularity of World Wide Web, the Green Project team
came up with the idea of developing Web applets using JAVA.
1994 – The team developed a Web browser called “HotJava” to locate
and run applet programs on Internet.
1995 – Oak was renamed as “Java”.
14
Introduction to Java
JAVA Features:
Compiled and Interpreted
Platform-Independent and Portable
Object-Oriented
Robust and Secure
Distributed
Familiar, Simple and Small
Multithreaded and Interactive
High Performance
Dynamic and Extensible 15
Introduction to Java
Overview of JAVA development process:
17
Introduction to Java
JAVA Environment:
It includes a large number of development tools and
hundreds of classes and methods.
The development tools are part of the system known as Java
Development Kit (JDK)
The classes and methods are part of the Java Standard
Library (JSL), also known as the Application Programming
Interface (API)
18
Introduction to Java
JAVA Environment:
The Java Development Kit comes with a collection of tools
that are used for developing and running Java programs.
Applet viewer – for viewing Java applets
Javac – Java Compiler
Java – Java interpreter
Javap – Java disassembler
Javah – for C header files
Javadoc – for creating HTML documents
Jdb – Java debugger 19
Introduction to Java
JAVA Version History:
JDK 1.0 (January 23, 1996)
JDK 1.1 (February 19, 1997)
J2SE 1.2 (December 8, 1998)
J2SE 1.3 (May 8, 2000)
J2SE 1.4 (February 6, 2002)
J2SE 5.0 (September 30, 2004)
Java SE 6 (December 11, 2006)
– Java SE 6 Update 10
– Java SE 6 Update 11
– Java SE 6 Update 12
– Java SE 6 Update 14
– Java SE 6 Update 16
– Java SE 6 Update 17
Java SE 7 20
Introduction to Java
Process of Building and Running Java Application programs:
Text Editor
Java jdb
Java Program
Output
21
Introduction to Java
Two Ways of using Java:
Java Source
Code
Java Compiler
Java enabled
Java Interpreter
Web Browser
Output Output
22
JDK Editions
Java Standard Edition (J2SE)
– J2SE can be used to develop client-side standalone
applications or applets.
Java Enterprise Edition (J2EE)
– J2EE can be used to develop server-side applications such
as Java servlets and Java ServerPages.
Java Micro Edition (J2ME).
– J2ME can be used to develop applications for mobile
devices such as cell phones.
24
Introduction to Java
General Structure of a Java program:
26
Introduction to Java
A closer look:
Next Line:
The keyword class is used to declare that a new class is
being defined and Example is an identifier that is the name
of the class.
The entire class definition, including all of its members, will
be between he opening curly brace ({) and the closing curly
brace (}).
The next line in the program is the single-line comment.
27
Introduction to Java
A closer look:
Next Line:
The next line of the code is:
Public static void main (String args[ ])
This line begins the main () method. This is the line at which
the program will begin executing
public keyword is an access specifier, which allows the
programmer to control the visibility of class members.
static keyword allows main() to be called without having to
instantiate a particular instance of the class.
void tells the compiler that main() does not return a value.
28
Introduction to Java
A closer look:
Next Line:
String args [ ] is a parameter inside main().
It declares a parameter named args, which is an array of
instances of the class String.
args receives any command-line arguments present when the
program is executed.
The next line is
System.out.println(“Welcome to java!!!!!!”);
This line outputs the string “Welcome to java!!!!!” followed
by new-line on the screen.
29
Introduction to Java
A closer look:
Next Line:
Output is accomplished by the built-in println() method.
System is a predefined class that provides access to the
system, and out is the output stream that is connected the
console.
Note that println() statement ends with a semicolon. All
statements in java end with a semicolon.
30
Introduction to Java
Second Example:
Example2.java:
This example demonstrates the use of variable.
A variable is a named memory location that may be
assigned a value by you.
class Example2 {
public static void main (String args [ ])
{
int num; //this declares a variable called num
num = 200; // this assigns num the value 200
System.out.println(“This is num: “ +num);
num = num*2;
System.out.print(“The value of num *2 is “);
System.out.println(num);
}
31
}
Data types, operators
Constants, Variable:
Constants:
Constants in Java refers to fixed values that do not change
during the execution of a program.
Java supports:- Syntex for declaring constant:
Integer Constants final data_type constant_name
Real Constants
Single Character Constants
String Constants
Backslash Character Constants
32
Data types, operators
Constants, Variable:
Constants:
Java Constants
33
Data types, operators
Constants, Variable:
Constants:
Integer Constants:
It refers to sequence of digits.
Three types of integers:-
Decimal
Octal
Hexadecimal
String Constants:
A string constant is a sequence of characters enclosed
between double quotes.
The characters may be alphabets, digits, special characters
and blank spaces.
Ex: “nift” “2010” “JAVA” “!....?” “6+4”
37
Data types, operators
Constants, Variable:
Constants:
Backslash Character Constants:
Java supports some special backslash character constants
that are used in output methods also known as escape
sequences.
‘\b’ -- back space
‘\f’ -- form feed (printer devices)
‘\n’ -- new line
‘\r’ -- carriage return
‘\t’ -- horizontal tab
‘\’’ -- single quote
‘\”’ -- double quote
‘\\’ -- backslah
38
Data types, operators
Constants, Variable:
Variables:
Variable is an identifier denotes a storage location used to store a data
value.
Variable name can be chosen by the programmer in a meaningful way
so as to reflect what it represents in the program.
Variable names may consists of alphabets, digits, the underscore and
dollar characters, subject to the following conditions:-
They must not begin with a digit
Uppercase and lowercase are distinct
Should not be a keyword
White space is not allowed
Variable names can be of any length
39
Data types, operators
Constants, Variable:
Data types:
Java is strongly Typed language.
Java’s safety and robustness comes from this fact.
Every variable in Java has a data type that specifies the size and type of
value that can be stored.
DATA TYPES IN JAVA
Primitive Non-Primitive
(intrinsic) (Derived)
40
Data types, operators
Constants, Variable:
Data types:
Java defines eight simple types of data: byte, short, int, long,
char, float, double, and boolean. These can be put in four
groups.
Integers: byte, short, int, long – for whole valued signed
numbers
Floating-point: float and double – numbers with fractional
precision
Character: char – symbols in character set, like letters and
numbers
Boolean: boolean – for representing true / false
41
Data types, operators
Constants, Variable:
Data types:
Integers:
byte, short, int, and long
unsigned integer type was eliminated in Java
Name Width Range
long 64 -9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
int 32 -2,147,483,648 to 2,147,483,647
Short 16 -32,768 to 32,767
byte 8 -128 to 127
We can append letter ‘L’ or ‘l’ at the end of the number for long data type
42
Data types, operators
Constants, Variable:
Data types:
Floating Point:
Also known as real numbers
Expressions require fractional precision.
Name Width Range
double 64 4.9e-324 to 1.8e+308
float 32 1.4e-045 to 3.4e+038
43
Data types, operators
Constants, Variable:
Data types:
Characters:
The data type used to store characters is ‘char’
Java is not same as char in C or C++. Java uses Unicode
to represent characters.
Name Width Range
char 16 0 to 65,536
44
Data types, operators
Constants, Variable:
Data types:
Boolean:
For logical values
It can have only one of two possible values, true or false.
Ex:
boolean c;
boolean d;
45
Data types, operators
Constants, Variable:
Declaration of Variables:
A variable must be declared before it is used in program.
A variable can be used to store a value of any data type.
Declaration does three things,
It tells the compiler what the variable name is
It specifies what type of data the variable will hold
The place of declaration decides the scope of the variable.
46
Data types, operators
Constants, Variable:
Assigning Value to a Variable:
Variable must be given a value after it has been declared
but before it is used in an expression.
It can be done by,
By using an assignment statement.
By using a read statement at runtime
Using Assignment Statement:
variableName = value;
Ex: myinteger = 100;
It is also possible to assign a value to a variable at the time of its declaration
data_type variableName = value;
47
Data types, operators
Constants, Variable:
Assigning Value to a Variable:
Using Read Statement: (JDK 1.4.0)
import java.io.DataInputStream;
class read{
public static void main (String args[])
{
DataInputStream in = new DataInputStream(System.in);
Int intNumber = 0;
Float floatNumber = 0.0;
try{
System.out.println(“Enter an Integer: “);
intNumber = Integer.parseInt(in.readLine());
System.out.println(“Enter a float number: “);
floatNumber = Float.valueOf(in.readLine()).floatValue();
}
Catch (Exception e){ }
System.out.println(“intNumber = “ + intNumber);
System.out.println(“floatNumber = “ + floatNumber);
}
48
}
Data types, operators
Constants, Variable:
Assigning Value to a Variable:
49
Data types, operators
Using Read Statement: (JDK 1.6.0)
import java.io.Console;
class console{
public static void main (String args[])
{
Console console = System.console();
int i=0;
String getpassword = "";
while(i <= 3)
{
getpassword = getpassword+password[i];
i++;
} 50
Data types, operators
Using Read Statement: (JDK 1.6.0)
51
Data types, operators
Constants, Variable:
Scope of Variable:
Java variables are classified into ,
instance variable
class variable
local variable
Ex:
final int LENGTH = 100;
final float PI = 3.14159;
53
Data types, operators
Constants, Variable:
Type Casting:
To store a value of one type into a variable of another type.
The value to be stored by proceeding it with the type name in
parantheses.
type variable1 = (type) variable2;
Ex:
int m = 50;
byte n = (byte) m;
54
Operators and Expressions
55
Operators and Expressions
Arithmetic operators:
Operator Meaning
+ Addition or unary plus
- Subtraction or unary minus
* Multiplication
/ Division
% Modulo division
Integer arithmetic
Real arithmetic
Mixed-mode arithmetic
56
Operators and Expressions
Relational operators :
Operator Meaning
< is less than
<= is less than or equal to
> is greater than
>= is greater than or equal to
== is equal to
!= is not equal to
57
Operators and Expressions
Logical operators :
Operator Meaning
&& logical AND
|| logical OR
! logical NOT
The logical operators && and || are used when we want to form
compound conditions by combining two or more relations.
a > b && x == 10
An expression of this kind is termed as a logical expressions
Yields true or false value according to the truth table
58
Truth Table
op-1 op-2 op-1 && op-2 op-1 || op-2
59
Operators and Expressions
Assignment operators :
In addition to usual assignment operator ‘=‘, java has a set of
‘Shorthand’ assignment operators.
v op= exp;
v – variable
exp – expression
op – binary operator
Statement with simple Statement with Shorthand
assignment operator operator
a =a+1 a += a
a =a-1 a –= a
a = a * (n + 1) a *= (n + 1)
a = a / ( n + 1) a /= ( n + 1)
a =a%b a %= b 60
Operators and Expressions
Increment and Decrement operators :
Operator Meaning
++ increment
-- decrement
62
Operators and Expressions
Bitwise operators :
Operator Meaning
& bitwise AND
! bitwise OR
^ bitwise exclusive OR
~ one’s complement
<< shift left
>> shift right
>>> shift right with zero fill
Used to manipulation of data at values of bit level for testing the
bits, or shifting them to the right or left.
They are not applied to float or double.
63
Operators and Expressions
Special operators :
Instanceof operator
member selection operator (.)
The instanceof is an object reference operator and returns true if
the object on the left-hand side is an instance of the class given on
the right-hand side.
Used to check whether the object belongs to a particular class or
not.
person instanceof student
Dot opeator is used to access the instance variables and methods of
class objects.
personal // reference to the variable age
64
Operators and Expressions
Arithmetic Expressions :
Ex:
x = a * b – c; y = b / c * a; z = b – b / c + d;
66
Operators and Expressions
Precedence of Arithmetic Operators :
An arithmetic expression without any parentheses will be evaluated
from left to right using the rules of precedence of operators.
Operator Description Associability Rank
. Member Selection Left to right 1
() Function call
68
Operators and Expressions
Precedence of Arithmetic Operators :
The basic evaluation procedure includes two left-to-right passes
through the expression.
During the first pass the higher priority operators are applied .
During the second pass the low priority operators are applied.
Ex:
x = 9 – 12 / 3 + 3 * 2 – 1 is evaluated as follows
First pass:
Step 1: x = 9 – 4 + 3 * 2 – 1 (12 / 3 evaluated)
Step 2: x = 9 – 4 + 6 – 1 (3 * 2 evaluated)
Second pass:
Step 3: x = 5 + 6 – 1 (9 – 4 evaluated)
Step 4: x = 11 – 1 (5 + 6 evaluated)
Step 5: x = 10 (11-1 evaluated)
69
Decision Making and Branching
Java’s program control statements can be put into;
1. Selection statements
2. Iteration statements
3. Control statements
Selection statements:
1. ‘if’ statement
2. ‘switch’ statement
70
Decision Making and Branching
Selection statements:
1. ‘if’ statement
The ‘if’ is a powerful decision making
statement used to control the flow of
execution of statements.
The syntax for ‘if’ statement:
if (test_expression)
False
Test expression
True
71
Decision Making and Branching
Selection statements:
1. ‘IF’ statement
The if statement may be implemented in different forms depending
on the complexity of conditions to be tested.
1. Simple IF statement
2. If . . . . ELSE statement
4. ELSE IF ladder
72
Decision Making and Branching
Selection statements:
Entry
1. Simple ‘IF’ statement
if (test_expression)
{
statement-block; True
Test expression
}
statement – x;
statement-block
False
Statement – x
Next statement
73
Decision Making and Branching
Selection statements:
1. ‘IF’ statement
Example:
import java.io.Console;
class ifexample{
public static void main (String args[]){
Console console = System.console( );
int inputnum = Integer.parseInt(console.readLine(" Input number: "));
System.out.println(“Even numbers from 1 to “ + inputnum);
for(int i = 0; i <=inputnum; i++)
{
if(i %2 == 0)
{
System.out.println(i);
}
}
}
}
74
Decision Making and Branching
Selection statements:
Entry
1. IF ….. ELSE statement
if (test_expression)
{
True-block statement (s);
True False
}
Else Test expression
{
False-block statement (s)
}
statement – x;
True-block False-block
statement statement
Statement – x
Next statement
75
Decision Making and Branching
Example:
import java.io.Console;
class ifelseexample{
Conditional Operator:
83
Decision Making and Looping
Conditional Operator:
84