Você está na página 1de 13

JAVA - QUICK GUIDE

http://www.tutorialspoint.com/java/java_quick_guide.htm

Copyright tutorials point.com

What is Java?
Java is:
Object Orient ed
Plat form independent :
Simple
Secure
Archit ect ural- neut ral
Port able
Robust
Mult i-t hreaded
Int erpret ed
High Performance
Dist ribut ed
Dynamic

Java Environment Set up:


Java SE is freely available from t he link Download Java. So you download a version based on your
operat ing syst em.
You can refer t o inst allat ion guide for a complet e det ail.

Java Basic Synt ax:


Object - Object s have st at es and behaviors. Example: A dog has st at es-color, name, breed
as well as behaviors -wagging, barking, eat ing. An object is an inst ance of a class.
Class - A class can be defined as a t emplat e/ blue print t hat describe t he behaviors/st at es
t hat object of it s t ype support .
Metho ds - A met hod is basically a behavior. A class can cont ain many met hods. It is in
met hods where t he logics are writ t en, dat a is manipulat ed and all t he act ions are execut ed.
Instant Variables - Each object has it s unique set of inst ant variables. An object 's st at e is
creat ed by t he values assigned t o t hese inst ant variables.

First Java Program:


Let us look at a simple code t hat would print t he words Hello World.
public class MyFirstJavaProgram{
/* This is my first java program.
* This will print 'Hello World' as the output
*/
public static void main(String []args){
System.out.println("Hello World"); // prints Hello World
}
}

About Java programs, it is very import ant t o keep in mind t he following point s.

Case Sensitivity - Java is case sensit ive which means ident ifier Hello and hello would have
different meaning in Java.
Class Names - For all class names t he first let t er should be in Upper Case.
If several words are used t o form a name of t he class each inner words first let t er should be in
Upper Case.
Example class MyFirstJavaClass
Metho d Names - All met hod names should st art wit h a Lower Case let t er.
If several words are used t o form t he name of t he met hod, t hen each inner word's first let t er
should be in Upper Case.
Example public void myMethodName()
Pro gram File Name - Name of t he program file should exact ly mat ch t he class name.
When saving t he file you should save it using t he class name (Remember java is case sensit ive)
and append '.java' t o t he end of t he name. (if t he file name and t he class name do not mat ch
your program will not compile).
Example : Assume 'MyFirst JavaProgram' is t he class name. Then t he file should be saved as
'MyFirstJavaProgram.java'
public static vo id main(String args[]) - java program processing st art s from t he main()
met hod which is a mandat ory part of every java program..

Java Ident ifiers:


All Java component s require names. Names used for classes, variables and met hods are called
ident ifiers.
In java t here are several point s t o remember about ident ifiers. They are as follows:
All ident ifiers should begin wit h a let t er (A t o Z or a t o z ), currency charact er ($) or an
underscore (_).
Aft er t he first charact er ident ifiers can have any combinat ion of charact ers.
A key word cannot be used as an ident ifier.
Most import ant ly ident ifiers are case sensit ive.
Examples of legal ident ifiers:age, $salary, _value, __1_value
Examples of illegal ident ifiers : 123abc, -salary

Java Modifiers:
Like ot her languages, it is possible t o modify classes, met hods, et c., by using modifiers. There are
t wo cat egories of modifiers.
Access Mo difiers : default , public , prot ect ed, privat e
No n-access Mo difiers : final, abst ract , st rict fp
We will be looking int o more det ails about modifiers in t he next sect ion.

Java Variables:
We would see following t ype of variables in Java:
Local Variables
Class Variables (St at ic Variables)

Inst ance Variables (Non st at ic variables)

Java Arrays:
Arrays are object s t hat st ore mult iple variables of t he same t ype. However an Array it self is an
object on t he heap. We will look int o how t o declare, const ruct and init ialize in t he upcoming
chapt ers.

Java Enums:
Enums were int roduced in Java 5.0. Enums rest rict a variable t o have one of only a few predefined
values. The values in t his enumerat ed list are called enums.
Wit h t he use of enums it is possible t o reduce t he number of bugs in your code.
For example if we consider an applicat ion for a fresh juice shop it would be possible t o rest rict t he
glass size t o small, medium and Large. This would make sure t hat it would not allow anyone t o order
any size ot her t han t he small, medium or large.

