2language fundamentals

58

Upload: nitish-sharma

Post on 06-Apr-2018

221 views

Category:

Documents


0 download

TRANSCRIPT

8/3/2019 2Language Fundamentals

http://slidepdf.com/reader/full/2language-fundamentals 1/58

8/3/2019 2Language Fundamentals

http://slidepdf.com/reader/full/2language-fundamentals 2/58

Installing Java on windows

 You can download version 1.6 of Java fromhttp://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 youroperating system's path variable, otherwise you will need to explicitly refer to the absolute location of java.

8/3/2019 2Language Fundamentals

http://slidepdf.com/reader/full/2language-fundamentals 3/58

Setting up the path

R ight-clicking on 'My Computer' and selecting 'Properties'.

Under the ' Advanced' tab, there is a button that allows you toset the 'Environment variables'.

Click on this and alter the 'Path' variable so that it also containsthe path to the Java executable.

For example, if you have installed Java in c:\jdk and your path iscurrently set to C:\WINDO WS\SYSTEM32, then you wouldchange your path to read C:\WINDO WS\SYSTEM32;c:\jdk\bin

 When you open a new command prompt, it will reflect thesechanges 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.

8/3/2019 2Language Fundamentals

http://slidepdf.com/reader/full/2language-fundamentals 4/58

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 includeat 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 willneed to specify the full path and name of this file inthe classpath, rather than just the name of thedirectory it is contained within.

8/3/2019 2Language Fundamentals

http://slidepdf.com/reader/full/2language-fundamentals 5/58

Java Program Development

Dos Based

GUI Based

 Applets

 Web Based

8/3/2019 2Language Fundamentals

http://slidepdf.com/reader/full/2language-fundamentals 6/58

Java Source file structure

 A Java file is the smallest unit of Java code that can becompiled by the Java compiler. A Java file consists of:

 An optional package directive

Zero or more import directives

One or more class definitions

8/3/2019 2Language Fundamentals

http://slidepdf.com/reader/full/2language-fundamentals 7/58

In C/C++

Linker

R  AM

Source

compiler

.obj

.exe

Loader

Linking File(.obj +Library File

8/3/2019 2Language Fundamentals

http://slidepdf.com/reader/full/2language-fundamentals 8/58

In JavaSource

compiler

.class

(.java)

(compiler output) The compiler generate .class file is made of byte codes.

  Virtual Machine (R un the program)

 Application api  JVM OS  Hardware

8/3/2019 2Language Fundamentals

http://slidepdf.com/reader/full/2language-fundamentals 9/58

Primitive Data TypesPrimitive data values are not objects. Each primitive data type defines

the range of values in the data type, and operations on these values aredefined by special operators in the language.

Each primitive data type also has a corresponding wrapper class that canbe used to represent a primitive value as an object.

PrimitiveData Types

Primitive data values are not objects. Each primitive data type definesthe range of values in the data type, and operations on these values aredefined by special operators in the language.

Each primitive data type also has a corresponding wrapper class that canbe used to represent a primitive value as an object.

PrimitiveData Ty pes

boolean char byte short int doublefloatlong

Floating point types

Numeric typesBoolean Type

Integral types

Character types Integer types

8/3/2019 2Language Fundamentals

http://slidepdf.com/reader/full/2language-fundamentals 10/58

Range of Primitive Data TypesData Type Wrapper

Class

 Width (bits) Default value Min value(MIN_VALUE)

Max value(MAX_VALUE)

boolean Boolean Notapplicable

False True false

char Character 16 0x0(\u0000)

0x0(\u0000)

0xfff 

byte Byte 8 0 -27 (-128) 27 (+127)

short Short 16 0 -215(- 32768)

215(+32767)

int Integer 32 0 -2 31 2 31

long Long 64 0L -263 263

float Float 32 0.0F -2 31 2 31

double Double 64 0.0D -263 263

8/3/2019 2Language Fundamentals

http://slidepdf.com/reader/full/2language-fundamentals 11/58

     Type Conversion and casting

     Automatic Type Promotion in Expression

8/3/2019 2Language Fundamentals

http://slidepdf.com/reader/full/2language-fundamentals 12/58

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 placeif the following two condition are met:

1) The two type are compatible

2) The destination is larger than the source type

8/3/2019 2Language Fundamentals

http://slidepdf.com/reader/full/2language-fundamentals 13/58

Type Conversion and casting

