Escolar Documentos
Profissional Documentos
Cultura Documentos
JAVA
What Is Java?
Java:
Is a platform and an object-oriented
language
Was originally designed by Sun
Microsystems for consumer electronics
Contains a class library
Uses a virtual machine for program
execution
JAVA BUZZWORDS
SIMPLE
OBJECT-ORIENTED
ROBUST
MULTITHREADED
ARCHITECTURE-NEUTRAL
INTERPERTED AND HIGH PERFORMANCE
DISTRIBUTED
DYNAMIC
SIMPLE
Java was designed to be easy for
professional programmer to lean and
use effectively.
Java inherits the c/c ++ syntax and many
of object-oriented features.
OBJECT-ORIENTED
Java was not designed to be source-code
compatible with any other language.
Everything is an object
ROBUST
Multiplatform environment of the web
pages extraordinary demands on a
program, because the program must
execute reliably in a variety of systems.
Failure: Memory management
Mishandled exceptional conditions (run
time error).
ARCHITECTURE-NEUTRAL
A central issue for the java designers was
the code longevity and portability.
Goal was write once;
Run any where, any time ,forever.
DISTIBUTED AND DYNAMIC
Java is designed for the distributed
environment of the internet because it
handles TCP/IP. Protocols.
Java also supports Remote Method
Invocation (RMI)
This features enables a program to invoke
methods across a network.
JAVA
JAVA CHANGED THE INTERNET
JAVA APPLETS
SECUTRITY
PORTABILITY
APPLETS
Java applets:
An applet is special kind of java program
that is designed to be transmitted over
the internet and automatically executed
by a java-compatible web browser.
SECUTRITY
Security
Java achieved this protection by confining
an applet to java execution environment
and not allowing it access to other parts
of the computer.
PORTABILITY
Portability
Portability is a major aspect of internet
because there are many different types
of computers and operating systems
connected to it.
An Object-Oriented Approach
Objects and classes
An object is a run-time representation of a thing.
A class is a static definition of things.
Class models elaborate:
Existing classes and objects
Behaviour, purpose, and structure
Relationships between classes
Relationships between run-time objects
Same models exist throughout the project.
Integration
Analysis Design Implementation
and testing
CLASS MODELS
Platform Independence
Java source code is stored as text in a .java file.
The .java file is compiled into .class files.
A .class file contains Java bytecodes (instructions).
The bytecodes are interpreted at run time.
The Java .class file is the executable code.
Compile JVM
(javac) (java)
JVM
Application
How Does JVM Work?
The class loader loads all required classes.
JVM uses a CLASSPATH setting to locate class
files.
JVM Verifier checks for illegal bytecodes.
JVM Verifier executes bytecodes.
JVM may invoke a Just-In-Time (JIT) compiler.
Memory Manager releases memory used by the
dereferenced object back to the OS.
JVM handles Garbage collection.
Garbage collection
Java the objects are dynamically allocated
by using the new operator.
The objects must be manually release by
use of an delete operator
But java take it deallocation of memory
automatically .This is accomplished by
garbage collections.
Reference object.
Using the Appropriate
Development Kit
Java2 comes in three sizes:
J2ME (Micro Edition): Version specifically
targeted at the consumer space
J2SE (Standard Edition): Complete
ground-up development environment for
the Internet
J2EE (Enterprise Edition): Everything in
the J2SE plus an application server and
prototyping tools
Object-Oriented Principles
Object-Oriented
programming
Object-Oriented programming(o o p)s
Oops organizes a program around its
data (that is objects) a set of well
defined interface to that data.
An object-oriented program can be
characterized as data controlling access
to the code.
oops
ABSTRACTION
ENCAPSULATION
INHERITANCE
POLYMORPHISM
ABSTRACTION
To execute
prompt> a .class
java SayHello file:
Hello world
prompt>
Title: Blue
Moon
Type
Identifier
int myAge; Initial value
boolean isAMovie;
float maxItemCost = 17.98F;
Declaring Variables
Basic form of variable declaration:
type identifier [ = value];
}
GETTING USER INPUT
import java.util.Scanner;
public class calcu {
public static void main (String args[]){
Scanner val1 = new Scanner(System.in);
double fnum, snum, answer;
System.out.println("Enter the first num:");
fnum = val1.nextDouble();
System.out.println("Enter the second num:");
snum = val1.nextDouble();
answer = fnum + snum;
System.out.println(answer);
}
}
DATA TYPE,VARIABLES AND
ARRAYS
Primitive data types
Byte
Short
Int
Long
Char
Float
Double
Boolean
INTEGERS
Long 64
Long is signed 64 bit type and is used for
where an int type is not large enough to
hold the desired value.
The range of long is quite large.
public class Light {
// compute distance light travels using long variables.
public static void main(String[] args) {
int lightspeed;
long days;
long seconds;
long distance;
//aproximate speed of the light in miles per second
lightspeed = 186000;
days = 1000;
seconds = days * 24 * 60 * 60 ;
distance = lightspeed *seconds;
System.out.print("In " +days);
System.out.print(" days light will travel about");
System.out.println(distance + " miles");
Byte
The smallest integer type is byte.
This is a singed 8-bit type has a range form
-128 to 127.
Byte variables are declared by use of the
byte keyword.
Example
Byte b,c;
Short
Short is 16-bit type it range from -32768 to
32767
Example short s;
Int
The most commonly used integer type is
int range -2147483648 to 2147483647
Float
32 bits range 1.4e-045 to 3.4e+038
Double
64 bits store range 4.9e-324 to 1.8e+308
Characters
Java char is 16-bit type The range of char
is 0 65,536
There are not negative char
Type conversion and casting
If the 2 types are compatible,java performs automatic
conversion.
For example, an int value can be assigned to a long
variable.
Int x=5;
Long y=x; //OK
However, not all types are compatible, and thus not all
type conversions are implicitly allowed.
For example, there is no conversion defined from
double to byte.
Byte z= 15.2 //ERROR!
Examining Conversions and
Casts
Java automatically converts a value of one
numeric type to a larger type.
byte
short
int
char long
Java doesshort
not automatically downcast.
byte int long
char
Using Arrays and
Collections
What Is an Array?
An array is a collection of variables of the same type.
Each element can hold a single item.
Items can be primitives or object references.
The length of the array is fixed when it is created.
[0] 1
[0] Action
[1] 2
[1] Comedy
[2] 4
[2] Drama
[3] 8
Creating an Array of
Primitives
Null
1. Declare the array: arrayName
type[] arrayName;
or
type arrayName[]; 0
arrayName
0
0
type is a primitive, such as int and so on.
2. Create the array object:
// Create array object syntax 1
arrayName
arrayName = new type[size]; 2
3. Initialize the array elements 4
(optional).
Declaring an Array of
Primitives
Create a variable to reference the array object:
powers null
ClassName[] arrVar;
arrVar
or null
ClassName arrVar[];
null
null
2. Create the array object:
arrVar
Action
// Create array object syntax
Comedy
arrVar = new ClassName[size];
Drama
System.out.println(i[1]);
}
public class arrayexamples2 {
public static void main(String[ ] args) {
int i[ ]={34,56,76,78,45,334,};
System.out.println(i[2]);
}
}
public class arraytableexample3 {
public static void main(String[] args) {
System.out.println("Index\tValue");
int i[ ]={34,56,76,78,45,334,};
[2] 0 0
[3] 0 0
//demonstrate a two dimensional array.
class twodarray {
public static void main(String args[]) {
int x[ ][ ]=new int[4][5];
int i,j,k=0;
for(i=0;i<4;i++)
for(j=0;j<5;j++)
{
x[i][j]= k;
k++;
}
for(i=0;i<4;i++)
{
for(j=0;j<5;j++)
System.out.print(x[i][j] +" ");
System.out.println();
}
}
}
Java operators
Categorizing Operators
There are five types of operators:
unary
prefix
Postfix
Infix binary operators
Ternary operators
Categorizing Operators
The built in java operators can be
grouped into:
Assignment
Arithmetic
Integer bitwise
Relational
Boolean
Using the Assignment
Operator
The result of an assignment operation is a value and
can be used whenever an expression is permitted.
The value on the right is assigned to the identifier
on the left:
int var1 = 0, var2 = 0;
var1 = 50; // var1 now equals 50
var2 = var1 + 10; // var2 now equals 60
int a, b, c, d, e;
a = 2 + 2; // addition
b = a * 3; // multiplication
c = b - 2; // subtraction
d = b / 2; // division
e = b % 2; // returns the remainder of division
Incrementing and
Decrementing Values
The ++ and -- operators increment and
decrement by 1, respectively:
int var1 = 3;
var1++; // var1 now equals 4
Selection Transfer
Using Flow Control in Java
Each simple statement terminates with a
semicolon (;).
Group statements by using the braces { }.
Each block executes as a single statement within
the flow of control structure.
{
boolean finished = true;
System.out.println("i = " + i);
i++;
}
Using the if Statement
if ( boolean_expr )
statement1;
General:
[else
statement2];
if (i % 2 == 0)
System.out.println("Even");
Examples: else
System.out.println("Odd");
if (i % 2 == 0) {
System.out.print(i);
System.out.println(" is even");
}
Nesting if Statements
if (speed >= 25)
if (speed > 65)
System.out.println("Speed over 65");
else
System.out.println("Speed >= 25 but <= 65");
else
System.out.println("Speed under 25");
case constant_expr1:
statement1;
break;
The switch
case constant_expr2: statement is useful
statement2; when selecting an
break; action from several
[default: alternative integer
statement3;] values.
} Integer_expr
must be byte, int,
char, or short.
More About the switch
Statement
switch (choice) {
case labels
case 37:
must be
System.out.println("Coffee?");
constants.
Use break break;
to jump out
of a switch. case 45:
It is System.out.println("Tea?");
recommend break;
ed to always
provide a default:
default. System.out.println("???");
break;
}
Looping in Java
There are three types of loops in Java:
while
dowhile
for
All loops have four parts:
Initialization
Iteration condition
Body
Termination
Using the while Loop
while is the simplest loop statement and
contains the following general form:
while ( boolean_expr )
statement;
Example: int i = 0;
while (i < 10) {
System.out.println("i = " + i);
i++;
}
Using the dowhile Loop
dowhile loops place the test at the
end: do
statement;
while ( termination );
int i = 0;
Example:
do {
System.out.println("i = " + i);
i++;
} while (i < 10);
Using the for Loop
for loops are the most common loops:
for ( initialization; termination; iteration )
statement;
Example:
Exception object
Handler
for this
Yes exception? No
Advantages of Java Exceptions: Separating
Error Handling Code
In traditional programming, error handling often
makes code more confusing to read.
Java separates the details of handling
unexpected errors from the main work of the
program.
The resulting code is clearer to read and,
therefore, less prone to bugs.
Advantages of Java Exceptions:
Passing Errors Up the Call Stack
Super (parameter-list)
1.Super keyword is used to call immediate
parent.
2.Super keyword can be used with instance
members i.e., instance variables and instance
methods.
3.Super keyword can be used within
constructor to call the constructor of parent
class.
OK now lets practically implement this points
of super keyword.
class base
{
int a = 100;
}
Superclass
InventoryItem
Subclasses
Movie Game Vcr
Example of Inheritance
The InventoryItem class defines
methods and variables.
InventoryItem
Movie
Specifying Additional
Methods
The superclass defines methods for all
types of InventoryItem.
The subclass can specify additional
methods that are specific to Movie.
public class InventoryItem {
public float calcDeposit()
public String calcDateDue()
public class Movie extends InventoryItem {
public void getTitle()
public String getLength()
Overriding Superclass
Methods
A subclass inherits all the methods of its
superclass.
The subclass can override a method with
its own specialized version.
The subclass method must have the same
signature and semantics as the superclass
method.
class trainer
{
void communicationskill()
{
System.out.println("Trainer 's communication should be remarkable");
}
}
class javatrainer extends trainer
{
void communicationskill()
{
System.out.println("Trainer 's communication is good");
}
}
class skills
{
public static void main(String a[])
{
javatrainer jt=new javatrainer();
jt.communicationskill();
}
}
Invoking Superclass
Methods
If a subclass overrides a method, then it
can still call the original superclass
method.
Use super.method() to call a
superclass method from the subclass.
Treating a Subclass as Its
Superclass
A Java object instance of a subclass is assignable to its
superclass definition.
You can assign a subclass object to a reference that is
declared with the superclass.
The compiler treats the object via its reference (that is, in
terms of its superclass definition).
The JVM run-time environment creates a subclass
object, executing subclass methods, if overridden.
public static void main(String[] args) {
InventoryItem item = new Vcr();
double deposit = item.calcDeposit();
}
Using the instanceof
Operator
You can determine the true type of an
object by using an instanceof operator.
An object reference can be downcast to
the correct type, if necessary.
public void aMethod(InventoryItem i) {
if (i instanceof Vcr)
((Vcr)i).playTestTape();
}
Limiting Methods and
Classes with final
You can mark a method as final to
prevent it from being overridden.
public final boolean checkPassword(String p) {
}
Youclass
public final can mark
Color { a whole class as final to
prevent it from being extended.
}
Summary
In this lesson, you should have
learned the following:
A subclass inherits all the variables and
methods of its superclass.
You can specify additional variables and
methods and override methods.
A subclass can call an overridden
superclass method by using super.
Polymorphism ensures that the correct
version of a method is called at run time.