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

Java Notes(Module 1) (DR.shiavani) (1)

The document provides an overview of Java, focusing on its bytecode, development kit (JDK), runtime environment (JRE), and virtual machine (JVM), which enable Java's portability and security. It also discusses key concepts of object-oriented programming such as encapsulation, inheritance, and polymorphism, along with Java's basic structure, including classes, objects, and methods. Additionally, it covers Java's history, primitive data types, and a simple example program.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Java Notes(Module 1) (DR.shiavani) (1)

The document provides an overview of Java, focusing on its bytecode, development kit (JDK), runtime environment (JRE), and virtual machine (JVM), which enable Java's portability and security. It also discusses key concepts of object-oriented programming such as encapsulation, inheritance, and polymorphism, along with Java's basic structure, including classes, objects, and methods. Additionally, it covers Java's history, primitive data types, and a simple example program.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

Module 2 -Java

Java Byte Code:


The key that allows Java to solve both the security and the portability problems
just described is that the output of a Java compiler is not executable code.
Rather, it is bytecode. Byte code is a highly optimized set of instructions
designed to be executed by the Java run-time system, which is called the Java
Virtual Machine (JVM).In essence, the original JVM was designed as an
interpreter for bytecode.
Translating a Java program into bytecode makes it much easier to run a program
in a wide variety of environments because only the JVM needs to be
implemented for each platform. Once the run-time package exists for a given
system, any Java program can run on it.

Bytecode is the intermediate representation of Java programs just as assembler


is the intermediate representation of C or C++ programs. Programming code,
once compiled, is run through a virtual machine instead of the computer’s
processor. By using this approach, source code can be run on any platform once
it has been compiled and run through the virtual machine.
Bytecode is the compiled format for Java programs. Once a Java program has
been converted to bytecode, it can be transferred across a network and executed
by Java Virtual Machine (JVM). Bytecode files generally have a .class
extension.

Dr. Srivani P BMSIT&M Page 1


Module 2 -Java

A method's bytecode stream is a sequence of instructions for the Java virtual


machine. Each instruction consists of a one-byte opcode followed by zero or
more operands. Rather than being interpreted one instruction at a time, Java
bytecode can be recompiled at each particular system platform by a just-in-time
compiler. Usually, this will enable the Java program to run faster.

Java Development Kit (JDK):

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 (JRE):

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 (JVM):

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.

Dr. Srivani P BMSIT&M Page 2


Module 2 -Java

Just In Time Compiler (JIT):

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.

Dr. Srivani P BMSIT&M Page 3


Module 2 -Java

Java Buzz Words


 Simple
 Secure
 Portable
 Object-oriented
 Robust
 Multithreaded
 Architecture-neutral
 Interpreted
 High performance
 Distributed
 Dynamic

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.

Secure: With Java's secure feature it enables to develop virus-free, tamper-free


systems. Authentication techniques are based on public-key encryption.

Architecture-neutral: Java compiler generates an architecture-neutral object


file format, which makes the compiled code executable on many processors,
with the presence of Java runtime system.
Irrespective of the operating system(32bits or 64 bits), the int and float data type
occupies 4 bytes of data.

Dr. Srivani P BMSIT&M Page 4


Module 2 -Java

Portable: Being architecture-neutral and having no implementation dependent


aspects of the specification makes Java portable. Compiler in Java is written in
ANSI C with a clean portability boundary, which is a POSIX subset.

Robust: Java makes an effort to eliminate error prone situations by


emphasizing mainly on compile time error checking and runtime checking.

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.

Multithreaded: With Java's multithreaded feature it is possible to write


programs that can perform many tasks simultaneously. This design feature
allows the developers to construct interactive applications that can run
smoothly.

Interpreted: Java byte code is translated on the fly to native machine


instructions and is not stored anywhere. The development process is more rapid
and analytical since the linking is an incremental and light-weight process.

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

Dr. Srivani P BMSIT&M Page 5


Module 2 -Java

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.

Object Oriented Paradigm


Abstraction
An essential element of object-oriented programming is abstraction. Humans
manage complexity through abstraction.
From the outside, the car is a single object. Once inside, you see that the car
consists of several subsystems: steering, brakes, sound system, seat belts,
heating, cellular phone, and so on. In turn, each of these subsystems is made up
of more specialized units.
For instance, the sound system consists of a radio, a CD player, and/or a tape
player. The point is that you manage the complexity of the car (or any other
complex system) through the use of hierarchical abstractions.

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

