0% found this document useful (0 votes)
81 views

Chapter 1

The document discusses basic syntactical constructs in Java including: - Java features such as being object oriented, compiled, interpreted, platform independent, robust and secure. - Defining a class including creating objects and accessing class members. - Java tokens and data types such as variables, data types, arrays and strings. - Operators and expressions including arithmetic, relational, logical operators and operator precedence. - Decision making and looping constructs such as if/else statements, switch statements, while, do-while and for loops.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
81 views

Chapter 1

The document discusses basic syntactical constructs in Java including: - Java features such as being object oriented, compiled, interpreted, platform independent, robust and secure. - Defining a class including creating objects and accessing class members. - Java tokens and data types such as variables, data types, arrays and strings. - Operators and expressions including arithmetic, relational, logical operators and operator precedence. - Decision making and looping constructs such as if/else statements, switch statements, while, do-while and for loops.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

Chapter 1: Basic Syntactical Constructs in Java

Chapter 1: Basic Syntactical Constructs in Java


CONTENTS
1.1 Java Features and the Java Programming Environment.
● Object Oriented
● Compiled
● Interpreted
● Platform independent and Portable
● Robust and Secure
● Dynamic.
1.2 Defining a Class
● Creating Object
● Accessing class members
1.3 Java Tokens & Data types
● Constants & Symbolic Constants,
● Variables,
● Dynamic initialization,
● Data types,
● Array & string,
● Scope of variable,
● Type casting,
● Standard default values.
1.4 Operators & Expressions
● Arithmetic Operators,
● Relational Operators,
● Logical Operators,
● Increment & Decrement,
● Conditional Operators,
● Bit wise Operators,
● Instance of Operators,
● Dot Operators,
● Operator precedence & associativity,
● Evaluation of Expressions,
● Type conversions in expressions,
● Mathematical Functions - min (), max (), sqrt (), pow (), exp (), round (), abs ().
1.5 Decision making & looping
● If statement,
● if else statement,
● Nested if else statement,
● if else if ladder,
● The switch statement,
● Nested switch statement,
● The?: operator,
● The while statement,
● The do while statement,
● The ‘for’ statement,
● break, continue & return statement,
● Nested loops,
● Labeled loops,
● For-each version of for loop.

Mrs. A. R. Sonawane Lecturer CM Dept. K. K. Wagh Polytechnic, Nashik


Chapter 1: Basic Syntactical Constructs in Java
1.1 Java Features and the Java Programming Environment.

Questions:
1. Explain Any 4 Features Of Java.
2. Explain: Platform Independence, Complied And Interpreted Features Of Java.
3. What Is JVM? What Is Byte Code?
4. Define JDK. List The Tools Available In JDK. Explain One In Details?
5. What Is Byte Code? Explain Any Tools Available In JDK.

Java Features
1. Compiled and Interpreted
2. Platform – Independent and Portable
3. Object – Oriented
4. Robust and Secure
5. Distributed
6. Dynamic and Extensible

1. Compiled and Interpreted


● Java is the only language, which has compiler and interpreter both. This has
been designed to ensure platform independence nature for the language. Due
to this Java has been made a two-stage system.
● First, Java complier translates the source code into byte code instructions and
thereafter in the second stage, Java interpreter generates machine code that
can be directly executed by machine that is running Java program.
● This provides portability to any machine for which a Java virtual machine
has been written. It also allows for extensive code checking and improved
security.

2. Platform – Independent and Portable


● The most significant contribution of Java over the other languages is its
portability. Java programs can be easily moved from one computer system to
another, anywhere and anytime. Changes and upgrades in operating systems,
processors and system resources will not force any changes in Java programs.
● This is the reason why Java has become popular language for programming on
Internet which interconnects different kinds of systems worldwide.
● We can download Java applet from a remote computer onto our local system
via Internet and execute it locally. This makes the Internet an extension of the
user’s basic system providing practically unlimited number of accessible
applets and applications.
● Java ensures portability in two ways. First, Java compiler generates byte code
instructions that can be implemented on any machine. Secondly, the size of
primitive data types are machine – independent.

3. Object – Oriented
● Java is strictly or truly object-oriented language due to the following reasons.
o Everything in Java is considered as the object including the source
program because it is written in a class itself.
o The object model in Java is simple and easy to extend, while simple
types, such as integers, are kept as high-performance non objects.

Mrs. A. R. Sonawane Lecturer CM Dept. K. K. Wagh Polytechnic, Nashik