Example:
class FreshJuice{
enum FreshJuiceSize{ SMALL, MEDIUM, LARGE }
FreshJuiceSize size;
}
public class FreshJuiceTest{
public static void main(String args[]){
FreshJuice juice = new FreshJuice();
juice.size = FreshJuice. FreshJuiceSize.MEDIUM ;
System.out.println("Size :" + juice.size);
}
}

No te: enums can be declared as t heir own or inside a class. Met hods, variables, const ruct ors can be
defined inside enums as well.

Java Keywords:
The following list shows t he reserved words in Java. These reserved words may not be used as
const ant or variable or any ot her ident ifier names.
abst ract

assert

boolean

break

byt e

case

cat ch

char

class

const

cont inue

default

do

double

else

enum

ext ends

final

finally

float

for

got o

if

implement s

import

inst anceof

int

int erface

long

nat ive

new

package

privat e

prot ect ed

public

ret urn

short

st at ic

st rict fp

super

swit ch

synchronized

t his

t hrow

t hrows

t ransient

volat ile

while

t ry

void

Comment s in Java
Java support s single line and mult i-line comment s very similar t o c and c++. All charact ers available
inside any comment are ignored by Java compiler.
public class MyFirstJavaProgram{
/* This is my first java program.
* This will print 'Hello World' as the output
* This is an example of multi-line comments.
*/
public static void main(String []args){
// This is an example of single line comment
/* This is also an example of single line comment. */
System.out.println("Hello World");
}
}

Dat a Types in Java


There are t wo dat a t ypes available in Java:
Primit ive Dat a Types
Reference/Object Dat a Types

Primit ive Dat a Types:


There are eight primit ive dat a t ypes support ed by Java. Primit ive dat a t ypes are predefined by t he
language and named by a key word. Let us now look int o det ail about t he eight primit ive dat a t ypes.
byt e
short
int
long
float
double
boolean
char

Reference Dat a Types:


Reference variables are creat ed using defined const ruct ors of t he classes. They are used t o
access object s. These variables are declared t o be of a specific t ype t hat cannot be changed.
For example, Employee, Puppy et c.
Class object s, and various t ype of array variables come under reference dat a t ype.
Default value of any reference variable is null.
A reference variable can be used t o refer t o any object of t he declared t ype or any compat ible
t ype.
Example : Animal animal = new Animal("giraffe");

Java Lit erals:

A lit eral is a source code represent at ion of a fixed value. They are represent ed direct ly in t he code
wit hout any comput at ion.
Lit erals can be assigned t o any primit ive t ype variable. For example:
byte a = 68;
char a = 'A'

St ring lit erals in Java are specified like t hey are in most ot her languages by enclosing a sequence of
charact ers bet ween a pair of double quot es. Examples of st ring lit erals are:
"Hello World"
"two\nlines"
"\"This is in quotes\""

Java language support s few special escape sequences for St ring and char lit erals as well. They are:
No tatio n

Character represented

\n

Newline (0x0a)

\r

Carriage ret urn (0x0d)

\f

Formfeed (0x0c)

\b

Backspace (0x08)

\s

Space (0x20)

\t

t ab

\"

Double quot e

\'

Single quot e

\\

backslash

\ddd

Oct al charact er (ddd)

\uxxxx

Hexadecimal UNICODE charact er (xxxx)

Java Access Modifiers:


Java provides a number of access modifiers t o set access levels for classes, variables, met hods and
const ruct ors. The four access levels are:
Visible t o t he package. t he default . No modifiers are needed.
Visible t o t he class only (privat e).
Visible t o t he world (public).
Visible t o t he package and all subclasses (prot ect ed).

Java Basic Operat ors:


Java provides a rich set of operat ors t o manipulat e variables. We can divide all t he Java operat ors int o
t he following groups:

The Arit hmet ic Operat ors:


Operato r

Descriptio n

Example

Addit ion - Adds values on eit her side of t he operat or

A + B will give
30

Subt ract ion - Subt ract s right hand operand from left hand operand

A - B will give 10

Mult iplicat ion - Mult iplies values on eit her side of t he operat or

A * B will give
200

Division - Divides left hand operand by right hand operand

B / A will give 2

Modulus - Divides left hand operand by right hand operand and


ret urns remainder

B % A will give
0

++

Increment - Increase t he value of operand by 1

B++ gives 21

--

Decrement - Decrease t he value of operand by 1

B-- gives 19

The Relat ional Operat ors:


Operato r

Descriptio n

Example

==

Checks if t he value of t wo operands are equal or not , if yes t hen


condit ion becomes t rue.

(A == B) is
not t rue.

!=

