67
Session 2 Session 2 Java Language Fundamentals 07:56 PM

Session 2 Session 2 Java Language Fundamentals 9:17 AM

Embed Size (px)

Citation preview

Page 1: Session 2 Session 2 Java Language Fundamentals 9:17 AM

Session 2Session 2

Java Language Fundamentals

04:42 PM

Page 2: Session 2 Session 2 Java Language Fundamentals 9:17 AM

ReviewReview

Java was introduced by Sun Microsystems in 1995. Java is a programming language popularly used to build programs that can

work on the Net. Its primary features are: it is object-oriented and a cross platform language. Swing, Drag and Drop, Java 2D API, Java Sound and RMI are some of the

features added to the existing version of Java. A Java applet is designed to work in a pre-defined “sandbox” only. This

makes it safe to be used on the Internet. Java bytecodes are machine language instructions understood by the Java

Virtual Machine and usually generated as a result of compiling Java language source code.

04:42 PM

Page 3: Session 2 Session 2 Java Language Fundamentals 9:17 AM

Review Contd…Review Contd…

Java programs can be divided into following categories-applets, applications, GUI applications, servlets and database applications.

Java visual development tools help the programmer to develop Java applications and applets more quickly and efficiently.

The JDK contains the software and tools needed to compile, debug and execute applets and applications written in the Java language. It’s basically a set of command-line tools.

Enhancement in Swing, AWT, a new I/O class and so on has been added in the latest version of Java 1.4.2.

The future will use a lot of Java related programs for consumer gadgets with embedded technologies.

04:42 PM

Page 4: Session 2 Session 2 Java Language Fundamentals 9:17 AM

ObjectivesObjectives

Interpret the Java ProgramUnderstand the basics of Java Language Identify the Data TypesUnderstand arrays Identify the OperatorsFormat output using Escape Sequence

04:42 PM

Page 5: Session 2 Session 2 Java Language Fundamentals 9:17 AM

A Sample Java A Sample Java programprogram

// This is a simple program called First.javaclass First{ public static void main (String [] args) { System.out.println ("My first program in Java ");

}}

04:42 PM

Page 6: Session 2 Session 2 Java Language Fundamentals 9:17 AM

Analyzing the Java Analyzing the Java Program Program

The symbol // stands for commented line. When longer comments are needed, mark each line with a //.

◦ Or use the /* and */ comment delimiters -> block off a longer comment

The line class First declares a new class called First. public static void main (String [] args)

◦ This is the main method from where the program begins its execution.

System.out.println (“My first program in java”);◦ object.method(parameters)

◦ This line displays the string My first program in java on the screen.

04:42 PM

Page 7: Session 2 Session 2 Java Language Fundamentals 9:17 AM

04:42 PM

Page 8: Session 2 Session 2 Java Language Fundamentals 9:17 AM

Phase 1: Creating a Phase 1: Creating a ProgramProgramconsists of editing a file with an editor program

(normally known simply as an editor).A file name ending with the .java extension

indicates that the file contains Java source code. ◦ Eclipse (www.eclipse.org), ◦ NetBeans (www.netbeans.org),◦ JBuilder (www.borland.com), ◦ JCreator (www.jcreator.com), ◦ BlueJ (www.blueJ.org), ◦ jGRASP (www.jgrasp.org) ◦ jEdit (www.jedit.org).

04:42 PM

Page 9: Session 2 Session 2 Java Language Fundamentals 9:17 AM

Phase 2: Compiling a Java Program into Phase 2: Compiling a Java Program into BytecodesBytecodes the programmer uses the command javac (the Java compiler) to compile a program. For

example, to compile a program called Welcome.java, you would type

javac Welcome.java

If the program compiles, the compiler produces a .class file called Welcome.class that

contains the compiled version of the program.

The Java compiler translates Java source code into bytecodes that represent the tasks to

execute in the execution phase (Phase 5). Bytecodes are executed by the Java Virtual