To create a conversion between two incompatible type youmust use a cast.

Example

byte b;

int i=257;

b=(byte)i; Result:- b=1

8/3/2019 2Language Fundamentals

http://slidepdf.com/reader/full/2language-fundamentals 14/58

Automatic Type Promotion in Expression

 Java defines several type promotion rules that apply toexpression. They are as follows:-

First, all type byte, short, and char values are promotedto int then, if one operand is a long, the wholeexpression is promoted to long.

If one operand is float the entire expression is promotedto float. If one of the operand is double, the result isdouble.

8/3/2019 2Language Fundamentals

http://slidepdf.com/reader/full/2language-fundamentals 15/58

Automatic Type Promotion in Expression

Example

byte b=42;char=a;

short=1024;

int i=50000;

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

8/3/2019 2Language Fundamentals

http://slidepdf.com/reader/full/2language-fundamentals 16/58

Variable

 A  variable stores a value of a particular type.

Types of variable

Instance variable

Reference variable

Static variables

Local variables

8/3/2019 2Language Fundamentals

http://slidepdf.com/reader/full/2language-fundamentals 17/58

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 thatstore references to objects are called reference variable.

Lifetime of variables

1) Instance variable :- members of a class and created for eachobject 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 theclass exists.

 3) Local variables :- declared in methods and in blocks and createdfor each execution of the method or block. After the execution of the method or block completed local variables are no longer

accessible.

8/3/2019 2Language Fundamentals

http://slidepdf.com/reader/full/2language-fundamentals 18/58

y Tokensy Identifiers

y Keywords

y Operators

y Literals

y Comments

y Separators

y Identifiers

y Keywords

8/3/2019 2Language Fundamentals

http://slidepdf.com/reader/full/2language-fundamentals 19/58

Tokens, Identifiers & Keywords Java tokensy 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 (suchas int or while), an identifier (such as b or sum), a constant (suchas 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 choosesB. Keywords: names already in the programming languageC. Separators (also known as punctuators): punctuation characters and

paired-delimitersD. Operators: symbols that operate on arguments and produce results

E. Literals (specified by their type)a. Numeric: int and doubleb. Logical: booleanc. Textual: char and Stringd. R eference: null

F. Comments

8/3/2019 2Language Fundamentals

http://slidepdf.com/reader/full/2language-fundamentals 20/58

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 literalLiterals are value assigned to variable in a program.

Identifier

Identifiers are user for naming classes, methods variables, labels, interfaces etc.

8/3/2019 2Language Fundamentals

http://slidepdf.com/reader/full/2language-fundamentals 21/58

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.

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.

abstract const finally interface short transient

assert continue float long static try  

boolean default for native srtictfp void

break do goto new super volatile

byte double if package switch while

case else implements private synchronized

catch enum import protected this

char extends instanceof public throw

class final int return throws

8/3/2019 2Language Fundamentals

http://slidepdf.com/reader/full/2language-fundamentals 22/58

Character Escape Sequences

Escape Sequence Description

\ddd Octal character

\uxxxx Hexadecimal Unicode character

\ Single quote

\ Double quote

\\ Backslash

\r Carriage return

\n New line\f Form feed

\t Tab

\b Backspace

8/3/2019 2Language Fundamentals

http://slidepdf.com/reader/full/2language-fundamentals 23/58

Operators

 An operator is a symbol that tells the computer toperform certain mathematical or logical manipulation.

Operators are used in program to manipulate data and variables.

8/3/2019 2Language Fundamentals

http://slidepdf.com/reader/full/2language-fundamentals 24/58

Types of operator in Java

 Assignment operators = Arithmetic operators - + * / % ++ --Logical operators && || & | ! ^

R elational operators > < >= <= == !=Bitwise operators & | ^ >> >>>

Compound Assignment operators += -+ *= /= %= <<= >>= >>>=

Conditional operator ? :Type comparison operator

instanceof 

8/3/2019 2Language Fundamentals

http://slidepdf.com/reader/full/2language-fundamentals 25/58

LogicalOperators

 X Y !x X & Y   X && Y 

 X | Y  X || Y 

 X ^ Y 

false false true false false false

false true true false true true

true false false false true true

true true false true true false

8/3/2019 2Language Fundamentals

http://slidepdf.com/reader/full/2language-fundamentals 26/58

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

0 0 1 0 0 0

0 1 1 0 1 1

1 0 0 0 1 1

1 1 0 1 1 0

8/3/2019 2Language Fundamentals

http://slidepdf.com/reader/full/2language-fundamentals 27/58

Conditional Operator

public class TernaryOperatorDemo{

public static void main(String args [])

{int x=10, y=12, z=0;

z= x>y? x : y;

S ystem.out.println(z:- +z);

}

}

8/3/2019 2Language Fundamentals

http://slidepdf.com/reader/full/2language-fundamentals 28/58

Operator Precedence

The order in which operators are applied isknown as precedence.

Operator with a higher precedence are appliedbefore operators with a lower precedence.

If two operators have the same precedence, they 

are applied in the order they appear in astatement. That is, from left to right.

8/3/2019 2Language Fundamentals

http://slidepdf.com/reader/full/2language-fundamentals 29/58

Operator PrecedencePostfix [] . () expr++ expr --

Unary  ++expr --expr +expr -expr ! ~

Creation/caste new (type) expr

Multiplicative * / %

 Additive + -

shift >> >>>R elational < <= > >= instanceof 

Equality  == !=

Bitwise AND &

Bitwise exclusive OR  ^

Bitwise inclusive OR  |

Logical AND &&

Logical OR  ||

Ternary  ? :

 Assignment =

8/3/2019 2Language Fundamentals

http://slidepdf.com/reader/full/2language-fundamentals 30/58

Operator Precedence

Example

Result = 4 + 5 * 3;

First (5*3) is evaluated and the result is added to 4giving the final result as 19.

This kind of precedence of one operator over anotherapplies to all the operators.

8/3/2019 2Language Fundamentals

http://slidepdf.com/reader/full/2language-fundamentals 31/58

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 defaultsequential order of execution. There are three main categoriesof control flow statements:-

y Selection statements: if, if-else and switch.

y Loop statements:  while, do-while and for.

y Transfer statements: break, continue, return, try-catch-finally and assert.

8/3/2019 2Language Fundamentals

http://slidepdf.com/reader/full/2language-fundamentals 32/58

Selection Statements

if switch

a) Simple if statement a) Simple switch