Dr. Srivani P BMSIT&M Page 6


Module 2 -Java

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.

Each method or variable in a class may be marked private or public.


 The public interface of a class represents everything that external users of
the class need to know, or may know.
 The private methods and data can only be accessed by code that is a
member of the class.

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

Dr. Srivani P BMSIT&M Page 7


Module 2 -Java

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

Polymorphism (from Greek, meaning “many forms”) is a feature that allows


one interface to be used for a general class of actions. Polymorphism in java is
a concept by which we can perform a single action by different ways.
Polymorphism is derived from 2 Greek words: poly and morphs. The word
"poly" means many and "morphs" means forms. So polymorphism means many
forms.

There are two types of polymorphism in java:

 compile time polymorphism and


 Runtime polymorphism.

Dr. Srivani P BMSIT&M Page 8


Module 2 -Java

We can perform polymorphism in java by method overloading and method


overriding.

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.

Polymorphism, Encapsulation, and Inheritance Work Together


When properly applied, polymorphism, encapsulation, and inheritance combine
to produce a programming environment that supports the development of far
more robust and scalable programs than does the process-oriented model. A
well-designed hierarchy of classes is the basis for reusing the code in which you
have invested time and effort developing and testing. Encapsulation allows you
to migrate your implementations over time without breaking the code that
depends on the public interface of your classes. Polymorphism allows you to
create clean, sensible, readable, and resilient code.

Dr. Srivani P BMSIT&M Page 9


Module 2 -Java

Java Basics

When we consider a Java program, it can be defined as a collection of objects


that communicate via invoking each other's methods. Let us now briefly look
into what do class, object, methods, and instance variables mean.

 Object - Objects have states and behaviours. Example: A dog has


states - colour, name, breed as well as behaviour such as wagging their
tail, barking, eating. An object is an instance of a class.

 Class - A class can be defined as a template/blueprint that describes


the behaviour/state that the object of its type supports.

 Methods - A method is basically behaviour. A class can contain many


methods. It is in methods where the logics are written, data is
manipulated and all the actions are executed.

 Instance Variables - Each object has its unique set of instance


variables. An object's state is created by the values assigned to these
instance variables.

First Java Program


Let us look at a simple code that will print the words Hello World.

public class MyFirstJavaProgram {


/* This is my first java program.
This will print 'Hello World' as the output */

public static void main(String []args) {


System.out.println("Hello World"); // prints Hello World
}
}

C:\> javac MyFirstJavaProgram.java


C:\> java MyFirstJavaProgram
Hello World

Dr. Srivani P BMSIT&M Page 10


Module 2 -Java

COMMENTS

Java supports three styles of comments.


1) The one shown at the top of the program is called a multiline comment.
This type of comment must begin with /* and end with */.
2) Single line comment . //
3) Documentation Comment