Checks if t he value of t wo operands are equal or not , if values are not


equal t hen condit ion becomes t rue.

(A != B) is
t rue.

>

Checks if t he value of left operand is great er t han t he value of right


operand, if yes t hen condit ion becomes t rue.

(A > B) is
not t rue.

<

Checks if t he value of left operand is less t han t he value of right


operand, if yes t hen condit ion becomes t rue.

(A < B) is
t rue.

>=

Checks if t he value of left operand is great er t han or equal t o t he value


of right operand, if yes t hen condit ion becomes t rue.

(A >= B) is
not t rue.

<=

Checks if t he value of left operand is less t han or equal t o t he value of


right operand, if yes t hen condit ion becomes t rue.

(A <= B) is
t rue.

The Bit wise Operat ors:


Operato r

Descriptio n

Example

&

Binary AND Operat or copies a bit t o t he result if it


exist s in bot h operands.

(A & B) will give 12 which is


0000 1100

Binary OR Operat or copies a bit if it exist s in eat her


operand.

(A | B) will give 61 which is


0011 1101

Binary XOR Operat or copies t he bit if it is set in one


operand but not bot h.

(A ^ B) will give 49 which is


0011 0001

Binary Ones Complement Operat or is unary and has


t he efect of 'flipping' bit s.

(~A ) will give -61 which is


1100 0011 in 2's complement
form due t o a signed binary
number.

<<

Binary Left Shift Operat or. The left operands value is


moved left by t he number of bit s specified by t he
right operand.

A << 2 will give 240 which is


1111 0000

>>

Binary Right Shift Operat or. The left operands value


is moved right by t he number of bit s specified by
t he right operand.

A >> 2 will give 15 which is


1111

>>>

Shift right zero fill operat or. The left operands value
is moved right by t he number of bit s specified by
t he right operand and shift ed values are filled up
wit h zeros.

A >>>2 will give 15 which is


0000 1111

The Logical Operat ors:


Operato r

Descriptio n

Example

&&

Called Logical AND operat or. If bot h t he operands are non zero t hen t hen
condit ion becomes t rue.

(A && B)
is false.

||

Called Logical OR Operat or. If any of t he t wo operands are non zero t hen
t hen condit ion becomes t rue.

(A || B) is
t rue.

Called Logical NOT Operat or. Use t o reverses t he logical st at e of it s


operand. If a condit ion is t rue t hen Logical NOT operat or will make false.

!(A && B)
is t rue.

The Assignment Operat ors:


Operato r

Descriptio n

Example

Simple assignment operat or, Assigns values from right side


operands t o left side operand

C = A + B will
assigne value of A +
B int o C

+=

Add AND assignment operat or, It adds right operand t o t he


left operand and assign t he result t o left operand

C += A is equivalent
to C = C + A

-=

Subt ract AND assignment operat or, It subt ract s right


operand from t he left operand and assign t he result t o left
operand

C -= A is equivalent
to C = C - A

*=

Mult iply AND assignment operat or, It mult iplies right operand
wit h t he left operand and assign t he result t o left operand

C *= A is equivalent
to C = C * A

/=

Divide AND assignment operat or, It divides left operand wit h


t he right operand and assign t he result t o left operand

C /= A is equivalent
to C = C / A

%=

Modulus AND assignment operat or, It t akes modulus using


t wo operands and assign t he result t o left operand

C %= A is equivalent
to C = C % A

<<=

Left shift AND assignment operat or

C <<= 2 is same as
C = C << 2

>>=

Right shift AND assignment operat or

C >>= 2 is same as
C = C >> 2

&=

Bit wise AND assignment operat or

C &= 2 is same as C
=C&2

^=

bit wise exclusive OR and assignment operat or

C ^= 2 is same as C
=C^2

|=

bit wise inclusive OR and assignment operat or

C |= 2 is same as C
=C|2

Misc Operat ors


There are few ot her operat ors support ed by Java Language.

Condit ional Operat or ( ? : ):


Condit ional operat or is also known as t he t ernary operat or. This operat or consist s of t hree operands
and is used t o evaluat e boolean expressions. The goal of t he operat or is t o decide which value
should be assigned t o t he variable. The operat or is writ t en as :
variable x = (expression) ? value if true : value if false

inst anceOf Operat or:


This operat or is used only for object reference variables. The operat or checks whet her t he object is
of a part icular t ype(class t ype or int erface t ype). inst anceOf operat or is wriit en as:
( Object reference variable ) instanceOf

(class/interface type)

Precedence of Java Operat ors:


Catego ry

Operato r

Asso ciativity

Post fix

() [] . (dot operat or)

Left t o right

Unary

++ - - ! ~

Right t o left

Mult iplicat ive

*/%

Left t o right

Addit ive

+-

Left t o right

Shift

>> >>> <<

Left t o right

Relat ional

> >= < <=

Left t o right

Equalit y

== !=

Left t o right

Bit wise AND

&

Left t o right

Bit wise XOR

Left t o right

Bit wise OR

Left t o right

Logical AND

&&

Left t o right

Logical OR

||

Left t o right

Condit ional

?:

Right t o left

Assignment

= += -= *= /= %= >>= <<= &= ^= |=

Right t o left

Comma

Left t o right

The while Loop:


A while loop is a cont rol st ruct ure t hat allows you t o repeat a t ask a cert ain number of t imes.

Synt ax:
The synt ax of a while loop is:
while(Boolean_expression)
{

//Statements
}

The do...while Loop:


A do...while loop is similar t o a while loop, except t hat a do...while loop is guarant eed t o execut e at
least one t ime.

Synt ax:
The synt ax of a do...while loop is:
do
{
//Statements
}while(Boolean_expression);

The for Loop:


A for loop is a repet it ion cont rol st ruct ure t hat allows you t o efficient ly writ e a loop t hat needs t o
execut e a specific number of t imes.
A for loop is useful when you know how many t imes a t ask is t o be repeat ed.

Synt ax:
The synt ax of a for loop is:
for(initialization; Boolean_expression; update)
{
//Statements
}

Enhanced for loop in Java:


As of java 5 t he enhanced for loop was int roduced. This is mainly used for Arrays.

Synt ax:
The synt ax of enhanced for loop is:
for(declaration : expression)
{
//Statements
}

The break Keyword:


The break keyword is used t o st op t he ent ire loop. The break keyword must be used inside any loop
or a swit ch st at ement .
The break keyword will st op t he execut ion of t he innermost loop and st art execut ing t he next line of
code aft er t he block.

The cont inue Keyword:


The continue keyword can be used in any of t he loop cont rol st ruct ures. It causes t he loop t o
immediat ely jump t o t he next it erat ion of t he loop.
In a for loop, t he cont inue keyword causes flow of cont rol t o immediat ely jump t o t he updat e
st at ement .
In a while loop or do/while loop, flow of cont rol immediat ely jumps t o t he Boolean expression.

Synt ax:

The synt ax of a cont inue is a single st at ement inside any loop:


continue;

The if St at ement :
An if st at ement consist s of a Boolean expression followed by one or more st at ement s.

Synt ax:
The synt ax of an if st at ement is:
if(Boolean_expression)
{
//Statements will execute if the Boolean expression is true
}

The if...else St at ement :


An if st at ement can be followed by an opt ional else st at ement , which execut es when t he Boolean
expression is false.

Synt ax:
The synt ax of a if...else is:
if(Boolean_expression){
//Executes when the Boolean expression is true
}else{
//Executes when the Boolean expression is false
}

The if...else if...else St at ement :


An if st at ement can be followed by an opt ional else if...else st at ement , which is very usefull t o t est
various condit ions using single if...else if st at ement .

Synt ax:
The synt ax of a if...else is:
if(Boolean_expression 1){
//Executes when the Boolean expression 1 is true
}else if(Boolean_expression 2){
//Executes when the Boolean expression 2 is true
}else if(Boolean_expression 3){
//Executes when the Boolean expression 3 is true
}else {
//Executes when the one of the above condition is true.
}

Nest ed if...else St at ement :


It is always legal t o nest if-else st at ement s. When using if , else if , else st at ement s t here are few
point s t o keep in mind.
An if can have zero or one else's and it must come aft er any else if's.
An if can have zero t o many else if's and t hey must come before t he else.
Once an else if succeeds, none of he remaining else if's or else's will be t est ed.

Synt ax:
The synt ax for a nest ed if...else is as follows:

if(Boolean_expression 1){
//Executes when the Boolean expression 1 is true
if(Boolean_expression 2){
//Executes when the Boolean expression 2 is true
}
}

The swit ch St at ement :


A switch st at ement allows a variable t o be t est ed for equalit y against a list of values. Each value is
called a case, and t he variable being swit ched on is checked for each case.

Synt ax:
The synt ax of enhanced for loop is:
switch(expression){
case value :
//Statements
break; //optional
case value :
//Statements
break; //optional
//You can have any number of case statements.
default : //Optional
//Statements
}