b) if-else b) Nested switch

c) Nested if-else

d) if-else-if Ladder

8/3/2019 2Language Fundamentals

http://slidepdf.com/reader/full/2language-fundamentals 33/58

Selection Statements Simple if statement

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

if-else statementsyntax:- if(boolean-expression)

{ True-block statement;

}else{ False-block statement;}statement block;

8/3/2019 2Language Fundamentals

http://slidepdf.com/reader/full/2language-fundamentals 34/58

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);}

}

if Example

8/3/2019 2Language Fundamentals

http://slidepdf.com/reader/full/2language-fundamentals 35/58

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);

}

}

if-else Example

8/3/2019 2Language Fundamentals

http://slidepdf.com/reader/full/2language-fundamentals 36/58

Selection StatementsNested if-else statement

syntax:- if(condition 1){if(condition 2){

statement 1;}else{

statement 2;}

}

else{statement 3;

}

statement-block;

8/3/2019 2Language Fundamentals

http://slidepdf.com/reader/full/2language-fundamentals 37/58

Selection Statements

if-else-if Ladder

syntax:- if(condition 1)statement 1;

else if(condition 2)statement 2;

else if(condition 3)statement 3;

elsestatement 4;

statement block;

8/3/2019 2Language Fundamentals

http://slidepdf.com/reader/full/2language-fundamentals 38/58

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");

}

}

}

}

Nested if-else Example

8/3/2019 2Language Fundamentals

http://slidepdf.com/reader/full/2language-fundamentals 39/58

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

8/3/2019 2Language Fundamentals

http://slidepdf.com/reader/full/2language-fundamentals 40/58

Selection Statements

Simple switchsyntax:- switch(expression){

case value-1:block 1;

break;case value-2:

block 2;break;

default:default block;}statement block;

8/3/2019 2Language Fundamentals

http://slidepdf.com/reader/full/2language-fundamentals 41/58

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;

Selection Statementsswitch Example

8/3/2019 2Language Fundamentals

http://slidepdf.com/reader/full/2language-fundamentals 42/58

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 thepath of execution depending on the value of the expression.

Nested switch

8/3/2019 2Language Fundamentals

http://slidepdf.com/reader/full/2language-fundamentals 43/58

y Example:-int i=0, j=0;