public static void main(String args[]) {


All Java applications begin execution by calling main( ).
When a class member is preceded by public, then that member may be accessed
by code outside the class in which it is declared.
The keyword static allows main( ) to be called without having to instantiate a
particular instance of the class. This is necessary since main( ) is called by the
Java Virtual Machine before any objects are made.

System.out.println("This is a simple Java program.");

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.

Dr. Srivani P BMSIT&M Page 11


Module 2 -Java

Data Type Range Default size


Boolean False/ true 1 bit
char 0-65536 2 byte
byte –128 to 127 1 byte
short –32,768 to 32,767 2 byte
int –2,147,483,648 to 2,147,483,647 4 byte
–9,223,372,036,854,775,808 to
long 8 byte
9,223,372,036,854,775,807
float 1.4e–045 to 3.4e+038 4 byte
double 4.9e–324 to 1.8e+308 8 byte

Integers: Java does not support unsigned, positive-only integers.


int is used for storing integer values. Its size is 4 bytes and has a default
value of 0. The maximum values of integer is 2^31 and the minimum value
is -2^31. It can be used to store integer values unless there is a need for
storing numbers larger or smaller than the limits

Char: Java uses Unicode to represent characters. Unicode defines a fully


international character set that can represent all of the characters found in all
human languages. It is a unification of dozens of character sets, such as Latin,
Greek, Arabic, Cyrillic, Hebrew, Katakana, Hangul, and many more. For this
purpose, it requires 16 bits.

Its default value is ‘\u0000’ with the max value being ‘\uffff’ and has a size of 2 bytes.

Example- char a=’D’;

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.

public class JavaCharExample {

public static void main(String[] args) {


char ch1 = 'a';
char ch2 = 65; /* ASCII code of 'A'*/

System.out.println("Value of char variable ch1 is :" +


ch1);
System.out.println("Value of char variable ch2 is :" +
ch2);
Dr. Srivani P BMSIT&M Page 12
Module 2 -Java

}
}

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.

public class JavaByteExample {


public static void main(String[] args) {

byte b1 = 100;
byte b2 = 20;

System.out.println("Value of byte variable b1 is :" + b1);


System.out.println("Value of byte variable b1 is :" + b2);
}
}

Output would be
Value of byte variable b1 is :100
Value of byte variable b1 is :20

 short data type


A short data type is greater than byte in terms of size and less than a
integer. It stores the value that ranges from -32,768 to 32767. The
default size of this data type: 2 bytes. Let’s take an example and understand
the short data type.

 Boolean takes either True or false


boolean is a special datatype which can have only two values ‘true’ and
‘false’. It has a default value of ‘false’ and a size of 1 byte. It comes in
use for storing flag values.

Dr. Srivani P BMSIT&M Page 13


Module 2 -Java

Example- boolean flag=true;

public class JavaBooleanExample {

public static void main(String[] args) {

boolean b1 = true;
boolean b2 = false;
boolean b3 = (10 > 2)? true:false;

System.out.println("Value of boolean variable b1 is :" + b1);


System.out.println("Value of boolean variable b2 is :" + b2);
System.out.println("Value of boolean variable b3 is :" + b3);
}
}
Output would be
Value of boolean variable b1 is :true
Value of boolean variable b2 is :false
Value of boolean variable b3 is :true

 Floating-point numbers, also known as real numbers, are used when


evaluating expressions that require fractional precision.

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.*;

public class JavaFloatExample {

public static void main(String[] args) {


float f = 10.4f;
System.out.println("Value of float variable f is :" + f);
}
}
Output would be
Value of float variable f is :10.4

 Double precision is actually faster than single precision on some modern


processors that have been optimized for high-speed mathematical
Dr. Srivani P BMSIT&M Page 14
Module 2 -Java

calculations. All transcendental math functions, such as sin( ), cos( ), and


sqrt( ), return double values.
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.

public class JavaDoubleExample {

public static void main(String[] args) {

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

A literal is a source code representation of a fixed value. They are represented


directly in the code without any computation. Literals can be assigned to any
primitive type variable.

For example:
byte a = 68;

Dr. Srivani P BMSIT&M Page 15


Module 2 -Java

char a = 'A'

byte, int, long, and short can be expressed in decimal(base 10),


hexadecimal(base 16) or octal(base 8) number systems as well.

Integer Literals:

int decimal = 100;


int octal = 0144;
int hexa = 0x64;

 Decimal (Base 10)


Digits from 0-9 are allowed in this form.

Int x = 101;

 Octal (Base 8)
Digits from 0 – 7 are allowed. It should always have a prefix 0.

int x = 0146;

 Hexa-Decimal (Base 16)


Digits 0-9 are allowed and also characters from a-f are allowed in this form.
Furthermore, both uppercase and lowercase characters can be used, Java
provides an exception here.
int x = 0X123Face;

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

Dr. Srivani P BMSIT&M Page 16


Module 2 -Java

Char Literals in Java


These are the four types of char-

 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.

char ch = '\u0061';// Here /u0061 represent a.

 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\""

Dr. Srivani P BMSIT&M Page 17


Module 2 -Java

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:

Notation Character represented


\n Newline (0x0a)
\r Carriage return (0x0d)
\f Form feed (0x0c)
\b Backspace (0x08)
\s Space (0x20)
\t tab
\" Double quote
\' Single quote
\\ backslash
\ddd Octal character (ddd)
\uxxxx Hexadecimal UNICODE character
(xxxx)

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.

Dr. Srivani P BMSIT&M Page 18


Module 2 -Java

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

data type variable [ = value][, variable [= value] ...] ;

Following are valid examples of variable declaration and initialization in Java:

int a, b, c; // Declares three ints, a, b, and c.


int a = 10, b = 10; // Example of initialization
byte B = 22; // initializes a byte type variable B.
double pi = 3.14159; // declares and assigns a value of PI.
char a = 'a'; // the char variable a is initialized with value 'a'

There are three kinds of variables in Java:


 Local variables
 Instance variables
 Class/Static variables

Dr. Srivani P BMSIT&M Page 19


Module 2 -Java

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

Dr. Srivani P BMSIT&M Page 20


Module 2 -Java

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

public static void main(String[] args)


{
Person A = new Person(170, 65);
A.run();
A.print();
}
}

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

Dr. Srivani P BMSIT&M Page 21


Module 2 -Java

void addStudent()
{
studentCount++;
}

public static void main(String[] args)


{
sample java = new sample();
sample python = new sample();
java.addStudent();
python.addStudent();
System.out.println("Total Students " + studentCount);
}
}
Total Students 17

Dynamic Initialization

Java allows variables to be initialized dynamically, using any expression valid


at the time the variable is declared.
Ex:
class dyn {
public static void main(String args[])
{
double a = 3.0, b = 4.0;
// c is dynamically initialized
double c = Math.sqrt(a * a + b * b);
System.out.println("Hypotenuse is " + c);
}
}

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

The Scope and Lifetime of Variables

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.

Dr. Srivani P BMSIT&M Page 22


Module 2 -Java

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.

To understand the effect of nested scopes, consider the following program:

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

Variable Naming Conventions in Java


There are particular conventions to be followed when naming variables to
enhance the readability of the program.
Some of them are:

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.

Dr. Srivani P BMSIT&M Page 23


Module 2 -Java

c. The reserved words such as int,static,void and so on cannot be used as


variable names.

d. Constant values can be stored in variables which are named in “ALL_CAPS”.

e. Variables which need two distinct words can be written together using
camelCase.

Type Conversion and Casting


 Widening Casting(Implicit)

 Narrowing Casting(Explicitly done)

1) Java’s Automatic Conversions (Implicit Conversion)

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:

Dr. Srivani P BMSIT&M Page 24


Module 2 -Java

//64 bit long integer

long l;

//32 bit long integer

int i;

l=i;

2) Casting Incompatible Types


Although the automatic type conversions are helpful, they will not fulfill all
needs. To create a narrowing conversion between two incompatible types, you
must use a cast. A cast is simply an explicit type conversion.
It has this general form: (target-type) value

public class Test


{
public static void main(String[] args)
{
double d = 100.04;
long l = (long)d; //explicit type casting required
int i = (int)l; //explicit type casting required

System.out.println("Double value "+d);


System.out.println("Long value "+l);
System.out.println("Int value "+i);

}
Output :
Double value 100.04
Long value 100
Int value 100

Automatic Type Promotion in Expressions


byte a = 40;
byte b = 50;
byte c = 100;
int d = a * b / c;

Dr. Srivani P BMSIT&M Page 25


Module 2 -Java

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

Type Promotion Rules


1.All byte, short and char values are promoted to int.
2.If one operand is a long, the whole expression is promoted to long.
3.If one operand is a float, the entire expression is promoted to float.
4.If any of the operands is double, the result is double.

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.

Dr. Srivani P BMSIT&M Page 26


Module 2 -Java

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;

Ex: int month_days[];


It declares an array variable but do not allocate any memory. New is a special
operator that allocates memory.
array-var = new type[size]; // (new will automatically be initialized to zero )
OR
dataType[] arrayVar = new dataType[arraySize];
class Array {
public static void main(String args[]) {
int month_days[];
month_days = new int[12];
month_days[0] = 31;
month_days[1] = 28;
month_days[2] = 31;
month_days[3] = 30;
month_days[4] = 31;
month_days[5] = 30;
month_days[6] = 31;
month_days[7] = 31;
month_days[8] = 30;
month_days[9] = 31;
month_days[10] = 30;
month_days[11] = 31;
System.out.println("April has " + month_days[3] + " days.");
}
}

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

public static void main(String args[]) {


int month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
System.out.println("April has " + month_days[3] + " days.");
}
}

Output:
April has 30 days

Multidimensional Arrays

In Java, multidimensional arrays are actually arrays of arrays.

int twoD[][] = new int[4][5];

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

Dr. Srivani P BMSIT&M Page 28


Module 2 -Java

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

The Modulus Operator


The modulus operator, %, returns the remainder of a division operation. It can
be applied to floating-point types as well as integer types. The following
example program demonstrates the %:

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

Note: RESULT OF ARITHMETIC EXPRESSIONIS ALWAYS


MAX(int, type of a and type of b)
Ex: byte a=10;
byte b= 20;
c= a+b; // the result will be integer type

Arithmetic Compound Assignment Operators [Shorthand assignment]


Dr. Srivani P BMSIT&M Page 30
Module 2 -Java

