Você está na página 1de 58

Installing Java on windows

You can download version 1.6 of Java from


http://www.oracle.com/technetwork/java/javase/downloads/jdk-6u25-download-346242.html

Once Java has been installed, you will be able to run Java program by

running the java executable that was installed. You may find it convenient to add the location of this file to your operating system's path variable, otherwise you will need to explicitly refer to the absolute location of java.

Setting up the path


Right-clicking on 'My Computer' and selecting 'Properties'. Under the 'Advanced' tab, there is a button that allows you to

set the 'Environment variables'.


the path to the Java executable.

Click on this and alter the 'Path' variable so that it also contains For example, if you have installed Java in c:\jdk and your path is

currently set to C:\WINDOWS\SYSTEM32, then you would change your path to read C:\WINDOWS\SYSTEM32;c:\jdk\bin

When you open a new command prompt, it will reflect these changes and allow you to run java programs by typing "java". If you have installed the SDK, then you will also be able to run "javac" to compile stuff.

Setting up the classpath In addition to setting up the path, you also need to tell Java where to find compiled class files at runtime. You will probably want to set the classpath to include at least the current working directory (.) Example:SET CLASSPATH=%CLASSPATH%; The classpath can also contain other directories that may contain compiled class files. Note that if you are using classes that are contained inside a .jar file, you will need to specify the full path and name of this file in the classpath, rather than just the name of the directory it is contained within.

Java Program Development


Dos Based GUI Based

Applets
Web Based

Java Source file structure


A Java file is the smallest unit of Java code that can be compiled by the Java compiler. A Java file consists of:
An optional package directive
Zero or more import directives One or more class definitions

In C/C++
Source

compiler

.obj

Linker

Linking File(.obj +Library File

.exe
Loader

RAM

In Java
Source (.java) compiler
(compiler output) The compiler generate .class file is made of byte codes.

.class

Virtual Machine (Run the program)

Application api JVM OS Hardware

Primitive Data Types


Primitive data values are not objects. Each primitive data type defines the range of values in the data type, and operations on these values are defined by special operators in the language. Each primitive data type also has a corresponding wrapper class that can be used to represent a primitive value as an object. Primitive Data Types
Boolean Type Integral types Numeric types Floating point types

Character types

Integer types

boolean

char

byte

short

int

long

float

double

Range of Primitive Data Types


Data Type Wrapper Class Width (bits) Default value Min value
(MIN_VALUE)

Max value
(MAX_VALUE)

boolean Boolean char Character

Not applicable 16

False 0x0 (\u0000) 0 0 0 0L

True 0x0 (\u0000) -27 (-128) -215(32768) -231 -263

false 0xffff

byte short int long

Byte Short Integer Long

8 16 32 64

27 (+127) 215(+32767 ) 231 263

float
double

Float
Double

32
64

0.0F
0.0D

Type Conversion and casting

Automatic Type Promotion in Expression

Type Conversion and casting


Javas Automatic conversions When one type of data is assigned to other type of variable , an automatic type conversion will take place if the following two condition are met:
1) The two type are compatible 2) The destination is larger than the source type

Type Conversion and casting


To create a conversion between two incompatible type you must use a cast.
Example byte b; int i=257;

b=(byte)i;

Result:- b=1

Automatic Type Promotion in Expression


Java defines several type promotion rules that apply to expression. They are as follows:First, all type byte, short, and char values are promoted to int then, if one operand is a long, the whole expression is promoted to long. If one operand is float the entire expression is promoted to float. If one of the operand is double, the result is double.

Automatic Type Promotion in Expression

Example
byte b=42; char=a; short=1024; int i=50000;

double result=(i/c)+(s*b);

Variable
A variable stores a value of a particular type. Types of variable
Instance variable Reference variable Static variables Local variables

Variable
A variable stores a value of a particular type. A variable has a name, a type, and a value associated with it. In Java, variables can only store values of primitive data types and references to objects. Variables that store references to objects are called reference variable. Lifetime of variables 1) Instance variable :- members of a class and created for each object of the class. Instance variables exist as long as the object they belong to exists. 2) Static variables :- members of a class, but not created for any object of the class and, therefore belong only to the class. They are created when the class is loaded at runtime, and exist as long as the class exists. 3) Local variables :- declared in methods and in blocks and created for each execution of the method or block. After the execution of the method or block completed local variables are no longer accessible.

Tokens
Identifiers Keywords Operators Literals Comments Separators

Identifiers

Keywords

Tokens, Identifiers & Keywords


Java tokens
The tokens of a language are the basic building blocks which can be put