Chapter 1: Basic Syntactical Constructs in Java
o Java implements all of the features of Object oriented programming
including inheritance, polymorphism, dynamic binding etc. An
extensive class library is also available in the core language packages.
o The library of Java is created in terms of package. It is a collection of
similar working classes. The methods are defined in the classes. In
order to use these methods we need to import the package in our
program.
o The Java class library (API) itself implemented inheritance of classes
in order to re-use the code. Thus simplifying the program also.
o Most of the methods and constructors of the Java classes are
overloaded. That is, Java itself implements the property of
polymorphism in large extent.
o Java does not support the multiple inheritance to avoid the duplication
of data. But multiple inheritance in supported by the way of ‘interface’.
Using interface, we can create the multiple inheritance by avoiding
duplication of data.
o Java does not support the concept of global variables in any case. Thus
data encapsulation is strictly supported.

4. Robust and Secure


● Java is a robust language. It provide many safeguards to ensure reliable code.
It has strict compile time and run time checking for data types. It is designed
as a garbage – collected language relieving the programmers virtually all
memory management problems.
● Java also incorporates the concept of exception handling which captures
serious errors and eliminates any risk of crashing the system.
● Security becomes an important issue for a language that is used for
programming on Internet. Threat of viruses and abuse of resources are
everywhere. Java systems not only verify all memory access but also ensure
that no viruses are communicated with an applet.
● The absence of pointers in Java ensures that programs cannot gain access to
memory locations without proper authorization.

5. Distributed
● Java is designed as a distributed language for creating applications on
networks. It has the ability to share both data and programs.
● Java applications can open and access remote objects on Internet as easily as
they can do in local system. This enables multiple programmers at a multiple
remote locations to collaborate and work together on a single project.

6. Dynamic and Extensible


● Java is a dynamic language. Java is capable of dynamically linking in new
class libraries, methods and objects. We can add the code to a Java application
at run time. Java can also determine the type of class through a query, making
it possible to either dynamically link or abort the program, depending on the
response.
● Java program supports function written in other languages such as C/C++.
These functions are known as native methods. This facility enables the
programmer to use efficient functions available in other languages. Native
methods are linked dynamically at run time.

Mrs. A. R. Sonawane Lecturer CM Dept. K. K. Wagh Polytechnic, Nashik


Chapter 1: Basic Syntactical Constructs in Java
Java Environment

Java environment includes a large number of development tools and hundreds of


classes and methods. The development tools are part of the system known as Java
Development Kit (JDK) and the classes and methods are part of the Java Standard
Library (JSL), also known as Application Programming Interface (API).

● Java Development Kit


The Java Development Kit comes with a collection of tools that are
used for developing and running Java programs. They include:
o appletviewer (for viewing Java applets)
o javac (Java Compiler)
o java (Java interpreter)
o javap (Java Disassembler)
o javah (for C header files)
o javadoc (for creating HTML documents)
o jdb (Java Debugger)

Table: Java Development Tools


Tool Description
appletviewer Enables us to run Java applets (without actually using a Java –
compatible browser).
Java Java interpreter, which runs applets and applications by reading
and interpreting byte code files.
Javac The Java compiler, which translates java source code to byte code
files that interpreter can understand.
Javadoc Creates HTML – format documentation from Java source code
files.
Javah Produces header files for use with native methods.
Javap Java disassembler, which enables us to convert byte code files into
a program description.
Jdb Java debugger, which helps us to find errors in our programs.

● Application Programming interface


o The Java Standard Library (or API) includes hundreds of classes
and methods grouped into several functional packages. Most
commonly used packages are:
1. Language Support Package
2. Utilities Package
3. Input/Output Package
4. Networking Package
5. AWT Package
6. Applet Package

Byte Code
o The Java compiler creates a byte code. This is the machine independent code so, it
can be executed on any machine.

Mrs. A. R. Sonawane Lecturer CM Dept. K. K. Wagh Polytechnic, Nashik


Chapter 1: Basic Syntactical Constructs in Java
o In order to make the Java as machine independent language, the byte code is
introduced. However, the Java Development Kit installed on different machine is
different for all of them.
o Byte code is the compiled format for Java programs. Once a Java program has
been converted to byte code, it can be transferred across a network and executed
by Java Virtual Machine (JVM). A Byte code file generally has a .class extension.

Java Virtual Machine (JVM)