switch(i){case 2: j+=6;case 4: j+1=;

default: j+=2;case 0: j+=4;}

System.out.println(j); --->6

Because there are no break statements, the programgets 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.

switch Example

8/3/2019 2Language Fundamentals

http://slidepdf.com/reader/full/2language-fundamentals 44/58

Iteration/Loop

Loop is the process of executing one or morestatements till the specific condition doesnt satisfied.

There are two types of loop

     Entry control loop

     Exit control loop

8/3/2019 2Language Fundamentals

http://slidepdf.com/reader/full/2language-fundamentals 45/58

Entry control loop:- In the entry controlled loop, the controlconditions are tested before the start of the loop execution. If thecondition are not satisfied, the body of the loop will not beexecuted.

Exit control loop:- In exit controlled loop, the test is performed at

the end of the loop and therefore the body is executedunconditionally for the first time. do-while loop is exit controlloop. It executes its body at least once.

Iteration/Loop

8/3/2019 2Language Fundamentals

http://slidepdf.com/reader/full/2language-fundamentals 46/58

Iteration/Loop

Four constructs for performing loop operations

1) while loop

2) do-while loop

 3) for loop

4) for-each loop

8/3/2019 2Language Fundamentals

http://slidepdf.com/reader/full/2language-fundamentals 47/58

y  whilesyntax:- initialization

 while(condition){ //body of loop;

increment/decrement;

}y for

1) for(initialization; condition; iteration){//body of loop;}

2) for( ; ; ){//body of loop;}

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

Entry control loop

8/3/2019 2Language Fundamentals

http://slidepdf.com/reader/full/2language-fundamentals 48/58

Exit control loop

d0-while

syntax:- initialization

do{ //body of loop;

increment/decrement;}

 while(condition);

8/3/2019 2Language Fundamentals

http://slidepdf.com/reader/full/2language-fundamentals 49/58

Whilepublic 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

 while Example

8/3/2019 2Language Fundamentals

http://slidepdf.com/reader/full/2language-fundamentals 50/58

forPublic 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

for Example

8/3/2019 2Language Fundamentals

http://slidepdf.com/reader/full/2language-fundamentals 51/58

do-whilepublic 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

do-while Example

8/3/2019 2Language Fundamentals

http://slidepdf.com/reader/full/2language-fundamentals 52/58

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

collection of objects, such as array, in strictly sequentialfashion, from start to finish.

Example:-for(type itr-var: collection)

statement-block;

y Here , type specifies the type and itr-var specifies thename of an iteration variable that will receives the

elements from a collection, one at a time, from beginningto end.

y It eliminates the need to establish a loop counter, specify astarting and ending value and manually index the array.

8/3/2019 2Language Fundamentals

http://slidepdf.com/reader/full/2language-fundamentals 53/58

for-each

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");

}

}

}

for-each Example

8/3/2019 2Language Fundamentals

http://slidepdf.com/reader/full/2language-fundamentals 54/58

Transfer Statements

ycontinue

ybreak

8/3/2019 2Language Fundamentals

http://slidepdf.com/reader/full/2language-fundamentals 55/58

continue

 A continue statement stops the iteration of a loop (while,do or for) and causes execution to resume at the top of thenearest enclosing loop.

 You use a continue statement when you do not want toexecute the remaining statements in the loop, but you do

not want to exit the loop itself.

8/3/2019 2Language Fundamentals

http://slidepdf.com/reader/full/2language-fundamentals 56/58

continuepublic 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;

//R eset of loop body skipped when i is elevenSystem.out.print(i+\t);

}

}}

Output

Odd Numbers

1 3 5 7 9

continue Example

8/3/2019 2Language Fundamentals

http://slidepdf.com/reader/full/2language-fundamentals 57/58

break

The break statement transfers control out of the enclosingloop (for, while, do or switch statement).

 You use a break statement when you want to jump

immediately to the statement following the enclosingcontrol structure

b k b k l

8/3/2019 2Language Fundamentals

http://slidepdf.com/reader/full/2language-fundamentals 58/58

breakpublic class BreakExample

{

public static void main(String args[]){

System.out.println(Numbers 1-10);

for(int i=1; ; ++i)

{

if(i == 11)break;

//R eset of loop body skipped when i is eleven

System.out.print (i+\t);

}

}

}

Output

Numbers 1-10

1 2 3 4 5 6 7 8 9 10

break Example