Machine (JVM)—a part of the JDK and the foundation of the Java platform.

A virtual machine (VM) is a software application that simulates a computer, but

hides the under- lying operating system and hardware from the programs that interact

with the VM.

the same VM is implemented on many computer platforms, applications that it executes can be used

on all those platforms.

bytecodes are platform-independent instructions—they are not dependent on a particular

hardware platform (>< machine codes).

->So Java’s bytecodes are portable—that is, the same bytecodes can execute on any

platform containing a JVM that understands the version of Java in which the bytecodes

were compiled.

The JVM is invoked by the java command.

04:42 PM

Page 10: Session 2 Session 2 Java Language Fundamentals 9:17 AM

Phase 3: Loading a Program into Phase 3: Loading a Program into MemoryMemory the program must be placed in memory before it can execute

—known as loading.

java Welcome

The class loader takes the .class files containing the

program’s bytecodes and transfers them to primary memory.

The class loader also loads any of the .class files provided by

Java that your program uses.

The .class files can be loaded from a disk on your system or

over a network (e.g., your local college or company network,

or the Internet).

04:42 PM

Page 11: Session 2 Session 2 Java Language Fundamentals 9:17 AM

Phase 4: Bytecode Phase 4: Bytecode VerificationVerificationas the classes are loaded, the bytecode

verifier examines their bytecodes to ensure that they are valid and do not violate Java’s security restrictions.

Java enforces strong security, to make sure that Java programs arriving over the network do not damage your files or your system (as computer viruses and worms might).

04:42 PM

Page 12: Session 2 Session 2 Java Language Fundamentals 9:17 AM

Phase 5: ExecutionPhase 5: Execution the JVM executes the program’s bytecodes, thus performing the

actions specified by the program.

In early Java versions, the JVM was simply an interpreter for Java

bytecodes -> execute slowly. Today’s JVMs typically execute

bytecodes using a combination of interpretation and so-called just-in-

time (JIT) compilation.

Thus Java programs actually go through two compilation phases—

one in which source code is translated into bytecodes (for portability

across JVMs on different computer platforms) and a second in which,

during execution, the bytecodes are translated into machine language

for the actual computer on which the program executes.

04:42 PM

Page 13: Session 2 Session 2 Java Language Fundamentals 9:17 AM

Compiling and executing the Compiling and executing the Java programJava program

The java compiler creates a file called 'First.class' that contains the byte codes

To actually run the program, a java interpreter called java is required to execute the code.

04:42 PM

Page 14: Session 2 Session 2 Java Language Fundamentals 9:17 AM

Passing Command Line Passing Command Line ArgumentsArguments

class CommLineArg{

public static void main (String [] pargs){

System.out.println("These are the arguments passed to the main method.");

System.out.println(pargs [0]);System.out.println(pargs [1]);System.out.println(pargs [2]);

}}

04:42 PM

Page 15: Session 2 Session 2 Java Language Fundamentals 9:17 AM

Passing Command Line Passing Command Line ArgumentsArguments

Output

04:42 PM

Page 16: Session 2 Session 2 Java Language Fundamentals 9:17 AM

Basics of the Java Basics of the Java Language Language

Classes & Methods

Data types

Variables

Constants

Operators

Control structures

04:42 PM

Page 17: Session 2 Session 2 Java Language Fundamentals 9:17 AM

Classes in Java Classes in Java

Class declaration Syntax

class Classname {

var_datatype variablename;:

 met_datatype methodname(parameter_list):

}

04:42 PM

Page 18: Session 2 Session 2 Java Language Fundamentals 9:17 AM

Sample classSample class

04:42 PM

Page 19: Session 2 Session 2 Java Language Fundamentals 9:17 AM

Data Types Data Types

byte char boolean short int long float double

Array

Class

Interface

04:42 PM

Page 20: Session 2 Session 2 Java Language Fundamentals 9:17 AM

