Professional Documents
Culture Documents
1
2
Javas History
Developed by James Gosling and team at
Sun Microsystems
The java language project initiated in june 1991.
Originally designed for small, embedded systems in
electronic appliances like set-top boxes.
Originally called Oak
Renamed as java in 1995
Sun microsystems was acquired by Oracle Corporation
in 27-jan-2010
3
Java Versions
source code
(programming
language Programmers write
instructions) this.
Compilers
compile source
code into object
code.
object code
(binary Computers run this.
instructions)
8
Java source
code
Java compilers
compile source code
into bytecode.
bytecode
When a Java program
is run, the JVM
translates bytecode to
object code.
object code
9
Java Is Architecture-
Neutral
Java Is Portable
Java's Performance
Java Is Multithreaded
Java Is Dynamic
16
Characteristics of Java
Java Is Simple
Java Is Object-
Oriented
Java Is Distributed
Java Is Interpreted
Java Is Robust
Java Is Secure Write once, run anywhere
Java Is Architecture-
With a Java Virtual Machine
Neutral (JVM), you can write one
Java Is Portable program that will run on any
Java's Performance platform.
Java Is Multithreaded
Java Is Dynamic
17
Characteristics of Java
Java Is Simple
Java Is Object-
Oriented
Java Is Distributed
Java Is Interpreted
Java Is Robust
Java Is Secure
Java Is Architecture- Because Java is architecture
Neutral neutral, Java programs are
Java Is Portable portable. They can be run on any
platform without being
Java's Performance recompiled.
Java Is Multithreaded
Java Is Dynamic
18
Characteristics of Java
Java Is Simple
Java Is Object-
Oriented
Java Is Distributed
Java Is Interpreted
Java Is Robust
Java Is Secure
Java Is Architecture- The execution speed of Java
Neutral programs improved
Java Is Portable significantly due to the
introduction ofJust-In Time
Java's Performance Compilation(JIT)
Java Is Multithreaded They can be run on any
platform without being
Java Is Dynamic recompiled.
19
Characteristics of Java
Java Is Simple
Java Is Object-
Oriented
Java Is Distributed
Java Is Interpreted
Java Is Robust
Java Is Secure
Java Is Architecture-
Neutral Allows you to write programs that
do many things simultaneously.
Java Is Portable Multithread programming is
Java's Performance smoothly integrated in Java,
whereas in other languages you
Java Is Multithreaded
have to call procedures specific to
Java Is Dynamic the operating system to enable
multithreading.
20
Characteristics of Java
Java Is Simple
Java Is Object-
Oriented
Java Is Distributed
Java Is Interpreted
Java Is Robust
Java Is Secure
Java Is Architecture-
Neutral
Java Is Portable Java programs carry with them
substantial amount of run time
Java's Performance information
Java Is Multithreaded Java resolves accesses to object at
runtime
Java Is Dynamic
21
What is OOP?
Conventional programming(process-oriented
model)
This approach characterizes
A program as a series of linear steps (that is,
code).
The process-oriented model can be thought of as
code acting on data.
Abstraction
Abstraction is a powerful methodology to manage
complex systems.
Abstraction is managed by well-defined objects and
their hierarchical classification.
Abstraction in Java or Object orientedprogramming
is a way to seperate implementationfrom interface
For example a car in itself is a well-defined object,
which is composed of several other smaller objects
like a gearing system, steering mechanism, engine,
which are again have their own subsystems. But for
humans car is a one single object, which can be
managed by the help of its subsystems, even if
their inner details are unknown.
25
Encapsulation
Encapsulation means putting together all the
variables and the methods into a single unit
called Class " T h e D o u g h n u t D ia g r a m "
S h o w in g t h a t a n o b je c t h a s
The data (state) of p r iv a t e s t a t e a n d
b e h a v io u r . S t a t e
p u b l ic
c a n o n ly b e
an object is private
c h a n g e d b y in v o k in g s o m e
b e h a v io u r
it cannot be P r iv a t e D a t a
accessed directly.
The state can only
be changed P u b li c I n t e r f a c e
through its
behaviour,
otherwise known as
its public interface
26
Encapsulation
Looking at the example of a power steering
mechanism of a car.
Power steering of a car is a complex system,
which internally have lots of components tightly
coupled together, they work synchronously to
turn the car in the desired direction. It even
controls the power delivered by the engine to the
steering wheel. But to the external world there is
only one interface is available and rest of the
complexity is hidden. Moreover, the steering unit
in itself is complete and independent. It does not
affect the functioning of any other mechanism.
Inheritance
Inheritance is the ability to define a new class in
terms of an existing class
The existing class is the parent, base or superclass
The new class is the child, derived or subclass
The child class inherits all of the attributes and
behaviour of its parent class
It can then add new attributes or behaviour
Or even alter the implementation of existing behaviour
Inheritance is therefore another form of code
reuse
28
Hello.java
/*
Hello World, first application, only output.
*/
import java.io.*;
class Hello{
public static void main (String args []) {
System.out.println(Hello World\n);
} //end main
}//end class
31
To compile:
javac Hello.java
To run:
java Hello
Note : - Set Environment variables To run java programs anywhere
Set path to JDK bin directory
set path=C:\Program Files\Java\jdk1.8.0_31\bin
Set classpath to include the current directory
Add a new system variable Classpath . set classpath=.;
32
Notice:
Java is CASE SENSITIVE!!
File name has to be the same as class name in
file.
Need to import necessary class definitions
All statements in Java end with a semicolon.
Whitespace is ignored by compiler
In Java, all code must reside inside a class.
33
A closer look
1. Multi line
/* comment
Hello World, first application, only output.
*/
import java.io.*;
class Hello{
public static void main (String args []) {
System.out.println(Hello World);
} //end main
2. Single line
}//end class comment
3. Documentation
comment
34
/*
Hello World, first application, only output.
*/ Similar to
#include<stdio.h>
Access to all the classes
import java.io.*;
defined in java.io
class Hello{
public static void main (String args []) {
System.out.println(Hello World);
} //end main
}//end class
35
/*
Hello World, first application, only output.
*/ Keyword class to
declare a new
import java.io.*; class
Name of the class
class Hello{
public static void main (String args []) {
System.out.println(Hello World);
} //end main
}//end class
36
/*
Hello World, first application, only output.
*/
Execute statement
class Hello{
public static void main (String args []) {
System.out.println(Hello World);
} //end main
}//end class
37
public static void main (String args
[])
String args[ ]
String args[ ] declares a parameter named
args, which is an array of instances of the class
String.
System.out.println(Hello
World);
class Example2 {
public static void main(String args[]) {
int num; // this declares a variable called
num
num = 100; // this assigns num the value 100
Integers
Byte
Variables of type byte are especially useful when
youre working with a stream of data from a
network or file.
For raw binary data that may not be directly
compatible with Javas other built-in types.
Short
It is probably the least-used Java type
This type is mostly applicable to 16-bit computers,
which are becoming increasingly scarce.
46
Int
The most commonly used integer type is int.
Commonly employed to control loops and to index
arrays.
Long
Occasions where an int type is not
Large enough to hold the desired value.
47
Floating-Point
Java implements the standard (IEEE754) set of
floating-point types and operators.
Float
Variables of type float are useful when you need a
fractional component, but dont require a large
degree of precision.
Double
All math functions, such as sin( ), cos( ), and sqrt(
), return double values.
When you need to maintain accuracy over many
iterative calculations, or are manipulating large-
valued numbers, double is the best choice.
48
Characters
In C/C++, char is 8 bits wide.
Java uses Unicode to represent characters. It
requires 16 bits.
Unicode defines a fully international character set
that can represent all of the characters found in
all human languages
The ASCII character set occupies the first 127
values in the Unicode character set.
Booleans
Java has a simple type, called boolean, for
logical values.
It can have only one of two possible values, true
or false.
Demonstrate double
variables
// Compute the area of a circle.
class Area {
public static void main(String args[]) {
double pi, r, a;
a = pi * r * r; // compute area
System.out.println("Area of circle is " + a);
}
}
51
Demonstrate boolean
variables.
class BoolTest {
public static void main(String args[]) {
boolean b;
b = false;
System.out.println("b is " + b);
b = true;
System.out.println("b is " + b);
class CharDemo {
public static void main(String args[]) {
char ch1, ch2;
ch1 = 88; // code for X
ch2 = 'Y';
Floating-Point Literals
They can be expressed in either standard or
scientific notation.
Boolean Literals
Boolean : In Java, they can only be assigned to
variables declared as boolean, or used in
expressions with Boolean operators.
Character Literal
For example:
String Literals
String literals in Java are specified like they are in
most other languages
By enclosing a sequence of characters between a
pair of double quotes.
Eg:- Hello World
58
Variables
The variable is the basic unit of storage in a Java
program.
Declaring a Variable
type identifier [ = value][, identifier [=
value] ...] ;
The type is one of Javas atomic types, or the
name of a class or interface.
The identifier is the name of the variable.
59
Dynamic Initialization
class DynInit {
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);
}
}
60
class Scope
{
public static void main(String args[])
{
int x; // known to all code within main
x = 10;
if(x == 10)
{ // start new scope
int y = 20; // known only to this block
// x and y both known here.
System.out.println("x and y: " + x + " " + y);
x = y * 2;
}
// y = 100; // Error! y not known here. x is still known here.
System.out.println("x is " + x);
}
} Note : -Nested blocks can have access to its outermos
62
Demonstrate lifetime of a
variable.
class LifeTime
{
public static void main(String args[])
{
int x;
for(x = 0; x < 3; x++)
{
int y = -1; // y is initialized each time block is entered
System.out.println("y is: " + y); // this always prints -1
y = 100;
System.out.println("y is now: " + y);
}
}
}
63
Type Conversion
Widening conversion - Java automatic type conversion
will take place iff
a. Two type are compactable
b. The destination type > source type
Eg:- int byte
Numeric types are compactable but not compactable with
char,bool etc..
Narrowing conversion
A cast is simply an explicit type conversion
(target-type) value
Eg:- byte int
Eg 1:- b = (byte) i;
Eg 2:- i = (int) d;
65
Allocating an array
Syntax 1 : var-name=new type[size];
Eg : month_days=new int[12];
for(i=0;i<5;i++)
result=result+num[i];
System.out.println(result/5);
}
}
Multi Dimensional Arrays
Array of arrays
Syntax : type array-name[][]=new type[row][col]
Eg : int towD[][]=new int[4][5];
[0][0]
[1][0] [1][1]
x=42;
y=++x; // y will be ??
x=42;
y=x++; // y will be ??
0 0 1 0 1 0 1 0
2^1+2^3+2^5
2+8+32=42
Eg: -
byte b=-42;
42 is represented as 00101010
a. Inver 1s and zeros =11010101
b. Add 1 to the result 11010101+
1
Result= 11010110
To decode
Operator Result
& Logical AND
| Logical OR
^ Logical XOR
|| Short circuit OR
&& Short Circuit AND
! Logical Unary NOT
&= AND assignment
|= OR Assignment
^= XOR Assignment
== Equal to
!= Not Equal to
?: Ternary if then else
A B A|B A&B A^B !A
FALS FALS
E E
TRUE FALS
E
FASL TRUE
E
TRUE TRUE
Short circuit Logical
Operators
The && and || operators "short-circuit",
meaning they don't evaluate the right hand side
if it isn't necessary.
The & and | operators, when used as logical
operators, always evaluate both sides.
int x,y,z;
x=y=z=100;
Ternary(Three way) operator
Precedence
1 () [] .
2 ++ -- ~ !
3 * / %
4 + -
5 >> >>> <<
6 > >= < <=
7 == !=
8 &
9 ^
10 |
11 &&
12 ||
13 ?:
14 = OP=
Control Statements
Cause the flow of execution
3 categories
Selection
Iteration
Jump
Selection Control Statement
Allows to choose different paths of execution
based on o/p of an expression or state of a
variable according to run time conditions
if
switch
if
if(condition)
statement1;
else
statement2;
Each statement may be single or compound
enclosed in curly brackets
Condition is an expression that returns a boolean
value
Else clause is optional
Eg:- int a,b,c;
if(a>b)
c=a;
else
If using a boolean value
boolean flag;
if(flag)
..
else
..
Nested if
if(i==10)
{
if(j<20)
a=b;
if(k>100)
c=d;
else
a=c;
}
else
a=d;
If-else-if ladder
if(condition)
statement;
else if(condition)
statement;
.
.
else
statement;
while(i<10)
{
System.out.println(a[i]);
i++;
}
}
}
do while
// body of loop
} while(condition);
// body of loop
}
Declaring loop control
variables inside the for loop
Possible to declare the variable inside the
initialization portion of for
Eg:- for(int i=0; i<10;i++)
{
}
Scope of this variable is limited to the for block
Using comma
It is possible to include more than one statement in
initialization and iteration part of for loop
class Comma {
public static void main(String args[])
{
int first, second ;
for ( first = 0, second = 10 ; first < second ; first++,
second-- )
{
System.out.println( first + " " + second ) ;
}
}
}
Some loop variations
boolean done=false;
int i=0;
for(;!done;)
{
System.out.println(i);
if(i==10)
done=true;
i++;
}
Infinite loop
for(; ;)
{
//body of the loop
}
Nested loops
for(i=0;i<m;i++)
for(j=i;j<n;j++)
{
//body of the inner loop
}
Jump Statements
Break, continue and return
Break
if(i==10)
break;
System.out.println(i);
}
}
Note : -In case of nested loops break only terminates the inne
}
Break as a form of goto
Java does not have goto statement
Instead break can be used to tell where the
execution exactly should resume
Labeled break
Syntax :- break label;
Label is a java identifier with a column
12
7
Note:-
When this form of break executes, control is
transferred out of the named block of code.