together to construct programs. A token can be a reserved word (such as int or while), an identifier (such as b or sum), a constant (such as 25 or "Alice in Wonderland"), a delimiter (such as { or ;) or an operator (such as + or =).

The different types of Tokens are: A. Identifiers: names the programmer chooses B. Keywords: names already in the programming language C. Separators (also known as punctuators): punctuation characters and paired-delimiters D. Operators: symbols that operate on arguments and produce results E. Literals (specified by their type) a. Numeric: int and double b. Logical: boolean c. Textual: char and String d. Reference: null F. Comments

Literals
A constant value in java is created by using a literal.

For example:100 -------- integer literal 98.6 --------floating-point literal x --------character literal This is a test --------String literal Literals are value assigned to variable in a program.

Identifier
Identifiers are user for naming classes,

methods

variables, labels, interfaces etc.

Keywords
All the words which are reserved in Java and can not be used as identifiers, all those words are keywords. There are 50 keywords currently defined in the Java Language.
abstract const finally interface short transient

assert
boolean break byte case catch char class

continue
default do double else enum extends final

float
for goto if implements import instanceof int

long
native new package private protected public return

static
srtictfp super switch synchronized this throw throws

try
void volatile while

The Keywords const and goto are reserved but not used. In addition to keywords, Java reserve the following: true, false, null. These are literal values defined by Java. You may not use these words as a Identifiers.

Character Escape Sequences


Escape Sequence \ddd \uxxxx Description Octal character Hexadecimal Unicode character

\ \ \\ \r \n \f \t \b

Single quote Double quote Backslash Carriage return New line Form feed Tab Backspace

Operators
An operator is a symbol that tells the computer to perform certain mathematical or logical manipulation. Operators are used in program to manipulate data and variables.

Types of operator in Java


Assignment operators

Arithmetic operators
Logical operators

= - + * / % ++ -&& || & | ! ^

Relational operators
Bitwise operators Compound Assignment operators

> < >= <= == !=


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

Conditional operator Type comparison operator

?: instanceof

Logical Operators
X Y !x X&Y X && Y X|Y X || Y X^Y

false false true


true

false true false


true

true true false


false

false false false


true

false true true


true

false true true


false

Bitwise Operators
A B ~A A&B A|B A^B

Conditional Operator
public class TernaryOperatorDemo { public static void main(String args []) { int x=10, y=12, z=0;

z= x>y? x : y;
System.out.println(z:- +z);
} }

Operator Precedence
The order in which operators are applied is known as precedence. Operator with a higher precedence are applied before operators with a lower precedence. If two operators have the same precedence, they are applied in the order they appear in a

statement. That is, from left to right.

Operator Precedence
Postfix
Unary Creation/caste Multiplicative

[] . () expr++ expr -++expr new * / % --expr +expr -expr ! ~ (type) expr

Additive
shift Relational Equality

+
< ==

<= != > >= instanceof

>> >>>

Bitwise AND
Bitwise exclusive OR Bitwise inclusive OR Logical AND Logical OR Ternary Assignment

&
^ | && || ?: =

Operator Precedence
Example Result = 4 + 5 * 3; First (5*3) is evaluated and the result is added to 4 giving the final result as 19. This kind of precedence of one operator over another applies to all the operators.

Flow Control Statements


Java Control statements control the order of execution in a java program, based on data values and conditional logic. We use control statements when we want to change the default sequential order of execution. There are three main categories of control flow statements: Selection statements: if, if-else and switch. Loop statements: while, do-while and for. Transfer statements: break, continue, return, try-catch-

finally and assert.

Selection Statements
if
a) Simple if statement b) if-else
c) Nested if-else d) if-else-if Ladder

switch
a) Simple switch b) Nested switch

Selection Statements
Simple if statement

syntax :-

if(boolean expression) { statement-block; } statement-block;

if-else statement

syntax:-

if(boolean-expression) { True-block statement; } else { False-block statement; } statement block;

if
public class IfExample { public static void main(String[] args) { int i = 10; if(i %2==0) System.out.println("i is EVEN No."); System.out.println(I is :- +i); } }

Example

if-else Example
public class IfElseExample { public static void main(String[] args) { int i = 10; if(i %2==0) System.out.println("i is EVEN No."); else System.out.println("i is ODD No.");

System.out.println(i is :- +i); }
}

Selection Statements
Nested if-else statement

syntax:-

if(condition 1) { if(condition 2) { statement 1; } else { statement 2; } } else { statement 3; }


statement-block;

Selection Statements
if-else-if Ladder syntax:if(condition 1) statement 1; else if(condition 2) statement 2; else if(condition 3) statement 3; else statement 4; statement block;

Nested if-else Example