Java Met hods:


A Java met hod is a collect ion of st at ement s t hat are grouped t oget her t o perform an operat ion.
When you call t he Syst em.out .print ln met hod, for example, t he syst em act ually execut es several
st at ement s in order t o display a message on t he console.
In general, a met hod has t he following synt ax:
modifier returnValueType methodName(list of parameters) {
// Method body;
}

A met hod definit ion consist s of a met hod header and a met hod body. Here are all t he part s of a
met hod:
Mo difiers: The modifier, which is opt ional, t ells t he compiler how t o call t he met hod. This
defines t he access t ype of t he met hod.
Return T ype: A met hod may ret urn a value. The ret urnValueType is t he dat a t ype of t he
value t he met hod ret urns. Some met hods perform t he desired operat ions wit hout ret urning a
value. In t his case, t he ret urnValueType is t he keyword vo id.
Metho d Name: This is t he act ual name of t he met hod. The met hod name and t he paramet er
list t oget her const it ut e t he met hod signat ure.
Parameters: A paramet er is like a placeholder. When a met hod is invoked, you pass a value
t o t he paramet er. This value is referred t o as act ual paramet er or argument . The paramet er list
refers t o t he t ype, order, and number of t he paramet ers of a met hod. Paramet ers are
opt ional; t hat is, a met hod may cont ain no paramet ers.
Metho d Bo dy: The met hod body cont ains a collect ion of st at ement s t hat define what t he
met hod does.

Java Classes & Object s:


Object - Object s have st at es and behaviors. Example: A dog has st at es-color, name, breed
as well as behaviors -wagging, barking, eat ing. An object is an inst ance of a class.

Class - A class can be defined as a t emplat e/ blue print t hat describe t he behaviors/st at es
t hat object of it s t ype support .
A sample of a class is given below:
public class Dog{
String breed;
int age;
String color;
void barking(){
}
void hungry(){
}
void sleeping(){
}
}

A class can cont ain any of t he following variable t ypes.


Lo cal variables . variables defined inside met hods, const ruct ors or blocks are called local
variables. The variable will be declared and init ialized wit hin t he met hod and t he variable will be
dest royed when t he met hod has complet ed.
Instance variables . Inst ance variables are variables wit hin a class but out side any met hod.
These variables are inst ant iat ed when t he class is loaded. Inst ance variables can be accessed
from inside any met hod, const ruct or or blocks of t hat part icular class.
Class variables . Class variables are variables declared wit h in a class, out side any met hod,
wit h t he st at ic keyword.

Except ions Handling:


A met hod cat ches an except ion using a combinat ion of t he try and catch keywords. A t ry/cat ch
block is placed around t he code t hat might generat e an except ion. Code wit hin a t ry/cat ch block is
referred t o as prot ect ed code, and t he synt ax for using t ry/cat ch looks like t he following:
try
{
//Protected code
}catch(ExceptionName e1)
{
//Catch block
}

Mult iple cat ch Blocks:


A t ry block can be followed by mult iple cat ch blocks. The synt ax for mult iple cat ch blocks looks like
t he following:
try
{
//Protected code
}catch(ExceptionType1 e1)
{
//Catch block
}catch(ExceptionType2 e2)
{
//Catch block
}catch(ExceptionType3 e3)
{
//Catch block
}

The t hrows/t hrow Keywords:

If a met hod does not handle a checked except ion, t he met hod must declare it using t he thro ws
keyword. The t hrows keyword appears at t he end of a met hod's signat ure.
You can t hrow an except ion, eit her a newly inst ant iat ed one or an except ion t hat you just caught , by
using t he thro w keyword. Try t o underst and t he different in t hrows and t hrow keywords.

The finally Keyword


The finally keyword is used t o creat e a block of code t hat follows a t ry block. A finally block of code
always execut es, whet her or not an except ion has occurred.
Using a finally block allows you t o run any cleanup-t ype st at ement s t hat you want t o execut e, no
mat t er what happens in t he prot ect ed code.
A finally block appears at t he end of t he cat ch blocks and has t he following synt ax:
try
{
//Protected code
}catch(ExceptionType1 e1)
{
//Catch block
}catch(ExceptionType2 e2)
{
//Catch block
}catch(ExceptionType3 e3)
{
//Catch block
}finally
{
//The finally block always executes.
}

For a complet e det ail of t he Java Programming language, it is recommended t o go t hrough our simple
Java Tut orial.

Você também pode gostar