Integer TypesInteger TypesThe integer types are for numbers without

fractional parts. Negative values are allowed.

04:42 PM

Page 21: Session 2 Session 2 Java Language Fundamentals 9:17 AM

Floating-Point TypesFloating-Point TypesThe floating-point types denote numbers

with fractional parts

04:42 PM

Page 22: Session 2 Session 2 Java Language Fundamentals 9:17 AM

The char TypeThe char Type•The char type is used to describe individual characters.

•For example, 'A' is a character constant with value 65.

•It is different from "A", a string containing a single character. Unicode code units can be

expressed as hexadecimal values that run from \u0000 to \uFFFF.

• For example, \u2122 is the trademark symbol (™) and \u03C0 is the Greek letter pi (π).

04:42 PM

Page 23: Session 2 Session 2 Java Language Fundamentals 9:17 AM

The boolean TypeThe boolean Type The boolean type has two values, false and true. It is used for

evaluating logical conditions.

You cannot convert between integers and boolean values.

void bubbleSort(int[] x, int n) { boolean anotherPass; // true if something was out of order

do { anotherPass = false; // assume everything sorted for (int i=0; i<n-1; i++) { if (x[i] > x[i+1]) { int temp = x[i]; x[i] = x[i+1]; x[i+1] = temp; //

exchange anotherPass = true; // something wasn't sorted, keep going

} } } while (anotherPass);

}

void bubbleSort(int[] x, int n) { boolean anotherPass; // true if something was out of order

do { anotherPass = false; // assume everything sorted for (int i=0; i<n-1; i++) { if (x[i] > x[i+1]) { int temp = x[i]; x[i] = x[i+1]; x[i+1] = temp; //

exchange anotherPass = true; // something wasn't sorted, keep going

} } } while (anotherPass);

}04:42 PM

Page 24: Session 2 Session 2 Java Language Fundamentals 9:17 AM

Type CastingType Casting

In type casting, a data type is converted into another data type.

Example float c = 34.89675f;

int b = (int)c + 10;

04:42 PM

Page 25: Session 2 Session 2 Java Language Fundamentals 9:17 AM

Automatic type and Automatic type and CastingCasting

There are two type of data conversion: automatic type

conversion and casting.

When one type of data is assigned to a variable of another

type then automatic type conversion takes place provided

it meets the conditions specified:

◦ The two types are compatible

◦ The destination type is larger than the source type.

Casting is used for explicit type conversion. It loses

information above the magnitude of the value being

converted.

04:42 PM

Page 26: Session 2 Session 2 Java Language Fundamentals 9:17 AM

Type Promotion RulesType Promotion Rules

All byte and short values are promoted to int type.

If one operand is long, the whole expression is promoted to long.

If one operand is float then the whole expression is promoted to float.

If one operand is double then the whole expression is promoted to double.

04:42 PM

Page 27: Session 2 Session 2 Java Language Fundamentals 9:17 AM

04:42 PM

Page 28: Session 2 Session 2 Java Language Fundamentals 9:17 AM

VariablesVariablesThree components of a variable

declaration are:◦ Data type

◦ Name

◦ Initial value to be assigned (optional)

Syntaxdatatype identifier [=value][,

identifier[=value]...];

04:42 PM

Page 29: Session 2 Session 2 Java Language Fundamentals 9:17 AM

Initializing VariablesInitializing Variables you must explicitly initialize it by means of an assignment

statement—you can never use the values of uninitialized variables.

the Java compiler flags the following sequence of statements as an

error:

int vacationDays;

System.out.println(vacationDays); // ERROR--variable not initialized

in Java you can put declarations anywhere in your code.

double salary = 65000.0;

System.out.println(salary);

int vacationDays = 12; // ok to declare a variable here

04:42 PM

Page 30: Session 2 Session 2 Java Language Fundamentals 9:17 AM

ExampleExample

Output