o The java compiler compiles produces an intermediate code known as byte
code for the java virtual machine, which exists only in the computer memory
It is a simulated computer within the computer and does all the major
functions of a real computer.

o Virtual machine code is not machine specific Machine specific code is


generated by Java Interpreter by acting as an intermediary between the virtual
machine and the real machine. Interpreter is written for each type of machine.

Java Program Structure

Documentation Section
Package Statement
Import Statements
Interface Statements
Class Definitions

Main Method Class

1.2 Java Tokens & Data types


Questions
1. What Do You Mean By Casting? What Is Its Need?

Mrs. A. R. Sonawane Lecturer CM Dept. K. K. Wagh Polytechnic, Nashik


Chapter 1: Basic Syntactical Constructs in Java
Tokens
A smallest individual element in a program is called as token. Java includes five
different types of tokens. They are:
● Identifiers
● Keywords
● Literals
● Operators
● Separators

Identifiers:
Identifiers are the programmer-designed tokens. They are used for naming
variables, classes, methods, objects, labels, packages and interfaces in a program.
Java identifiers follow following rules:
1. They can have alphabets, digits, and the underscore and dollar sign
characters.
2. They can have be of any length.
3. They must not begin with a digit.
4. Uppercase and Lowercase letters are distinct.
5. They must not be the keywords.
Keywords:
Keywords are an essential part of a language definition. These are also called
as reserved words. Java has given a special meaning for certain words. These
words are reserved for only the defined purpose in the programming. They
cannot be used for any other purpose. We cannot use them for the name of
variables, classes or methods.
All keywords are to be written only in lower case letters. Since, Java is case
sensitive; we can use these words as name of variables, classes or methods by
changing their case. However, being a good programmer it should be
avoided.
Literals
Literals in Java are a sequence of characters (digits, letters, and other characters)
that represent constant values to be stored in variables. Java language specifies
following type of literals:
● Integer literals
● Floating Point literals
● Character literals
● String literals
● Boolean Literals
● Null literal
Operators
An operator is a symbol that takes one or more arguments and operates on
them to produce a result.

Mrs. A. R. Sonawane Lecturer CM Dept. K. K. Wagh Polytechnic, Nashik


Chapter 1: Basic Syntactical Constructs in Java

Separators
Separators are symbols used to indicate where group of code are divided and
arranged. They basically define the shape and function of our code.

Constants and Symbolic Constants


Constants in Java refer to fixed values that do not change during the execution of a
program. Java supports several types of constants.

Mrs. A. R. Sonawane Lecturer CM Dept. K. K. Wagh Polytechnic, Nashik


Chapter 1: Basic Syntactical Constructs in Java

Figure: Java Constants

i. Integer constants
● Integers are probably the most commonly used type in the typical program. Any
whole number value is an integer literal.
● Examples are 1, 2, 3, and 42.
● Octal values are denoted in Java by a leading zero.
● Examples are 025, 041, 02 etc.
● Normal decimal numbers cannot have a leading zero. Thus, the seemingly valid
value 09 will produce an error from the compiler, since 9 is outside of octal’s 0 to
7 range. A more common base for numbers used by programmers is hexadecimal,
which matches cleanly with modulo 8 word sizes, such as 8, 16, 32, and 64 bits.
● You signify a hexadecimal constant with a leading zero-x, (0x or 0X). The range
of a hexadecimal digit is 0 to 15, so A through F (or a through f) are substituted
for 10 through 15.
● Examples are 0x4A, 0x85, 0xF9 etc.
● We rarely use the octal and hexadecimal integers in a program. Integer literals
create an int value, which in Java is a 32-bit integer value.
ii. Floating-point Constants
● These are also called as real constants. Floating-point numbers represent decimal
values with a fractional component. They can be expressed in either standard or
scientific notation. Standard notation consists of a whole number component
followed by a decimal point followed by a fractional component.
● For example, 2.000, 53.19259, and 0.6667 represent valid standard-notation
floating-point numbers.
● Scientific notation uses a standard-notation, floating-point number plus a suffix
that specifies a power of 10 by which the number is to be multiplied. The
exponent is indicated by an E or e followed by a decimal number, which can be
positive or negative. It is expressed in following format:
Mantissa e exponent
● Where mantissa is either a real number expressed in decimal notation or integer.
The exponent is an integer with an optional + or – sign.

Mrs. A. R. Sonawane Lecturer CM Dept. K. K. Wagh Polytechnic, Nashik