public class NestedifExample { public static void main(String args[]){ int x = 30; int y = 10;
if( x %2== 0 ){ if( y %2 == 0 ){ System.out.print(Both X and Y are EVEN"); } } } }

public class IfElseLadderDemo { public static void main(String[] args) { int testscore = 76; char grade; if (testscore >= 90) { grade = 'A'; } else if (testscore >= 80) { grade = 'B'; } else if (testscore >= 70) { grade = 'C'; } else if (testscore >= 60) { grade = 'D'; } else { grade = 'F'; } System.out.println("Grade = " + grade); } }

if-else Ladder Example

Selection Statements
Simple switch syntax:-

switch(expression){ case value-1: block 1; break; case value-2: block 2; break; default: default block; } statement block;

Selection Statements
Example:-

switch Example

switch(month){ case 1: case 3: case 5: case 7: case 8: case 10: case 12: System.out.println(Days 31); break; case 2: System.out.println(Days 28); break; default: default block; } statement block;

Nested switch

Nested switch

switch(count){ case 1: switch(target){ case 0: statement 1; break; case 1: statement 2; break;

}
case 2: statement 3; break; } when it compiles a switch statements, the Java compiler will inspect each of the case constants and create a jump table that it will use for selection the path of execution depending on the value of the expression.

Example:-

switch Example

int i=0, j=0;


switch(i){ case 2: case 4: default: case 0: }

j+=6; j+1=; j+=2; j+=4;

System.out.println(j);

--->6

Because there are no break statements, the program gets to the default case and adds 2 to j, then goes to case 0 and adds 4 to the new j. The result is s=6.

Iteration/Loop
Loop is the process of executing one or more statements till the specific condition doesnt satisfied. There are two types of loop
Entry control loop
Exit control loop

Iteration/Loop
Entry control loop:- In the entry controlled loop, the control conditions are tested before the start of the loop execution. If the condition are not satisfied, the body of the loop will not be executed.

Exit control loop:- In exit controlled loop, the test is performed at the end of the loop and therefore the body is executed unconditionally for the first time. do-while loop is exit control loop. It executes its body at least once.

Iteration/Loop
Four constructs for performing loop operations

1) while loop

2) do-while loop
3) for loop

4) for-each loop

Entry control loop


while

syntax:-

initialization while(condition) { //body of loop; increment/decrement; }

for

1) for(initialization; condition; iteration) {//body of loop; } 2) for( ; ; ) {//body of loop; } 3) for(initialization1, initialization2; condition; increment, decrement) { //body of loop; }

Exit control loop


d0-while syntax:- initialization do { //body of loop; increment/decrement; } while(condition);

While

while Example

public class WhileLoopDemo { public static void main(String args[]) { int count =1; System.out.println(Printing Numbers from 1 to 10); while(count <= 10) { System.out.print (count++ ); } } } Output Printing Numbers from 1 to 10

1 2 3 4 5 6 7 8 9 10

for

for Example

Public class ForLoopDemo { public static void main(String args[]) { System.out.println(Printing Numbers from 1 to 10); for(int count=1; count <=10; count++) { System.out.print(count+\t); } } } Output Printing Numbers from 1 to 10

1 2 3 4 5 6 7 8 9 10

do-while

do-while Example

public class DoWhileLoopDemo { public static void main(String args[]) { int count = 1; System.out.println(Printing Numbers from 1 to 10); do { System.out.print(count++ +\t); } while(count <= 10); } }

Output Printing Numbers from 1 to 10

1 2 3 4 5 6 7 8 9 10

for-each
A for-each style loop is designed to cycle through a

collection of objects, such as array, in strictly sequential fashion, from start to finish. Example:for(type itr-var: collection) statement-block;

Here , type specifies the type and itr-var specifies the name of an iteration variable that will receives the elements from a collection, one at a time, from beginning to end. It eliminates the need to establish a loop counter, specify a starting and ending value and manually index the array.

for-each

for-each Example

public class For_EachExample { public static void main(String args[]) { int nums[]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15}; for(int x:nums) { System.out.print(x+"\t"); } } }

Transfer Statements
continue break

continue
A continue statement stops the iteration of a loop (while, do or for) and causes execution to resume at the top of the nearest enclosing loop.
You use a continue statement when you do not want to execute the remaining statements in the loop, but you do not want to exit the loop itself.

continue
public class ContinueExample { public static void main(String args[]) { System.out.println(Odd Numbers); for(int i=1; i<=10; ++i) { if(i % 2 ==0) continue;

continue Example

//Reset of loop body skipped when i is eleven System.out.print(i+\t); } }

Output Odd Numbers

1 3 5 7 9

break
The break statement transfers control out of the enclosing loop (for, while, do or switch statement). You use a break statement when you want to jump immediately to the statement following the enclosing control structure

break
public class BreakExample { public static void main(String args[]) { System.out.println(Numbers 1-10); for(int i=1; ; ++i) { if(i == 11) break; //Reset of loop body skipped when i is eleven System.out.print (i+\t); } } }

break Example

Output

Numbers 1-10 1 2 3 4 5 6 7 8 9 10

Você também pode gostar