Java provides special operators that can be used to combine an arithmetic


operation with an assignment.

var op= expression;

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

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

Boolean Logical Operators

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.

Dr. Srivani P BMSIT&M Page 31


Module 2 -Java

Short-Circuit Logical Operators


Java provides two interesting Boolean operators not found in some other
computer languages. The OR operator results in true when A is true, no matter
what B is. Similarly, the AND operator results in false when A is false, no
matter what B is.
Java will not bother to evaluate the right-hand operand when the outcome of the
expression can be determined by the left operand alone. This is very useful
when the right-hand operand depends on the value of the left one in order to
function properly.

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:

if ( denom != 0 && num / denom >10)

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

A B ~A A&B A|B A^B

1 1 0 1 1 0

1 0 0 0 1 1

0 1 1 0 1 1

0 0 1 0 0 0

Dr. Srivani P BMSIT&M Page 33


Module 2 -Java

Java AND Operator: Logical && vs Bitwise &

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

Java OR Operator: Logical || and Bitwise |

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

System.out.println(a>b|a<c); //true | true = true

System.out.println(a>b||a++<c); //true || true = true


Dr. Srivani P BMSIT&M Page 34
Module 2 -Java

System.out.println(a); //10 because second condition is not


checked
System.out.println(a>b|a++<c); //true | true = true
System.out.println(a); //11 because second condition is
checked
}}

Output:

true
true
true
10
true
11

Left Shift & Right Shift

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

Java Shift Operator Example: >> vs >>>


>>> is also known as Unsigned Right Shift. For example, if you are shifting
something that does not represent a numeric value, you may not want sign
extension to take place. This situation is common when you are working with
pixel-based values and graphics. In these cases, you will generally want to shift
a zero into the high-order bit no matter what its initial value was. This is known
as an unsigned shift.

Dr. Srivani P BMSIT&M Page 35


Module 2 -Java

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;

Here is the same operation in binary form to further illustrate what is


happening:
11111111 11111111 11111111 11111111 –1 in binary as an int
>>>24
00000000 00000000 00000000 11111111 255 in binary as an
int

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

Dr. Srivani P BMSIT&M Page 36


Module 2 -Java

Java Ternary Operator


Java includes a special ternary (three-way) operator that can replace certain
types of if-then else statements. This operator is the ?. It can seem somewhat
confusing at first, but the ? can be used very effectively once mastered.

The ? has this general form:

expression1 ? expression2 : expression3


Here, expression1 can be any expression that Here, expression1 can be any
expression that evaluates to a boolean value. If expression1 is true, then
expression2 is evaluated; otherwise, expression3 is evaluated.

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:

Increment and Decrement


The ++ and the – – are Java’s increment and decrement operators. The
increment operator increases its operand by one. The decrement operator
decreases its operand by one.

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.

public class IfExample {


public static void main(String[] args) {
int age=20;
if(age>18)
{
System.out.print("Eligible to vote");
}
}
}

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;

The if-else-if Ladder


A common programming construct that is based upon a sequence of nested ifs is
the if-elseif
ladder. It looks like this:

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

if (ch == 'a' || ch == 'A')


System.out.println(ch + " is vowel.");
else if (ch == 'e' || ch == 'E')
System.out.println(ch + " is vowel.");
else if (ch == 'i' || ch == 'I')
System.out.println(ch + " is vowel.");
else if (ch == 'o' || ch == 'O')
System.out.println(ch + " is vowel.");
else if (ch == 'u' || ch == 'U')
System.out.println(ch + " is vowel.");
else
System.out.println(ch + " is a consonant.");
Dr. Srivani P BMSIT&M Page 39
Module 2 -Java

}
}

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:

Syntax: switch (expression)


{
case value1:
// statement sequence
break;
case value2:
// statement sequence
break;
.
.
.
case valueN :
// statement sequence
break;
default:
// default statement sequence
}

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

public class SwitchExample {


public static void main(String[] args) {
int number=20;
switch(number){
case 10: System.out.println("10");break;
case 20: System.out.println("20");break;
case 30: System.out.println("30");break;
default:System.out.println("Not in 10, 20 or 30");
}
}
}
Output : 20

Nested switch Statements


You can use a switch as part of the statement sequence of an outer switch. This
is called a nested switch. Since a switch statement defines its own block, no
conflicts arise between the
case constants in the inner switch and those in the outer switch.

For example, the following fragment is perfectly valid:


switch(count) {
case 1:
switch(target)
{ // nested switch
case 0:
System.out.println("target is zero");
break;
case 1: // no conflicts with outer switch
System.out.println("target is one");
break;
}
break;
case 2: // .........so on.
Dr. Srivani P BMSIT&M Page 41
Module 2 -Java

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

Dr. Srivani P BMSIT&M Page 42


Module 2 -Java

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

public class DoWhileExample {


public static void main(String[] args) {
int i=1;
do{
System.out.println(i);
i++;
}while(i<=10);
}
}

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.

1) Here is the general form of the traditional for statement:


for(initialization; condition; iteration)
{
// body
}
Ex : int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int sum = 0;
for(int i=0; i < 10; i++)
sum += nums[i];

Dr. Srivani P BMSIT&M Page 44


Module 2 -Java

For-Each Version of the for Loop:


The general form of the for-each version of the for is shown here:

for(type itr-var : collection) statement-block

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;

public class Test {


public static void main(String args[]) {
int [] numbers = {10, 20, 30, 40, 50};

for(int x : numbers ) {
System.out.print( x );
System.out.print(",");
}
System.out.print("\n");
String [] names = {"James", "Larry", "Tom", "Lacy"};

for( String name : names ) {


System.out.print( name );
System.out.print(",");
}
}
}
10, 20, 30, 40, 50,
James, Larry, Tom, Lacy,

Iterating Over Multidimensional Arrays

Dr. Srivani P BMSIT&M Page 45


Module 2 -Java

class sample {
public static void main(String args[]) {
int sum = 0;
int nums[][] = new int[3][5];

for(int i = 0; i < 3; i++)


for(int j = 0; j < 5; j++)
nums[i][j] = (i+1)*(j+1);

for(int x[] : nums) {


for(int y : x) {
System.out.println("Value is: " + y);
sum += y;
}
}
System.out.println("Summation: " + sum);
}
}
Output:
Value is: 1
Value is: 2
Value is: 3
Value is: 4
Value is: 5
Value is: 2
Value is: 4
Value is: 6
Value is: 8
Value is: 10
Value is: 3
Value is: 6
Value is: 9

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:

Dr. Srivani P BMSIT&M Page 46


Module 2 -Java

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.

public class ContinueDemo


{
public static void main(String[] args)
{
for (int i = 1; i <= 10; i++)
{
if (i % 2 == 0)
{
continue; // skip next statement if i is even
}
System.out.println(i + " ");
}
}
}
13579
Dr. Srivani P BMSIT&M Page 47
Module 2 -Java

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

The output from this program is shown here:


Before the return.

Here, return causes execution to return to the Java run-time system, since it is
the run-time system that call main( ):

Labelled Break Statement


In Labelled Break Statement, we give a label/name to a loop.
When this break statement is encountered with the label/name of the loop, it skips the
execution any statement after it and takes the control right out of this labelled loop.
And, the control goes to the first statement right after the loop.

Dr. Srivani P BMSIT&M Page 49


Module 2 -Java

public class LabelledBreak


{
public static void main(String... ar)
{

int i=7;

loop1:
while(i<20)
{
if(i==10)
break loop1;

System.out.println("i ="+i);
i++;
}

System.out.println("Out of the loop");

} //main method ends

Dr. Srivani P BMSIT&M Page 50


Module 2 -Java

Lexical Issues in Java


Java programs is a collection of White spaces , Identifiers , comments
, Literals , Operators , Separators and Keywords.

-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

A constant value in java is created by using a literal representation of


it. A literal can be used anywhere a value of its type is allowed.

-Comments

There are 3 types of comment in java. First is single line comment


and the second one is multi line comment. The third type of comment
is called documentation comment. It is used to produce an HTML file
that documents your program. It begins with a/** and ends with a*/.

-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 ' . ' .

Dr. Srivani P BMSIT&M Page 51


Module 2 -Java

- 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 Keywords are : abstract , assert , boolean , break , byte , case ,


catch , char , class , const , continue , default , do , double , else ,
extends , final , finally , float , for , goto , if , implements , import ,
instanceof , int interface , long , native , new , package , private ,
protected , public , return , short , static , strictfp , super , switch ,
synchronized , this , throw , throws , transient , try , void , volatile,
while.

Java Class Libraries


The java environment relies on several built-in class libraries that
contain many built-in methods that provide support for such things as
I/O , string handling , networking and graphics.

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.

Dr. Srivani P BMSIT&M Page 52

You might also like