Chapter 1: Basic Syntactical Constructs in Java
● Examples: 6.0032E23, 314159E–05, and 2e+100. Floating-point constants in
Java default to double precision.
● To specify a float literal, you must append an F or f to the constant.
● You can also explicitly specify a double literal by appending a D or d. doing so is,
of course, redundant. The default double type consumes 64 bits of storage, while
the less-accurate float type requires only 32 bits.
iii. Character Constants
● Characters in Java are indices into the Unicode character set. They are 16-bit
values that can be converted into integers and manipulated with the integer
operators, such as the addition and subtraction operators.
● A literal character is represented inside a pair of single quotes. All of the visible
ASCII characters can be directly entered inside the quotes, such as ‘x’, ‘k’, and
‘@’.
● For characters that are impossible to enter directly, there are several escape
sequences, which allow you to enter the character you need, such as ‘\’’ for the
single quote character itself, and ‘\n’ for the new-line character. Following are the
escape sequences used in Java.

Escape Meaning
\n New Line
\t Tab
\b Back Space
\r Carriage Return
\\ Form – Feed
\’ Single Quote
\” Double Quote
Table: Escape Characters
● There is also a mechanism for directly entering the value of a character in octal or
hexadecimal. For octal notation use the backslash followed by the three-digit
number. For example, ‘\141’ is the letter ‘a’. For hexadecimal, you enter a
backslash-u (\u), then exactly four hexadecimal digits. For example, ‘\u0900’ to
‘\u97f’ is used for Devanagari character display. ‘\ua432’ is a Japanese Katakana
character.

iv. String Constants


● String constants in Java are specified as they are in most other languages—by
enclosing a sequence of characters between a pair of double quotes. Examples of
string literals are:
● “Hello World” “This is first and \n This is second” “\”I love Java
Programming\”” “156…. + 856” “[email protected]
● The escape sequences and octal\hexadecimal notations that were defined for
character constants work the same way inside of string constants. One important
thing to note about Java strings is that they must begin and end on the same line.
There is no line-continuation escape sequence as there is in other languages.
C/C++ implements the string as array of characters, but in Java it is not the case.
Here, string is the object type.

v. Boolean Constants
● There are only two logical values that a boolean value can have i.e. true and false.
● The values of true and false do not convert into any numerical representation. The
true constant in Java does not equal 1, nor does the false constant equal 0. In Java,
they can only be assigned to variables declared as boolean, or used in expressions
with Boolean operators.

Mrs. A. R. Sonawane Lecturer CM Dept. K. K. Wagh Polytechnic, Nashik


Chapter 1: Basic Syntactical Constructs in Java
Symbolic Constants
We often use certain unique constants in a program. These constants may appear
repeatedly in a number of places in the program. One example of such a constant is
3.142, representing the value of the mathematical constant “pi”. Another example is
the total number of students whose mark sheets are analyzed by a “test analysis
program”. The number of students, say 50, may be used for calculating the class total,
class average, standard deviation etc.
SYNTAX:
final type symbolic_name = value;
EXAMPLE:
final int PI = 3.142;

Data Types

Type Size Minimum value Maximum value


byte 1 byte -128 127
short 2 byte -32,768 32,767
int 4 byte -2,147,483,648 2147483647

long 8 byte -9,223,372,036,854,775,808 922337203685477580


7
float 4 byte 3.4e - 038 1.7e + 308
double 8 byte 3.4e - 038 1.7e + 0.38
char 2 byte

Mrs. A. R. Sonawane Lecturer CM Dept. K. K. Wagh Polytechnic, Nashik


Chapter 1: Basic Syntactical Constructs in Java
boolean 1 byte

Declaration of variable:
Syntax:
Type vatiable1, variable2 ………….. variableN;
Assignment statement
1. Variable_name = value;
2. Type variable_name = value;

Scope of variable
● Instance variables
● Class variables
● Local variables

1. Instance Variables:
Instance variables are created when the objects are instantiated and therefore they are
associated with the objects. They take different values for each objects.
2. Class Variables:
Class variable are global to s class and belong to the entire set of objects that class
creates. Only one memory location is created for each class variable.
3. Local Variables:
Variables declared and used inside methods are called local variables. They are called so
because they are not available for use outside the method definition.

Type casting:
The process of converting one data type to another is called casting or type casting. If the two
types are compatible, then java will perform the conversion automatically. It is possible to
assign an int value to long variable. However if the two types of variables are not compatible,
the type conversions are not implicitly allowed, hence the need for type casting.
Syntax:
Type variable1 = (type) variable2;
Examples:
int m = 50;
byte n = (byte) m;
long count = (long) m;

