Java Notes(Module 1) (DR.shiavani) (1)
Java Notes(Module 1) (DR.shiavani) (1)
Java Development Kit contains two parts. One part contains the utilities like
javac, debugger, jar which helps in compiling the source code (.java files) into
byte code (.class files) and debug the programs. The other part is the JRE,
which contains the utilities like java which help in running/executing the byte
code. If we want to write programs and run them, then we need the JDK
installed.
Java Run-time Environment helps in running the programs. JRE contains the
JVM, the java classes/packages and the run-time libraries. If we do not want to
write programs, but only execute the programs written by others, then JRE
alone will be sufficient.
Java Virtual Machine is important part of the JRE, which actually runs the
programs (.class files), it uses the java class libraries and the run-time libraries
to execute those programs. Every operating system(OS) or platform will have a
different JVM.
JIT is a module inside the JVM which helps in compiling certain parts of byte
code into the machine code for higher performance. Note that only certain parts
of byte code will be compiled to the machine code, the other parts are usually
interpreted and executed.
Java is distributed in two packages - JDK and JRE. When JDK is installed it
also contains the JRE, JVM and JIT apart from the compiler, debugging tools.
When JRE is installed it contains the JVM and JIT and the class libraries.
javac helps in compiling the program and java helps in running the program.
When the words Java Compiler, Compiler or javac is used it refers to javac,
when the words JRE, Run-time Enviroment, JVM, Virtual Machine are
used, it refers to java.
Simple
Java was designed to be easy for the professional programmer to learn and use
effectively. If you already understand the basic concepts of object-oriented
programming like C++, learning Java will be even easier.
Object Oriented:
In Java, everything is an Object. The object model in Java is simple and easy to
extend, while primitive types, such as integers, are kept as high-performance
non-objects.
Platform Independent:
Unlike many other programming languages including C and C++, when Java is
compiled, it is not compiled into platform specific machine, rather into platform
independent byte code. This byte code is distributed over the web and
interpreted by the Virtual Machine (JVM) on whichever platform it is being run
on.
To better understand how Java is robust, consider two of the main reasons for
program failure: memory management mistakes and mishandled exceptional
conditions. For example, in C/C++, the programmer must manually allocate and
free all dynamic memory. This sometimes leads to problems, because
programmers will either forget to free memory that has been previously
allocated or, worse, try to free some memory that another part of their code is
still using. Java virtually eliminates these problems by managing memory
allocation and de-allocation for you. Java helps in this area by providing object-
oriented exception handling.
High Performance: With the use of Just-In-Time compilers, Java enables high
performance.
Distributed: Java is designed for the distributed environment of the internet.
Java also supports Remote Method Invocation (RMI). It handles TCP/IP
protocols.
Dynamic: Java is considered to be more dynamic than C or C++ since it is
designed to adapt to an evolving environment. Java programs can carry
extensive amount of run-time information that can be used to verify and resolve
accesses to objects on run-time.
History of Java
James Gosling initiated Java language project in June 1991 for use in one of his
many set-top box projects. The language, initially called ‘Oak’ after an oak tree
that stood outside Gosling's office, also went by the name ‘Green’ and ended up
later being renamed as Java, from a list of random words.
Sun released the first public implementation as Java 1.0 in 1995. It promised
Write Once, Run Anywhere (WORA), providing no-cost run-times on popular
platforms.
On 13 November, 2006, Sun released much of Java as free and open source
software under the terms of the GNU General Public License (GPL).
On 8 May, 2007, Sun finished the process, making all of Java's core code free
and open-source, aside from a small portion of code to which Sun did not hold
the copyright.
Three OO Concepts:
Encapsulation
Inheritance
Polymorphism
Encapsulation
Encapsulation is the mechanism that binds together code and the data it
manipulates, and keeps both safe from outside interference and misuse. It acts
as a protective wrapper that prevents the code and data from being arbitrarily
accessed by other code defined outside the wrapper. Access to the code and data
inside the wrapper is tightly controlled through a well-defined interface.
A class defines the structure and behaviour (data and code) that will be shared
by a set of objects. Each object of a given class contains the structure and
behaviour defined by the class. For this reason, objects are sometimes referred
to as instances of a class.
When you create a class, you will specify the code and data that constitute that
class. Collectively, these elements are called members of the class. Specifically,
the data defined by the class are referred to as member variables or instance
variables. The code that operates on that data is referred to as member
methods or just methods.
Inheritance
Inheritance is the process by which one object acquires the properties of another
object. This is important because it supports the concept of hierarchical
classification.
The class which inherits the properties of other is known as subclass (derived
class, child class) and the class whose properties are inherited is known as
superclass (base class, parent class).
Since mammals are simply more precisely specified animals, they inherit all of
the attributes from animals. A deeply inherited subclass inherits all of the
attributes from each of its ancestors in the class hierarchy.
Polymorphism
Example: Consider a stack (which is a last-in, first-out list). You might have a
program that requires three types of stacks. One stack is used for integer values,
one for floating-point values, and one for characters. The algorithm that
implements each stack is the same, even though the data being stored differs.
Java Basics
COMMENTS
This line outputs the string “This is a simple Java program.” followed by a new
line on the
screen. In this case, println( )displays the string which is passed to it.
System is a predefined class that provides access to the system, and out is the
output stream that is connected to the console.
Primitive Datatypes
There are eight primitive datatypes supported by Java.
Its default value is ‘\u0000’ with the max value being ‘\uffff’ and has a size of 2 bytes.
It must be confusing for you to see this new kind of data ‘/u000’. This is the
unicode format which java uses inplace of ASCII.
}
}
Output would be
Value of char variable ch1 is :a
Value of char variable ch2 is :A
Byte are useful when you’re working with raw binary data that may not
be directly compatible with Java’s other built-in types.
It’s an 8 bit signed two’s complement . The range of values are -128
to 127. It is space efficient because it is smaller than integer datatype.
It can be a replacement for int datatype usage but it doesn’t have the
size range as the integer datatype.
byte b1 = 100;
byte b2 = 20;
Output would be
Value of byte variable b1 is :100
Value of byte variable b1 is :20
boolean b1 = true;
boolean b2 = false;
boolean b3 = (10 > 2)? true:false;
Its default value is 0.0f and has a size of 4 bytes. It has an infinite
value range. However its always advised to use float in place of
double if there is a memory constraint. Currency should also never be
stored in float datatype. However it has a single precision bit.
import java.util.*;
double d = 1232.44;
System.out.println("Value of double variable d is :" +
d);
}
}
Output would be
Value of double variable f is :1232.44
Java Literals
For example:
byte a = 68;
char a = 'A'
Integer Literals:
Int x = 101;
Octal (Base 8)
Digits from 0 – 7 are allowed. It should always have a prefix 0.
int x = 0146;
Binary
A literal in this type should have a prefix 0b and 0B, from 1.7 one can also
specify in binary literals, i.e. 0 and 1.
int x = 0b1111;
Single Quote
Java Literal can be specified to a char data type as a single character within
a single quote.
char ch = 'a';
Char as Integral
A char literal in Java can specify as integral literal which also represents the
Unicode value of a character.
Furthermore, an integer can specify in decimal, octal and even hexadecimal
type, but the range is 0-65535.
char ch = 062;
Unicode Representation
Char literals can specify in Unicode representation ‘\uxxxx’. Here XXXX
represents 4 hexadecimal numbers.
Escape Sequence
Escape sequences can also specify as char literal.
char ch = '\n';
String literals in Java are specified like 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"
"two\nlines"
"\"This is in quotes\""
String and char types of literals can contain any Unicode characters. For
example:
char a = '\u0001';
String a = "\u0001";
Java language supports few special escape sequences for String and char literals
as well. They are:
float: The float data type is a single-precision 32-bit IEEE 754 floating
point.
double: The double data type is a double-precision 64-bit IEEE 754
floating point.
Variables
The variable is the basic unit of storage in a Java program. A variable is defined
by the combination of an identifier, a type, and an optional initializer. Each
variable in Java has a specific type, which determines the size and layout of the
variable's memory; the range of values that can be stored within that memory;
Declaring a Variable
Local Variables
Local variables are declared in methods, constructors, or blocks.
Local variables are implemented at stack level internally.
Access modifiers cannot be used for local variables.
For Example:
• class sample {
• int a = 9,
• b = 10;
• void LearnJava {
• int local_j = 45; // A local variable
• String s = ”BMSIT”; //A local variable
• }
• }
Instance Variables
Instance variables are declared in a class, but outside a method,
constructor or any block.
When a space is allocated for an object in the heap, a slot for each
instance variable value is created.
Access modifiers can be given for instance variables.
import java.io. * ;
class Person
{
int height,
weight; // Instance Variables
Person(int h, int w)
{
this.height = h;
this.weight = w;
}
void run() {
System.out.println(“Huff Puff”);
}
void print() {
System.out.println(“Now my weight is” + this.weight);
}
Class/static Variables
Class variables also known as static variables are declared with the static
keyword in a class, but outside a method, constructor or a block.
There would only be one copy of each class variable per class, regardless
of how many objects are created from it.
Static variables are stored in the static memory. It is rare to use static
variables other than declared final and used as either public or private
constants.
class sample
{
static int studentCount;
sample()
{
studentCount = 15;
}
void addStudent()
{
studentCount++;
}
Dynamic Initialization
Here, three local variables—a, b, and c—are declared. The first two, a and b, are
initialized by constants. However, c is initialized dynamically to the length of
the hypotenuse
Java allows variables to be declared within any block. A block defines a scope.
Thus, each time you start a new block, you are creating a new scope. A scope
determines what objects are visible to other parts of your program. It also
determines the lifetime of those objects.
In Java, the two major scopes are those defined by a class and those defined by
a method.
As a general rule, variables declared inside a scope are not visible (that is,
accessible) to code that is defined outside that scope. Thus, when you declare a
variable within a scope, you are localizing that variable and protecting it from
unauthorized access and/or modification.
class Scope {
public static void main(String args[]) {
int x; // known to all code within main
x = 10;
if(x == 10) { // start new scope
int y = 20; // known only to this block
// x and y both known here.
System.out.println("x and y: " + x + " " + y);
x = y * 2;
}
// y = 100; // Error! y not known here
// x is still known here.
System.out.println("x is " + x);
}
}
Output
x and y: 10 20
x is 22
a. Its convention to start the names of a variable with an alphabet rather than an
underscore or a dollar sign
b. Variable names can have any alphabets or numbers after the first letter.
However, spaces are not allowed.
e. Variables which need two distinct words can be written together using
camelCase.
When one type of data is assigned to another type of variable, an automatic type
conversion will take place if the following two conditions are met:
The two types are compatible. The destination type is larger than the source
type. Java also performs an automatic type conversion when storing a literal
integer constant into variables of type byte, short, long, or char.
Ex:
long l;
int i;
l=i;
}
Output :
Double value 100.04
Long value 100
Int value 100
The result of the intermediate term a * b easily exceeds the range of either of its
byte operands. To handle this kind of problem, Java automatically promotes
each byte, short, or char operand to int when evaluating an expression. This
means that the sub expression a*b is performed using integers—not bytes. Thus,
2,000, the result of the intermediate expression, 50 * 40, is legal even though a
and b are both specified as type byte.
byte b = 50;
b = b * 2; // Error! Cannot assign an int to a byte!
byte b = 50;
b = (byte)(b * 2); //which yields the correct value of 100.
class Promote {
public static void main(String args[]) {
byte b = 42;
char c = 'a';
short s = 1024;
int i = 50000;
float f = 5.67f;
double d = .1234;
double result = (f * b) + (i / c) - (d * s);
System.out.println((f * b) + " + " + (i / c) + " - " + (d * s));
System.out.println("result = " + result);
}
}
Output: will be of double data type
Arrays
An array is a group of like-typed variables that are referred to by a common
name. Arrays of any type can be created and may have one or more dimensions.
A specific element in an array is accessed by its index.
One-Dimensional Arrays
A one-dimensional array is essentially, a list of like-typed variables. To create
an array, you first must create an array variable of the desired type. The general
form of a one-dimensional
array declaration is:
datatype identifier [ ];
Or
datatype[ ] identifier;
Arrays can be initialized when they are declared. There is no need to use new.
class AutoArray {
Dr. Srivani P BMSIT&M Page 27
Module 2 -Java
Output:
April has 30 days
Multidimensional Arrays
Ex:
class TwoDArray {
public static void main(String args[]) {
int twoD[][]= new int[4][5];
int i, j, k = 0;
for(i=0; i<4; i++)
for(j=0; j<5; j++) {
twoD[i][j] = k;
k++;
}
for(i=0; i<4; i++) {
for(j=0; j<5; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
}
}
}
This program generates the following output:
01234
56789
10 11 12 13 14
15 16 17 18 19
Ex:
String[][] sampleData = { {"a", "b", "c", "d"}, {"e", "f", "g", "h"}, {"i", "j",
"k", "l"},
{"m", "n", "o", "p"} };
Operators in Java
Java provides a rich operator environment. Java provides a rich set of operators
to manipulate variables. We can divide all the Java operators into the following
groups:
Arithmetic Operators
Relational Operators
Bitwise Operators
Logical Operators
Ternary Operator and
Assignment Operator.
Operators Precedence
Postfix expr++ expr--
Unary ++expr --expr +expr -expr ~ !
Multiplicative */%
Additive +-
Shift << >> >>>
Relational < > <= >= instance of
Equality == !=
bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
logical AND &&
logical OR ||
Ternary ?:
Assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=
Arithmetic Operators
The basic arithmetic operations—addition, subtraction, multiplication, and
division—all behave as you would expect for all numeric types.
The unary minus operator negates its single operand.
The unary plus operator simply returns the value of its operand.
class OperatorExample{
public static void main(String args[]){
Dr. Srivani P BMSIT&M Page 29
Module 2 -Java
int a=10;
int b=5;
System.out.println(a+b);//15
System.out.println(a-b);//5
System.out.println(a*b);//50
System.out.println(a/b);//2
System.out.println(a%b);//0
}
}
Output
15
5
50
2
0
class Modulus {
public static void main(String args[]) {
int x = 42;
double y = 42.25;
System.out.println("x mod 10 = " + x % 10);
System.out.println("y mod 10 = " + y % 10);
}
}
x mod 10 = 2
y mod 10 = 2.25
class OperatorExample{
public static void main(String args[]){
int a=10;
int b=20;
a+=4;//a=a+4 (a=10+4)
b-=4;//b=b-4 (b=20-4)
System.out.println(a);
System.out.println(b);
}}
The relational operators determine the relationship that one operand has to the
other. The outcome of these operations is a boolean value. The relational
operators are most frequently used in the expressions that control the if
statement and the various loop statements.
operator Description
== Check if two operands are equal
!= Check if two operands are not equal.
> Check if operand on the left is greater than operand on the right
< Check operand on the left is smaller than right operand
>= check left operand is greater than or equal to right operand
<= Check if operand on left is smaller than or equal to right operand
The Boolean logical operators shown here operate only on boolean operands
and relational expressions. All of the binary logical operators combine two
boolean values to form a resultant boolean value. The logical Boolean
operators, &, |, and ^, operate on boolean values in the same way that they
operate on the bits of an integer.
For example, the following code fragment shows how you can take advantage
of short-circuit logical evaluation to be sure that a division operation will be
valid before evaluating it:
Since the short-circuit form of AND (&&) is used, there is no risk of causing a
run-time exception when denom is zero. If this line of code was written using
the single “&” version of AND, both sides would have to be evaluated, causing
a run-time exception when denom is zero.
class ShortCircuitAnd
{
public static void main(String arg[])
{
int c = 0, d = 100, e = 50; // LINE A
if( c == 1 && e++ < 100 )
{
d = 150;
Dr. Srivani P BMSIT&M Page 32
Module 2 -Java
}
System.out.println("e = " + e );
}
}
OUTPUT
e = 50
Bitwise Operators
Java defines several bitwise operators that can be applied to the integer types:
long, int, short, char, and byte. These operators act upon the individual bits of
their operands. They are summarized in the following table:
operator description
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
<< left shift
>> right shift
>>> Right Shift zero fill
&= Bitwise AND assignment
|= Bitwise OR assignment
^= Bitwise X-OR assignment
>>>= Shift right zero fill assignment
>>= Shift right assignment
<<= Shift left assignment
1 1 0 1 1 0
1 0 0 0 1 1
0 1 1 0 1 1
0 0 1 0 0 0
class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
int c=20;
System.out.println(a<b && a++<c); //false && true = false
System.out.println(a); //10 because second condition
is not checked
System.out.println(a<b & a++<c); //false && true = false
System.out.println(a); //11 because second condition is
checked
}}
Output:
false
10
false
11
The logical || operator doesn't check second condition if first condition is true. It
checks second condition only if first one is false.
The bitwise | operator always checks both conditions whether first condition is
true or false.
class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
int c=20;
System.out.println(a>b||a<c); //true || true = true
Output:
true
true
true
10
true
11
class OperatorExample
{
public static void main(String args[]){
System.out.println(10<<2); //10*2^2=10*4=40
System.out.println(10<<3); //10*2^3=10*8=80
System.out.println(10>>2); //10/2^2=10/4=2
System.out.println(20>>2); //20/2^2=20/4=5
System.out.println(20>>3); //20/2^3=20/8=2
}
}
int x = 13 >>> 1;
Out put : 6
// 13 = 00000000000000000000000000001101
// 6 = 00000000000000000000000000000110
y = -8 >>> 2;
Output : 1073741822
// -8 = 11111111111111111111111111111000
// 1073741822 = 00111111111111111111111111111110
The following code fragment demonstrates the >>>. Here, a is set to –1, which
sets all 32 bits to 1 in binary. This value is then shifted right 24 bits, filling the
top 24 bits with zeros, ignoring normal sign extension. This sets a to 255.
int a = -1;
a = a >>> 24;
class OperatorExample{
public static void main(String args[]){
//For positive number, >> and >>> works same
System.out.println(20>>2);
System.out.println(20>>>2);
//For nagative number, >>> changes parity bit (MSB) to 0
System.out.println(-20>>2);
System.out.println(-20>>>2);
}
}
Output
5
5
-5
1073741819
class OperatorExample{
public static void main(String args[]){
int a=2;
int b=5;
int min=(a<b)?a:b;
System.out.println(min);
}}
Output:
class IncDec {
public static void main(String args[]) {
int a = 1;
int b = 2;
int c;
int d;
c = ++b;
d = a++;
c++;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
}
Dr. Srivani P BMSIT&M Page 37
Module 2 -Java
}
Output
a=2
b=3
c=4
d=1
Control Statements
If- else:
The if statement is Java’s conditional branch statement. It can be used to route
program execution through two different paths. Here is the general form of the
if statement:
if (condition)
statement1;
else
statement2;
Here, each statement may be a single statement or a compound statement
enclosed in curly braces (that is, a block). The condition is any expression that
returns a boolean value. The else clause is optional.
Nested ifs
A nested if is an if statement that is the target of another if or else. Nested ifs are
very common in programming. When you nest ifs, the main thing to remember
is that an else statement always refers to the nearest if statement that is within
the same block as the else and that is not already associated with an else.
Syntax :
if (condition)
{
if (condition){
//Do something
}
//Do something
Dr. Srivani P BMSIT&M Page 38
Module 2 -Java
}
if(i == 10) {
if(j < 20) a = b;
if(k > 100) c = d; // this if is
else a = c; // associated with this else
}
else a = d;
Syntax: if(condition)
statement;
else if(condition)
statement;
else if(condition)
statement;
.
.
.
else
statement;
public class ControlFlowDemo
{
public static void main(String[] args)
{
char ch = 'o';
}
}
Switch
The switch statement is Java’s multiway branch statement. It provides an easy
way to dispatch execution to different parts of your code based on the value of
an expression. As such, it often provides a better alternative than a large series
of if-else-if statements. Here is the general form of a switch statement:
expression must be of type byte, short, int, char, or enumerated data type(
String).
class StringSwitch {
public static void main(String args[]) {
String str = "two";
switch(str)
{
case "one":
System.out.println("one");
break;
case "two":
System.out.println("two");
break;
case "three":
Dr. Srivani P BMSIT&M Page 40
Module 2 -Java
System.out.println("three");
break;
default:
System.out.println("no match");
break;
}
}
}
Output : two
Iteration Statements
Java’s iteration statements are for, while, and do-while. These statements create
what we commonly call loops. As you probably know, a loop repeatedly
executes the same set of instructions until a termination condition is met. As
you will see, Java has a loop to fit any programming need.
while
The while loop is Java’s most fundamental loop statement. It repeats a
statement or block
while its controlling expression is true. Here is its general form:
while(condition)
{
// body of loop
}
The condition can be any Boolean expression. The body of the loop will be
executed as long
as the conditional expression is true. When condition becomes false, control
passes to the next line of code immediately following the loop.
Example:
class WhileLoopExample{
public static void main(String[] args){
int num=0;
while(num<=5){
System.out.println(""+num);
num++;
}
}
}
do-while
The do-while loop always executes its body at least once, because its
conditional expression is at the bottom of the loop. Its general form is
do {
// body of loop
} while (condition);
Each iteration of the do-while loop first executes the body of the loop and then
evaluates the conditional expression. If this expression is true, the loop will
repeat. Otherwise, the loop terminates. As with all of Java’s loops, condition
must be a Boolean expression.
The do-while loop is especially useful when you process a menu selection,
because you will
usually want the body of a menu loop to execute at least once.
class Menu {
public static void main(String args[])
{
char choice;
do
{
System.out.println("Help on: ");
System.out.println(" 1. if");
System.out.println(" 2. switch");
System.out.println(" 3. while");
System.out.println(" 4. do-while");
System.out.println(" 5. for\n");
System.out.println("Choose one:");
choice = (char) System.in.read();
} while( choice < '1' || choice > '5');
System.out.println("\n");
switch(choice) {
case '1':
System.out.println("The if:\n");
System.out.println("if(condition) statement;");
System.out.println("else statement;");
break;
case '2':
System.out.println("The switch:\n");
System.out.println("switch(expression) {");
System.out.println(" case constant:");
System.out.println(" statement sequence");
System.out.println(" break;");
System.out.println(" //...");
System.out.println("}");
break;
case '3':
Dr. Srivani P BMSIT&M Page 43
Module 2 -Java
System.out.println("The while:\n");
System.out.println("while(condition) statement;");
break;
case '4':
System.out.println("The do-while:\n");
System.out.println("do {");
System.out.println(" statement;");
System.out.println("} while (condition);");
break;
case '5':
System.out.println("The for:\n");
System.out.print("for(init; condition; iteration)");
System.out.println(" statement;");
break;
}
}
}
For:
There are two forms of the for loop.
The first is the traditional form that has been in use since the original version of
Java. The second is the newer “for-each” form.
Here, type specifies the type and itr-var specifies the name of an iteration
variable that will receive the elements from a collection(array), one at a
time, from beginning to end. The collection being cycled through is
specified by collection.
Ex : int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int sum = 0;
for(int x: nums)
sum += x;
for(int x : numbers ) {
System.out.print( x );
System.out.print(",");
}
System.out.print("\n");
String [] names = {"James", "Larry", "Tom", "Lacy"};
class sample {
public static void main(String args[]) {
int sum = 0;
int nums[][] = new int[3][5];
Jump Statements
Using break
In Java, the break statement has three uses. First, as you have seen, it
terminates a statement sequence in a switch statement. Second, it can be used to
exit a loop. Third, it can be used as a “civilized” form of goto.
1) Using break to Exit a Loop
2) Using break as a Form of Goto:
Java does not have a goto statement because it provides a way to branch
in an arbitrary and unstructured manner. This usually makes goto-ridden
code hard to understand and hard to maintain.
public class BreakDemo
{
public static void main(String[] args)
{
for (int i = 1; i <= 10; i++)
{
if (i == 5)
{
break; // terminate loop if i is 5
}
System.out.print(i + " ");
}
System.out.println("Thank you.");
}
}
Output 1 2 3 4 Thank you
Using continue
In while and do-while loops, a continue statement causes control to be
transferred directly to the conditional expression that controls the loop. In a for
loop, control goes first to the iteration portion of the for statement and then to
the conditional expression. For all three loops, any intermediate code is
bypassed.
Break Continue
The break statement results in the The continue statement stops the
termination of the loop, it will come current execution of the iteration and
out of the loop and stops further proceeds to the next iteration
iterations.
The break statement has two forms: The continue statement skips the
labelled and current iteration of a for, while , or do-
unlabelled. while loop. The unlabelled form skips
An unlabelled break statement to the end of the innermost loop's body
terminates the innermost switch, for, and evaluates the Boolean expression
while, or do-while statement, but a that controls the loop.
labelled break terminates an outer A labelled continue statement skips the
statement. current iteration of an outer loop
marked with the given label.
The general form of the labelled break The general form of the labelled
statement is shown here: continue statement is shown here:
break label; continue label;
class Break { class ContinueLabel {
public static void main(String args[]) {public static void main(String args[]) {
boolean t = true; outer: for (int i=0; i<4; i++)
first: { {
second: { for(int j=0; j<4; j++)
third: { {
System.out.println("Before the if(j > i)
break."); {
if(t) System.out.println();
break second; // break out of second continue outer;
block }
System.out.println("This won't System.out.print(" " + (i * j));
execute"); }
} }
System.out.println("This won't System.out.println();
execute"); }
} }
System.out.println("This is after
second block.");
}
}
}
Output: 0
Before the break. 01
This is after second block. 024
Dr. Srivani P BMSIT&M Page 48
Module 2 -Java
0369
Return
The last control statement is return. The return statement is used to explicitly
return from a method. That is, it causes program control to transfer back to the
caller of the method. As such, it is categorized as a jump statement.
At any time in a method, the return statement can be used to cause
execution to branch back to the caller of the method. Thus, the return statement
immediately terminates the method in which it is executed.
class Return {
public static void main(String args[]) {
boolean t = true;
System.out.println("Before the return.");
if(t)
return; // return to caller
System.out.println("This won't execute.");
}
}
Here, return causes execution to return to the Java run-time system, since it is
the run-time system that call main( ):
int i=7;
loop1:
while(i<20)
{
if(i==10)
break loop1;
System.out.println("i ="+i);
i++;
}
-White Spaces
Java is a free form language. This means that you do not need to
follow any special indentation rules. In java , white spaces is a space ,
tab or new line.
-Identifiers
Identifiers are used for class names , method names and variable
names. An identifier may be any descriptive sequence of uppercase
and lowercase letters , numbers or the underscore and dollar sign
design.
-Literals
-Comments
-Separators
There are few symbols in java that are used as separators.The most
commonly used separator in java is the semicolon ' ; '. some other
separators are Parentheses '( )' , Braces ' {} ' , Bracket ' [] '
, Comma ' , ' , Period ' . ' .
- Java Keywords
There are 49 reserved keywords currently defined in java. These
keywords cannot be used as names for a variable , class or method.
The standard class also provide support for windowed output. Thus
java as a totality is a combination of the java language itself , plus its
standard classes.