class DynVar{

public static void main(String [] args){

double len = 5.0, wide = 7.0;double num = Math.sqrt(len * len + wide * wide);System.out.println("Value of num after dynamic

initialization is " + num);}

}

04:42 PM

Page 31: Session 2 Session 2 Java Language Fundamentals 9:17 AM

Scope and Lifetime of Scope and Lifetime of VariablesVariables

Variables can be declared inside a block. The block begins with an opening curly brace

and ends with a closing curly brace.A block defines a scope. A new scope is created every time a new

block is created. Scope specifies what objects are visible to

other parts of the program.It also determines the life of an object.

04:42 PM

Page 32: Session 2 Session 2 Java Language Fundamentals 9:17 AM

ExampleExampleclass ScopeVar{public static void main(String [] args){int num = 10;if ( num == 10){

// num is available in inner scopeint num1 = num * num;

System.out.println("Value of num and num1 are " + num + " " + num1);

}//num1 = 10; System.out.println("Value of num is " + num);

}}

Output

04:42 PM

Page 33: Session 2 Session 2 Java Language Fundamentals 9:17 AM

ConstantsConstants use the keyword final to denote a constant.

public class Constants

{

public static void main(String[] args)

{

final double CM_PER_INCH = 2.54;

double paperWidth = 8.5;

double paperHeight = 11;

System.out.println("Paper size in centimeters: "

+ paperWidth * CM_PER_INCH + " by " + paperHeight * CM_PER_INCH);

}

} The keyword final indicates that you can assign to the variable once, and then its

value is set once and for all. It is customary to name constants in all uppercase.

04:42 PM

Page 34: Session 2 Session 2 Java Language Fundamentals 9:17 AM

ConstantsConstants It is probably more common in

Java to want a constant that is

available to multiple methods

inside a single class. These are

usually called class constants.

You set up a class constant with

the keywords static final.

Note that the definition of the

class constant appears outside

the main method. Thus, the

constant can also be used in

other methods of the same

class.

public class Constants2

{

public static void main(String[] args)

{

double paperWidth = 8.5;

double paperHeight = 11;

System.out.println("Paper size in

centimeters: “ + paperWidth *

CM_PER_INCH + " by " + paperHeight *

CM_PER_INCH);

}

public static final double CM_PER_INCH =

2.54;

}

04:42 PM

Page 35: Session 2 Session 2 Java Language Fundamentals 9:17 AM

Array DeclarationsArray Declarations

Three ways to declare an array are:

◦datatype identifier [ ];

◦datatype identifier [ ] = new datatype[size];

◦datatype identifier [ ] = {value1,value2,….valueN};

04:42 PM

Page 36: Session 2 Session 2 Java Language Fundamentals 9:17 AM

Example – One Dimensional Example – One Dimensional ArrayArray

class ArrDemo{public static void main(String [] arg){double nums[] = {10.1, 11.3, 12.5,13.7, 14.9};System.out.println(" The value at location 3 is : " +

nums[3]);}

}

Output

04:42 PM

Page 37: Session 2 Session 2 Java Language Fundamentals 9:17 AM

Example – Multi Example – Multi Dimensional ArrayDimensional Arrayclass MultiArrayDemo

{public static void main ( String [] arg){

int multi[][] = new int [4][];multi[0] = new int[4];multi[1] = new int[4];multi[2] = new int[4];multi[3] = new int[4];int num = 0;for (int count = 0; count < 4; count++){

for (int ctr = 0; ctr < count+1; ctr++)

{multi[count][ctr] =

num;num++;

}}

for (int count = 0; count < 4; count++)

{for (int ctr = 0; ctr < count+1;

ctr++){

System.out.print(multi[count][ctr] + " ");

System.out.println();}

}}

}Output

04:42 PM

Page 38: Session 2 Session 2 Java Language Fundamentals 9:17 AM

Operators Operators

Arithmetic Operators

Bitwise Operators

Relational Operators

Logical Operators

Conditional Operators

Assignment operators04:42 PM

Page 39: Session 2 Session 2 Java Language Fundamentals 9:17 AM

Arithmetic OperatorsArithmetic Operators

Operands of the arithmetic operators must be of numeric type.

Boolean operands cannot be used, but character operands are allowed.

These operators are used in mathematical expressions.

04:42 PM

Page 40: Session 2 Session 2 Java Language Fundamentals 9:17 AM

ExampleExampleclass ArithmeticOp{

public static void main ( String [] arg){

int num = 5, num1 = 12, num2 = 20, result;result = num + num1;System.out.println("Sum of num and num1 is : (num + num1) " +

result);result = num % num1;System.out.println("Modulus of num and num1 is : (num % num1) " +

result);result *= num2;System.out.println("Product of result and num2 is : (result *=

num2) " + result);System.out.println("Value of num before the operation is : " + num);

num ++;System.out.println("Value of num after ++ operation is : " + num);double num3 = 25.75, num4 = 14.25, res;res = num3 - num4;System.out.println("num3 – num4 is : " +res);res -= 2.50;System.out.println("res -= 2.50 " + res);System.out.println("Value of res before -- operation is : "+ res);res--;System.out.println("Value of res after -- operation is : " + res);

}}

04:42 PM

Page 41: Session 2 Session 2 Java Language Fundamentals 9:17 AM

Output

04:42 PM

Page 42: Session 2 Session 2 Java Language Fundamentals 9:17 AM

Bitwise OperatorsBitwise Operators

A bitwise operator allows manipulation of

individual bits in an integral primitive data type.

These operators act upon the individual bits of their

operands.

Bitwise operators perform Boolean algebra on the

corresponding bits in the two arguments to produce

the result.

04:42 PM

Page 43: Session 2 Session 2 Java Language Fundamentals 9:17 AM

The bitwise operators are

& (“and”) | (“or”) ^ (“xor”) ~ (“not”) These operators work on bit patterns. For example, if n is an integer

variable, then

int fourthBitFromRight = (n & 8) / 8; gives you a 1 if the fourth bit from the right in the binary representation of

n is 1, and 0 if not. Using & with the appropriate power of 2 lets you mask out all but a single

bit.

04:42 PM

Page 44: Session 2 Session 2 Java Language Fundamentals 9:17 AM

Relational OperatorsRelational Operators

Relational operators test the relation

between two operands.

The result of an expression in which

relational operators are used, is Boolean

(either true or false).

Relational operators are used in control

structures.

04:42 PM

Page 45: Session 2 Session 2 Java Language Fundamentals 9:17 AM

ExampleExampleclass RelOp{

public static void main(String [] args){

float num = 10.0F;double num1 = 10.0;if (num == num1)

System.out.println ("num is equal to num1");else

System.out.println ("num is not equal to num1");}

}

Output

04:42 PM

Page 46: Session 2 Session 2 Java Language Fundamentals 9:17 AM

Logical OperatorsLogical OperatorsLogical operators work with Boolean

operands. Some operators are

◦&◦ |◦^◦!

04:42 PM

Page 47: Session 2 Session 2 Java Language Fundamentals 9:17 AM

Conditional OperatorsConditional OperatorsThe conditional operator is unique, because it is a ternary

or triadic operator that has three operands to the expression.

It can replace certain types of if-then-else statements. The code below checks whether a commuter’s age is

greater than 65 and print the message.

CommuterCategory = (CommuterAge > 65)? “Senior Citizen” : “Regular”;

04:42 PM

Page 48: Session 2 Session 2 Java Language Fundamentals 9:17 AM

Assignment OperatorsAssignment Operators

The assignment operator is a single equal sign, =, and assigns a value to a variable.

Assigning values to more than one variable can be done at a time.

In other words, it allows us to create a chain of assignments.

04:42 PM

Page 49: Session 2 Session 2 Java Language Fundamentals 9:17 AM

Operator Precedence Operator Precedence

Parentheses: ( ) and [ ] Unary Operators: +, -, ++, --, ~, !Arithmetic and Shift operators: *, /, %, +, -, >>, <<Relational Operators: >, >=, <, <=, ==, !=Logical and Bitwise Operators: &, ^, |, &&, ||, Conditional and Assignment Operators: ?=, =, *=, /=, +=, -

=Parentheses are used to change the order in which an

expression is evaluated. Any part of an expression enclosed in parentheses is evaluated first.

04:42 PM

Page 50: Session 2 Session 2 Java Language Fundamentals 9:17 AM

Mathematical Functions and Mathematical Functions and ConstantsConstants The Math class contains an assortment of mathematical functions that you

may occasionally need, depending on the kind of programming that you do.

To take the square root of a number, use the sqrt method:

double x = 4;

double y = Math.sqrt(x);

System.out.println(y); // prints 2.0

The Java programming language has no operator for raising a quantity to a

power. You must use the pow method in the Math class.

double y = Math.pow(x, a);

Math.PI

Math.E

04:42 PM

Page 51: Session 2 Session 2 Java Language Fundamentals 9:17 AM

Formatting output with Escape Formatting output with Escape Sequences Sequences Whenever an output is to be displayed on

the screen, it needs to be formatted. The formatting can be done with the help of

escape sequences that Java provides.System.out.println (“Happy \tBirthday”);

◦Output: Happy Birthday

04:42 PM

Page 52: Session 2 Session 2 Java Language Fundamentals 9:17 AM

Control FlowControl Flow All application development environments provide a decision

making process called control flow statements that direct the

application execution.

Flow control enables a developer to create an application that can

examine the existing conditions, and decide a suitable course of

action.

Loops or iteration are an important programming construct that can

be used to repeatedly execute a set of actions.

Jump statements allow the program to execute in a non-linear

fashion.

04:42 PM

Page 53: Session 2 Session 2 Java Language Fundamentals 9:17 AM

Control Flow Structures in Control Flow Structures in JavaJava

Decision-making◦if-else statement◦switch-case statement

Loops◦while loop◦do-while loop◦for loop

04:42 PM

Page 54: Session 2 Session 2 Java Language Fundamentals 9:17 AM

if-else statementif-else statement The if-else statement tests the result of a condition, and performs

appropriate actions based on the result.

It can be used to route program execution through two different paths.

The format of an if-else statement is very simple and is given below:

if (condition)

{

action1;

}

else

{

action2;

}04:42 PM

Page 55: Session 2 Session 2 Java Language Fundamentals 9:17 AM

ExampleExampleclass CheckNum{public static void main(String [] args){int num = 10;if (num % 2 == 0)System.out.println(num + " is an even number");

elseSystem.out.println(num + " is an odd number");

}}

Output

04:42 PM

Page 56: Session 2 Session 2 Java Language Fundamentals 9:17 AM

switch – case statementswitch – case statementThe switch – case statement can be used in

place of if-else-if statement.

It is used in situations where the expression

being evaluated results in multiple values.

The use of the switch-case statement

leads to simpler code, and better

performance.

04:42 PM

Page 57: Session 2 Session 2 Java Language Fundamentals 9:17 AM

ExampleExampleclass SwitchDemo{

public static void main(String[] args){

int day = 4;String str;switch (day){

case 0: str = "Sunday";break;

case 1: str = "Monday"; break;

case 2: str = "Tuesday"; break;

case 3: str =

"Wednesday"; break;

case 4: str = "Thursday"; break;

case 5: str =

"Friday";

break;case 6:

str = "Saturday";

break;

default: str = "Invalid

day"; }

System.out.println(str);}

}Output

04:42 PM

Page 58: Session 2 Session 2 Java Language Fundamentals 9:17 AM

while Loopwhile Loop while loops are used for situations when a loop has to be executed as

long as certain condition is True.

The number of times a loop is to be executed is not pre-determined, but

depends on the condition.

The syntax is:

while (condition)

{

action statements;

.

.

.

}

04:42 PM

Page 59: Session 2 Session 2 Java Language Fundamentals 9:17 AM

ExampleExampleclass FactDemo{public static void main(String [] args){int num = 5, fact = 1;while (num >= 1){

fact *= num; num--;}System.out.println("The factorial of 5 is : " + fact);

}}

Output

04:42 PM

Page 60: Session 2 Session 2 Java Language Fundamentals 9:17 AM

do – while Loopdo – while Loop The do-while loop executes certain statements till the specified

condition is True.

These loops are similar to the while loops, except that a do-while

loop executes at least once, even if the specified condition is False. The

syntax is:

do

{

action statements;

.

.

} while (condition);

04:42 PM

Page 61: Session 2 Session 2 Java Language Fundamentals 9:17 AM

ExampleExampleclass DoWhileDemo{public static void main(String [] args){int count = 1, sum = 0;do{

sum += count;count++;

}while (count <= 100);System.out.println("The sum of first 100 numbers

is : " + sum);}

}

The sum of first 100 numbers is : 5050

Output

04:42 PM

Page 62: Session 2 Session 2 Java Language Fundamentals 9:17 AM

for Loopfor Loop All loops have some common features: a counter variable that is initialized before the

loop begins, a condition that tests the counter variable and a statement that modifies

the value of the counter variable.

The for loop provides a compact format for incorporating these features.

Syntax:

for (initialization statements; condition; increment / decrement statements)

{

action statements;

.

.

}04:42 PM

Page 63: Session 2 Session 2 Java Language Fundamentals 9:17 AM

ExampleExampleclass ForDemo{

public static void main(String [] args){

int count = 1, sum = 0;for (count = 1; count <= 10; count += 2){

sum += count;}System.out.println("The sum of first 5 odd

numbers is : " + sum);}

}

The sum of first 5 odd numbers is : 25

Output

04:42 PM

Page 64: Session 2 Session 2 Java Language Fundamentals 9:17 AM

Jump StatementsJump StatementsThree jump statements are:

◦break◦continue◦return

The three uses of break statements are: ◦It terminates a statement sequence in a switch

statement.◦It can be used to exit a loop.◦It is another form of goto.

04:42 PM

Page 65: Session 2 Session 2 Java Language Fundamentals 9:17 AM

ExampleExampleclass BrDemoAppl{

public static void main(String [] args){

for (int count = 1; count <= 100; count++)

{ if (count == 10)

break; System.out.println("The value of

num is : " + count); }

System.out.println("The loop is over");}

}

The value of num is : 1The value of num is : 2The value of num is : 3The value of num is : 4The value of num is : 5The value of num is : 6The value of num is : 7The value of num is : 8The value of num is : 9The loop is over

Output

04:42 PM

Page 66: Session 2 Session 2 Java Language Fundamentals 9:17 AM

SummarySummary A Java program consists of a set of classes. A program may contain comments.

The compiler ignores this commented lines.

The Java program must have a main() method from where it begins its

execution.

Classes define a template for units that store data and code related to an entity.

Variables defined in a class are called the instance variables.

There are two types of casting:widening and narrowing casting.

Variables are basic unit of storage.

Each variable has a scope and lifetime.

Arrays are used to store several items of same data type in consecutive memory

locations.

04:42 PM

Page 67: Session 2 Session 2 Java Language Fundamentals 9:17 AM

Summary Contd…Summary Contd… Java provides different types of operators. They include:

◦ Arithmetic

◦ Bitwise

◦ Relational

◦ Logical

◦ Conditional

◦ Assignment

Java supports the following programming constructs:

◦ if-else

◦ switch

◦ for

◦ while

◦ do-while The three jump statements-break,continue and return helps to transfer

control to another part of the program.

04:42 PM