Type casting is of three types:


1. Narrowing,
2. Widening.
3. Automatic conversion
● The process of assigning a smaller type to a larger one is known as widening or
promotion.

● The process of assigning a larger type into a smaller one is called narrowing.

● For some types, it is possible to assign a value of one type to a variable of a different
type without a cast. Java does the conversion of the assigned value automatically.
This is known as automatic – type conversion. It is possible if the destination type
has enough precession to store the source value.

Casting is necessary when a value of one type is to be assigned to a different type of variable.
It may also be needed when a method returns a type different than the one we require. Generic
type casting helps in the retrieval of elements from a collection as each element in a collection
is considered to be an object.

Mrs. A. R. Sonawane Lecturer CM Dept. K. K. Wagh Polytechnic, Nashik


Chapter 1: Basic Syntactical Constructs in Java
1.3 Operators & Expressions
1) Arithmetic
They are used to construct mathematical expressions as in algebra.
+ , - , * , /, %

2) Relational
They are used to compare two quantities.
< , > , <= , >= , == , !=

3) Logical
The logical operator && and || are used when we want to form compound conditions by
combining two or more relations.
&& , || , !

4) Assignment
They are used to assign the value of an expression to a variable.
= , += , *= , -= , /= etc.

5) Increment / Decrement
These operators are used to increment and decrement value by 1.
It has two types:
1. Pre INC \ DEC ++a / --a
2. Post INC \ DEC a++ / a--

6) Conditional
Also called as ternary operator.
?:
Syntax:
Condition? Expression1: Expression2
It takes three arguments. The first argument is comparison argument. The second is the
result upon a true comparison and the third is the result upon a false comparison.

7) Bitwise
Java has a distinction of supporting special operators known as bitwise operators for
manipulation of data at values of bit level.

1. Bitwise NOT (~): Called bitwise complement the unary NOT operator, inverts all of
the bits of its operand.
2. Bitwise AND (&): It produce a 1 bit if both operands are also 1, a zero is produced
in all the cases.
E.g. – 0101 (decimal 5) & 0011 (decimal 3)
0001 (decimal 1)
3. Bitwise OR (|): it combines bit such that if either of the bits in the operand is a 1 then
the resultant bit is a 1.
4. Bitwise XOR (^)
5. The left shift (<<)
6. The right shift (>>)
7. Unsigned right shift (>>>>)

8) Special
a) instanceOf Operator
It is an object reference operator and returns true if the object on the left – hand
side is an instance of the class given on the right- hand side. It allows us to
determine whether the object belongs to a particular class or not.

Mrs. A. R. Sonawane Lecturer CM Dept. K. K. Wagh Polytechnic, Nashik


Chapter 1: Basic Syntactical Constructs in Java
b) Dot Operator
The Dot operator (.) is used to access the instance variables and methods of class
objects. It is also used to access classes and sub-packages from a package.

Evaluation of Expressions:
Expressions are evaluated using assignment statement.
Variable = expression;
Example: x = a * b – c;
y= b / c * a;

Mathematical Functions:
Sr. Method Description
No.
1. static double cbrt(double arg) Returns cube root of arg
2. static double pow(double y, double x) Returns y raised to x
3. static double sqrt(double arg) Returns square root of arg
4. static int abs(int arg) Returns absolute value of arg
static long abs(long arg)
static double abs(double arg)
static float abs(float arg)
5. static int max(int arg1, int arg2) Returns maximum value between arg1 and arg2

static long max(long arg1, long arg2)


static double max(double arg1, double arg2)
static float max(float arg1, float arg2)
6. static int min(int arg1, int arg2) Returns minimum value between arg1 and arg2

static long min(long arg1, long arg2)


static double min(double arg1, double arg2)
static float min(float arg1, float arg2)
7. static double ceil(double arg) Returns the smallest whole number greater than
or equal to arg
8. static double floor(double arg) Returns the largest whole number less than or
equal to arg

1.4 Decision making & looping.


If Statement
Syntax:
if (text expression)
{ //TRUE
//Statements
}
Statement – X; //FALSE

1) If ….. else Statement


Syntax:
if (text expression)
{ //TRUE
//Statements
}
else
{
//Statement; //FALSE
}

Mrs. A. R. Sonawane Lecturer CM Dept. K. K. Wagh Polytechnic, Nashik


Chapter 1: Basic Syntactical Constructs in Java
Statement – X;

2) Nested if else statements


Syntax:
if (text expression1)
{
if (text expression2)
{
//Statements
}
else
{
//Statements
}
}
else
{
//Statement;
}
Statement – X;

3) If else if ladder
Syntax:
if (text expression1)
{
//Statements
}
else if (text expression 2)
//Statement
.
.
.
else if (text expression N)
//statement N
else
{
//Statement;
}
Statement – X;

4) Switch statement
switch ( expression)
{
Case value – 1:
Block 1;
break;
Case value – 2:
Block 2;
break;
……….
………
default:
Default Block;
break;

Mrs. A. R. Sonawane Lecturer CM Dept. K. K. Wagh Polytechnic, Nashik


Chapter 1: Basic Syntactical Constructs in Java
Statement – X;

5) The ?: operator
The java language has an unusual operator, useful for making two – way decisions. This
operator is a combination of ? and : and takes three operands.
Conditional expression? Expression1: expression2;

6) While statement
Initialization;
while (test condition)
{
Body of the loop
}

7) Do statement
Initialization;
do{
Body of loop;
}while(condition);

While Do – while
It is a looping construct that will execute It is a looping construct that will execute
only if the test condition is true. at least once even if the test condition is
false.
It is an entry – controlled loop. It is an exit – controlled loop.
It is generally used for implementing It is typically used for implementing
common looping situations. menu based programs where, the menu is
required to be printed at least once.

8) For statement
for(initialization; test condition; increment/decrement)
{
Body of loop
}

9) Nesting of for loops


for(initialization; test condition; increment/decrement)
{
…………….. //OUTER Loop
for(initialization; test condition; increment/decrement)
{
Body of loop //INNER Loop
}
Body of loop
}

10) Enhanced for loops


It is also called as for each loop.
It is an extended language feature introduce with J@SE 5.0 release.
It helps us to retrieve the array of elements efficiently rather than the using array indexes.
If you won’t be modifying the contents of a collection or obtaining elements in reverse
order, then the for-each version of the for loop is often a more convenient alternative to
cycling through a collection than is using an iterator.
Recall that the for can cycle through any collection of objects that implement the Iterable
interface. Because all of the collection classes implement this interface, they can all be
operated upon by the for.

Mrs. A. R. Sonawane Lecturer CM Dept. K. K. Wagh Polytechnic, Nashik


Chapter 1: Basic Syntactical Constructs in Java
// Use the for-each for loop to cycle through a collection.
// Use a for-each style for loop.
Syntax:
for(data_type variable : array | collection) {}
Example
class ForEach
{
public static void main(String args[])
{
int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int sum = 0; // use for-each style for to display and sum the values
for(int x : nums)
{
System.out.println ("Value is: " + x); sum += x;
}
System.out.println ("Summation: " + sum);
}
}

11) Jump statements


a) Break (early exit)
The break keyword is used to stop the entire loop.
The break keyword must be used inside any loop or a switch statement.
The break keyword will stop the execution of the innermost loop and start
executing the next line of code after the block.
Example:
public class Test
{
public static void main(String args[])
{
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers )
{
if( x == 30 )
{
break;
}
System.out.print ( x );
System.out.print ("\n");
}
}
}
b) Continue (Early entry)
The continue statement skips the current iteration of a for, while, or do-while
loop.
The unlabeled form skips to the end of the innermost loop's body and evaluates
the boolean expression that controls the loop.
A labeled continue statement skips the current iteration of an outer loop marked
with the given label.
Example:
public class Test
{
public static void main(String args[])
{
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers )

Mrs. A. R. Sonawane Lecturer CM Dept. K. K. Wagh Polytechnic, Nashik


Chapter 1: Basic Syntactical Constructs in Java
{
if( x == 30 )
{
continue;
}
System.out.print ( x );
System.out.print ("\n");
}
}
}

c) Normal Execution (Labelled)


In java, we can give a label to a block of statements. A label is any valid java
variable name. To give a label to a loop, place it before the loop with a colon at
the end.
Loop1:
for (………)
{
………
………
}
……….

With break;
Loop1:
for (………)
{
for(…..)
{
………
break Loop1;
}
}
…………..

With continue
Loop1:
for (………)
{
for(…..)
{
………
continue Loop1;
}
}

Mrs. A. R. Sonawane Lecturer CM Dept. K. K. Wagh Polytechnic, Nashik

You might also like