Unit I Introducation and Overview Java
Unit I Introducation and Overview Java
Unit I Introducation and Overview Java
Tutorial 1
Introduction to Java
Java History
• Java is a general purpose, object oriented programming language developed by Sun Micro-
system of USA in 1991.
• Java was designed for the development of software for consumer electronic devices like TVs,
VCRs, such other electronic device.
Java Milestones
• 1990: Sun Microsystems decided to develop special software that could be used to manipulate
consumer electronic devices. A team of Sun Microsystems programmers headed by James
Gosling was formed to undertake this task.
• 1991 : After exploring the possibility of using the most popular object-oriented language C++,
the team announced a new language named “Oak”
• 1992: The team, known as Green project team by Sun Micro-system, demonstrated the
application of their new language age to control a list of home appliances using a hand-held
device with a tiny touch- sensitive screen.
• 1993: The WWW appeared on the internet and transformed the text-based internet into a
graphical-rich environment. The Green project team came up with the idea of developing
Web applets using the new language that could run on all types of computers connected to
Internet.
• 1994: The team developed a web browser called “HotJava” to locate and run applet programs
on Internet. HotJava demonstrated the power of the new language, thus making it instantly
popular among the internet users.
• 1995: Oak was renamed “JAVA”, due to some legal problem. Java is just a name and is not an
acronym. Many popular companies including Netscape and Microsoft announced their
support to java.
• Java coffee refers to coffee beans produced in the Indonesian island of Java
• 1996: Java established itself not only as a leader for internet programming but also as a
general-purpose, object-oriented programming language.Sun releases Java Development Kit
1.0
• 1998:Sun releases the JAVA 2 with version 1.2 of the software Development Kit (SDK 1.2)
• 2004:J2SE with JDK 5.0 (instead of JDK 1.5) was released, This is known as J2SE5.0
JAVA FEATURES
• The inventors of java wanted to design a language which could offer solutions to some of the
problems encountered in modern programming.
• They wanted the language to be not only reliable, portable and distributed but also simple,
compact and interactive.
- Usually a computer language is either compiled or interpreted. Java combines both these
approaches thus making java a two stage system.
- First, Java compiler translates source code into what is known as byte-code instruction.
Byte-code are not machine instructions and therefore, In second stage, java interpreter
generates machine code that can be directly executed by the machine that is running the
java program. Thus, we can say that java is both a compiled and interpreted language.
- The most significant contribution of java over other language is its portability.
- Java program can be easily moved from one computer system to another, anywhere and
anything. 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 a popular language for programming on internet
which interconnects different kind of systems worldwide.
- We can download a java applet from a remote computer onto our local system via internet
and execute it locally.
- First, java compiler generates byte-code instructions that can implemented on any
machine.
- Secondly, the size of the primitive data types is machine independent.
3. Object- oriented
- Java is a true object oriented language. Almost everything in java is an object. All program
code and data reside within objects and classes.
- Java comes with an extensive set of classes, arranged in packages. Such packages, we can
use in our programs by using inheritance.
5. Distributed
- Java is designed as a distributed language for creating applications on network. 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 a local system.
- This enables multiple programmers at multiple remote locations to collaborate and work
together on a single project.
- Java is small and simple language. Many features of C and C++ that are either redundant
or sources of unreliable code are not part of java.
e.g. Java does not use pointer, preprocessor header files, goto statement and many more.
- It also eliminates operator overloading and multiple inheritance.
8. High performance
- Java performance is impressive for an interpreted language, mainly due to the use of
intermediate byte-code. According to sun, java speed is comparable to the native C/C++.
- Java architecture is also designed to reduce overheads during runtime.
- Further, the incorporation of multi treading enhances the overall execution speed of java
programs.
- Java 2 Standard Edition (J2SE) 5.0 supports features, such as Generics, Enhanced for loop,
autoboxing or unboxing, type safe enums, static import and annotation(footnote). These
features reduce the work of the programmer by shifting the responsibility of creating the
reusable code to the compiler.
- The resulting source code is free from bugs because the errors made by the compiler are less
when compared to those made by programmers.
- J2SE 5.0 assures a significant increase in scalability and performance by improving the
startup time and reducing the amount of memory used in JAVA 2 runtime environment.
For example,
The introduction of the class, data sharing in the Hotspot JAVA VIRTUAL MACHINE (JVM)
improves the startup time by loading the core classes from the jar files into a shared
archive.
- Memory utilization is reduced by sharing data in the shared archive among JVM
processes.
- Java supports a number of APIs, such as JVM monitoring and Management API, Sun
management platform Extension, Logging, Monitoring and management interface and
Java Management Extension(JMX) to monitor and manage java applications.
- Java provides tools, such as jconsole, jps, jstat, and jstated use of monitoring and
management facilities.
- For example: GUI based tool called jconsole is used to monitor the JVM.
- J2SE 5.0 provides enhanced features to meet the requirements and challenges of java
desktop user. It provides an improved swing look and feel called ocean.
- This feature is mainly used for developing graphics applications that require OpenGL
hardware acceleration.
14. JDBCRowset
- Java support JDBC Rowset to sent data in a tabular format between the remote
components of a distributed enterprise applications.
JAVA C++
Object Oriented issues
1 Pure object oriented language Hybrid between procedural and object-
oriented.
2 All methods are part of a class Can have stand alone methods
3 Does not support multiple inheritance. Support multiple inheritance.
4 Does not support operator overloading Support Operator overloading.
5 No parameterized type Templates as parameterized type.
6 No default arguments Function parameters can take default
values.
7 All methods are dynamically bound. Only virtual functions are dynamically
bound.
8 Objects are passed to methods only by Objects can be passed to functions by
reference. value or reference
Pointers, Arrays and Strings
9 No explicit pointer manipulation and Support pointers, with dereferencing ( *
no pointer arithmetic. or ->) and address ( & ) operators.
10 Array references are not translated to Array references translate to pointer
pointer arithmetic. arithmetic.
Array lengths in multidimensional Array lengths have same sizes in
arrays can vary from one element to the multidimensional arrays.
next within one dimension.
Bound checking is done on arrays No bound checking on arrays
Strings are objects Strings are null terminated character
arrays.
Built in string concatenation operator All string operations are performed
(+). using functions
Special features
Automatic garbage collection No automatic garbage collection
Compiled and interpreted. Compiled
Architecture neutral. Architecture specific.
• Java interpreter act as an intermediary between the virtual machine and the real
machine.
User
Layers of interactions for java programs
JAVA PROGRAM STRUCTURE
A java program may contain many classes of which only one class defines a main method.
Classes contain data members and methods that operate on the data members of the class.
Methods may contain data type declarations and executable statements.
Documentation Section
Suggested
Package Statement
Optional
Import Statement
Optional
Interface Statement
Optional
Class definition
Optional
Main method class {
Essential
Main method definition
}
Mr. S V Deshmukh 2022-23
Fig. General structure of a Java Program Page 7
Tutorial 1 : Introduction to Java BCA Sy COCSIT, Latur
1. Documentation Section
The documentation section comprises a set of comment lines giving the name
of the program, the author and other details, which the programmer would
like to refer to at a later stage. Comment must explain why, and what of classes
and how of algorithms. Java uses three type of comments from these two
comments are already observed in C and C++. i.e single line ( // ) and Multiline
comment (/* */). Java also uses a third style of comment /** …..*/ known as
documentation comment.
2. Package statement
The first statement allowed in a java file is a package statement. This statement
declares a package name and informs the compiler that the classes defined
here belong to this package. Package statement is optional.
3. Import statement
An import statements are similar to the #include statement in C. This
statement instructs the interpreter to load the given class. Using import
statements, we can have access to classes that are part of other named
packages.
4. Interface statements
An interface is like a class but includes a group of method declarations. This is
also an optional section and is used only when we wish to implement the
multiple inheritance feature in the program.
5. Class definitions
A java program may contain multiple class definition. Classes are the primary
and essential of a java program. These classes are used to may the objects of
real- world problems. This is also optional.
6. Main method class
Every Java stand – alone program requires a main method as its starting point,
this class is the essential part of a java program.
JAVA ENVIRONMENT
• Java environment include 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 the Application programming interface (API)
7. A programming language
8. A development Environment
9. An application Environment
10.A deployment Environment
11.Integration libraries
1. A programming Language
It is an object oriented programming language which requires both, a
compiler and an interpreter. The compiler first translates a program into
an intermediate code called Java bytecode. Java bytecodes are the
platform independent codes for the JVM. They are interpreted by the
interpreter on the Java platform.
Compilation occurs just once; interpretation occurs each time.
2. A development Environment
The java development tools provide the programmer everything that is
needed for compiling, running, monitoring, debugging, and documenting
application.
3. An application Environment
The API(Application programming interface) provides the core
functionality of the Java programming language. It offers a huge collection
of useful classes which can be directly used in application.
4. A deployment Environment
The java technology provides standard mechanisms such as Java Web
start and Java Plug-in for deploying applications to end users.
5. Integration Libraries
Integration libraries such as Java DataBase Connectivity (JDBC) API, Java
Naming and Directory Interface (JNDI) API, Java Remote Method
Mr. S V Deshmukh 2022-23 Page 9
Tutorial 1 : Introduction to Java BCA Sy COCSIT, Latur
The JAVA Virtual Machine is the base for the java platform and is ported onto
various hardware-based platforms. The Phrase “Write once, run anywhere” is
used with java program. The platform independence of java is possible due to
the JVM. The java compiler is used to compiles the source code and generate
bytecode, which can be interpreted by a suitable JVM on any platform.
The JAVA API is a large collection of ready made software components that
provide many useful capabilities, such as Graphical User Interface(GUI), event
handling, I/ O, file handling, networking etc.
Java interpreter, which runs applets and applications by reading and interpreting
bytecode files.
• Javac
The java compiler, which translate java source code to byte-code files that the
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 bytecode files into a program
description.
• Jdb : Java debugger, which helps us to find errors in our programs.
Text Editor
Javac
Java Jdb
• The way these tools are applied to build and run application programs. To create a
java program, we need to create a source code file using a text editor.
• The source code is then compiled using the java compiler javac and executed using
the java interpreter java.
• The java debugger jdb is used to find errors, if any in the source code.
• A compiled java program can converted into a source code with the help of java
disassembler javap.
Jav
a
Java compiler
Apple Applicati
t Type on Type
Java Java
enable Interp
Output Output
Two ways of using java
Installing Java
To install java, we need to perform the following steps:
1. Double click the .exe file to initiate the installation procedure. The welcome screen
appears.
2. The welcome screen shows the licensing terms and conditions. Click the Accept
button to begin java installation. The progress screen appears.
3. The progress screen depicts the percentage of installation that has been completed.
Once the installation is complete, the complete screen appears.
4. The complete screen show the successful installation. Click the Finish button.
Configuring Java
Once java is installed, we need to configure it by adding the Java Path to the environment
variable, PATH.
To set the PATH variable to the java directory, we need to perform the following steps:
1. Right click on the My Computer icon and select the Properties option from the
dropdown menu.
2. Select the advanced tab to display the advance tab page.
3. Click the Environment variables button to display the Environment variables dialog
box,
4. The Environment variables dialog box is divided into two section-User Variable and
System variable. Under the System variables section, select the Path option below
the variable column and Click the Edit button. The Edit system Variable dialog box
appears.
5. By default, the PATH variable is already set to multiple locations. To set the Java
directory path to the Path variable, append the directory path in the Variable value
text box, separated by a semi-colon.
6. Click OK to close the Edit system Variable dialog box.
7. Click Ok to close the Environment Variable Dialog box.
8. Click OK to close System Properties dialog box and complete the process of
configuring Java.
Types of Comments
1. Single Line
- The Single line comment begins with a //. It is used in application program.
2. Multiline
- The Multiline comment begins with a /* and end with a */. It is used in application program.
3. Documentation comment
- This type of comment is used to produce an HTML file that documents your program.
- The documentation comment begins with a /** and ends with a */.
- Documentation comments allow you to embed information about your program into the
program itself.
- You can then use the javadoc utility program to extract the information and put it into an HTML
file.
- Documentation generated with javadoc, because that is the way the Java API library was
documented by Sun.
General form of a documentation comment
After the beginning /**, the first line or lines become the main description of your class,
variable, or method. After that, you can include one or more of the various @tags. Each @tag
must start at the beginning of a new line or follow an asterisk( * ) that is at the start of a line.
Multiple tags of the same type should be grouped together.
For example:
If you have three @see tags, put them one after the other.
/**
* @version 3.2
*/
Tokens
They are:
1. Reserved keywords
2. Identifiers
3. Literals
4. Operators
5. Separators
6. Variable
7. Datatypes
- Keywords are essential part of a language definition. They implements specific features of
language. Java language has reserved words, these keywords combined with operators and
separates according to syntax, from definition of the java language.
- Java language has reserved 50 words as keywords.
- Since keywords have specific meaning in java, we cannot use them as names for variables,
classes, methods and so on. All keywords are to be written in lower case letters.
Note: we should also not attempt to use the Boolean values true and false or null as names in our
program.
Identifiers:
- Identifiers are programmer-designed tokens.
- They are used for naming classes, methods, variables, objects, labels, packages and
interfaces in a program.
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 five major types of literals. They are:
Integer literals
Floating point literals
Character literals
String literals
Boolean literals
Data Types
Every variable in Java has data type. Data types specify the size and type of value that can be stored.
Java define eight simple types of data: byte, short, int, long, char, float, double and boolean.
These can be put in four groups:
Integers: This group includes byte, short, int and long, which are for whole valued signed
numbers.
Floating-point numbers: This group include float, double, which represent numbers with
fractional precision.
Characters: This group includes char, which represents symbols in a character set, like letters and
numbers.
Boolean: This group included boolean, which is a special type for representing true/false values.
Integers
Java defines four integer types: byte, short, int and long. All of these are signed, positive and
negative values. Java does not support unsigned, positive-only integers. The width and ranges of
these integer types is shown below:
byte b,c;
short s;
int a;
long seconds;
Floating-point numbers
Floating-point numbers also known as real numbers, are used when evaluating expressions that
require fractional precision. There are two kinds of floating-point types, float and double, which
represent single and double-precision numbers, respectively. The width and ranges are shown here:
double pi=3.1416;
Characters
In Java, the data type used to store characters is char. In C/C++, char is an integer type that is 8
bits wide. This is not the case in Java. Instead, Java uses Unicode to represent character. Unicode
defines a fully international character set that can represent all of the characters found in all human
languages. Some human languages have more than 256 characters such as Chinese and Japanese.
To represent this character it requires 16 bits. Thus in Java chars a 16-bit type. The range of char
is 0 to 65,536. there are no negative chars.
ch = ’X’;
Booleans
Java has simple type, called boolean, for logical values. It can have only one of two possible values,
true or false. This is the type returned by all relational operators, such as a<b.
Example:
boolean b;
b = true;
System.out.println(“ b is “ + b);
Standard Default Values
In Java, every variable has default value. If we don’t initialize a variable when it is first created,
Java provides default value to that variable type automatically as shown in table below:
Type of Variable Default value
byte zero : (byte) 0
short zero : (short) 0
int zero : 0
long zero : 0L
float 0.0f
double 0.0d
int zero : 0
char null character
boolean false
reference null
Separators:
Separators are symbols used to indicate where groups of code are divided and arranged. They
basically define the shape and function of our code.
For example:
The type is one of Java’s data type, or the name of a class or interface. The identifier is the name
of the variable. You can initialize the variable by specifying an equal sign and a value. To declare
more than one variable of the specified type, use comma-separated list.
Example:
char ch = ‘X’;
Java allows variables to be initialized dynamically, using expression valid at the time the variable
is declared.
For example,
- Java allows variables declared within any block. A block begins with an opening curly
brace and ended by a closing curly brace.
- 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.
- Variable declared inside a scope is not visible (accessible) to code that is defined outside
that scope. Thus, when you declared a variable within a scope, you are localizing that
variable and protecting it from unauthorized access and/or modification.
- Scope can be nested.
For example,
Each time you create a block of code, you are creating a new, nested scope. When this occurs,
the outer scope encloses the inner scope. This means that objects declared in the outer scope
will be visible to code within the inner scope. However, the reverse is not true. Objects declared
within the inner scope will not be visible outside it. To illustrate the effect of nested scope,
consider the following program:
{
int x; //known to all code within main
x = 10;
if (x == 10 )
{ //start a new scope
int y=20; //known only to this block
// x and y both known here (continued)
System.out.println(“x and y : ” + x + “ ” + y);
}
// y = 100; // Error ! y not known here
// x is still known here
System.out.println(“x is : ” + x);
}
}
As the comments indicate, the variable x is declared at the start of main()’s scope and is accessible
to all subsequent code within main(). Within the if block, y is declared. Since a block defines a
scope, y is only visible to other code within its block. Within the if block, x can be used because
code within a block (that is, a nested scope) has access to variables declared by an enclosing scope.
Variables are created when their scope is entered, and destroyed when their scope is left. This
means that a variable will not hold its value once it has gone out of scope. Therefore variables
declared within a method will not hold their values between calls to that method. Also, a variable
declared within a block will lose its value when the block is left. Thus, the lifetime of a variable is
confined to its scope. If a variable declaration includes an initialized, that variable will be
reinitialized each time the block in which it is entered. For example, consider the program given
below.
class LifeTime
int x;
Y = 100;
y is : -1
y is now : 100
y is : -1
y is now : 100
y is : -1
y is now : 100
As you can see, y is always reinitialized to –1 each time the inner for loop is entered. Even though
it is subsequently assigned the value 100, this value is lost.
Arrays
An array is a group of similar 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. Arrays offer a convenient means of grouping related information.
1. One-Dimensional Arrays
A one-dimensional array is a list of similar variables. To create an array, you first must create an
arrayvariable of the desired type. The general form of one-dimensional array declaration is
type var-name[ ];
Here,
type declares the base type of the array. The base type determines the data type of each element
that comprises the array. Thus, the base type for array determines what type of data the array will
hold. For example, the following declared an array named month_days with the type “array of
int”:
int month_days[];
Although, this declaration establishes the fact that month_days is an array variables, no array
actually exist. In fact, the value of month_days with an actual, physical array of integers, you must
allocate one using new and assign it to month_days. new is special operator that allocates memory.
The general
for of new as it applies to one-dimensional arrays appears as follows:
array-var = new type[size];
Ex : month_days = new int[12];
After this statement executes, month_days will refer to an array of 12 integers. Furthermore all
elements in the array will be initialized to zero. It is possible to combine the declaration of the array
variable with the allocation of the arrays itself, as shown here:
int month_days[] = new int[12];
Once you have allocated an array, you can access a specific element in the array by specifying its
index within square brackets. All array indexes start at zero.
For example, this statement assigns the value 28 to the second element of month_days.
month_days[1] = 28;
The next line displays the value stored at index 3.
System.out.println(month_days[3]);
Arrays can be initialized when they are declared. An array initializer is a list of comma-separated
expressions surrounded by curly braces. The commas separate the values of the array elements.
The array will automatically be created large enough to hold the number of elements you specify
in the array initializer. There is no need to use new. For example to store the number of days in
each month,
the following code creates an initialized array of integers:
class AutoArray {
int month_days[12] = {31, 28, 30, 31, 30, 31, 30, 31,
}}
2. Arrays of Arrays
In Java multi-dimensional arrays are actually arrays of arrays. To declare multi-dimensional array
variable, specify each additional index using another set of square brackets. For example, the
following declares a two-dimensional array variable called twoD.
This allocates a 4 by 5 array and assigns it to twoD. Internally this matrix implemented as an array
of arrays of int. conceptually, this array will look like the one shown in figure below:
Left index Given int twoD[ ][ ] = new int [4][5]; //determines row
The following program numbers each element in the array from left to right, top to bottom, and
then display these values:
class twoDArray {
int i, j, k=0;
twoD[i][j] = k;
k++;
}}
System.out.println(twoD[i][j] + “ ” );
System.out.println( );
}}
01234
56789
10 11 12 13 14
15 16 17 18 19
When you allocate memory for a multidimensional array, you need only specify the memory for
the first (leftmost) dimension. For example, the following code allocated memory for the first
dimension of twoD
when it is declared.
type[ ] var-name;
Here, the square brackets follow the type specifier, and not the name of the array variable.
For example,
Control Statements
1. if statements
2. switch statement
3. Conditional operator statement ( ? : Operator as discuss above )
if statements
The if statement is a powerful decision making statement and is used to control the flow of
execution of statements. It is basically a two-way decision statement and is used in conjunction
with an expression. Here is the general form of the if statement
if (test-expression) statement1;
It allows the computer to evaluate the expression first and then, depending on whether the value of
the expression (relation of condition) is ‘true’ or ‘false’, it transfers the control to a particular
statement. The if statement may be implemented in different forms depending on the complexity
of condition to be tested.
a) Simple if statement
b) If….else statement
i) Simple if statement
The general form of simple if statement is
if (test-expression)
{
statement-block;
}
statement-X;
The statement-block may be single statement or a group of statements. If the test-expression is true,
the statement-block will be executed; otherwise the statement-block will be skipped and the
execution will jump to the statement-X. For example:
if ( perc >= 35 )
result=”Pass”;
ii) The if..else statement
The general form of simple if statement is
if (test-expression) {
True-block statement(s);
}
else {
False-block statement(s);
}
statement-X;
If the test-expression is true, then the true-block statement(s) immediately following the if
statement, are executed; otherwise the false-block statement(s) are executed. In either case, either
true-block or false-block will be executed, not both. True block or false block may contain single
or multiple statement. For a single statement you don’t need to take curly braces.
int a, b;
// …..
if ( a< b)
a = 0;
else
b = 0;
statement-3;
}
statement-X;
If the condition-1 is false, the statement-3 will be executed; otherwise it continues to
perform the second test. If the condition-2 is true, the statement-1 will be evaluated;
otherwise the statmenet-2 will be evaluated and then the control is transferred to the
statement-X.
class ElseDemo {
public static void main(String args[]) {
int a = 10, b = 30, c = 20;
System.out.println(“Largest Value is : “);
if ( a > b) {
if (a > c)
System.out.println(a);
else
System.out.println(c);
}
else {
if (c > b)
System.out.println(c);
else
System.out.println(b);
}
}
}
if (condition-1) {
statement-1;
else if (condition-2)
statement-2;
else if (condition-3)
statement-3;
………………….
else if (condition-n)
statement-n;
else
default-statement;
}
statement-X;
This construct is known as the else if ladder. The condition is evaluated from top to bottom (of the
ladder), downwards. As soon as the condition is found, the statement associated with it executed
and the control is transferred to the statement-X (skipping the rest of the ladder).
When all the n conditions become false, then the final else containing the default-statement will
be executed. For example :
Switch statements
When one of the many alternative is to be selected, we can design a program using if statements to
control the selection. However, the complexity of such a program increases. The program becomes
difficult to read and follow. Java has built-in multiway decision statement known as a switch. The
switch statement test the value of a given variable (or expression) against a list of case value and
when a match is found, a block of statements associated with that case is executed. The general
form of the switch statement is shown below:
switch (expression)
{
case value-1:
block-1;
break;
case value-2:
block-2;
break;
………………..
………………..
default:
default-block;
break;
}
statement-X;
The expression is an integer expression of characters. value-1, value-2, …… are constants or
constant expressions and are known as case labels. Each of these values should be unique within a
switch statement. block-1, block-2,…..are statement lists and may contain zero or more statements.
There is no need to put braces around these blocks but it is important to note that case labels end
with a colon (:).
When the switch is executed, the value of the expression is successively compared against the
values value-1, value-2, ……. If a case is found whose value matched with the value of the
expression, then the block of statements that follow the case are executed. The break statement at
the end of each block signal the end of a particular case and causes an exit from the switch
statement, transferring the control to the statement-X following the switch.
The default is an optional case. When present, it will be executed it the value of the expression
does not match with any of the case values. If not present, no action takes place when all matched
fail and the control goes to the statement-X.
The break statement is optional. If you omit the break execution will continue on into the next
case. If is sometimes desirable to have multiple cases without break statements between them. For
example, consider the following program. As you can see, execution falls through each case until
a break statement for the end of the switch is reached.
class SwitchDemo {
public static void main(String args[ ] ) {
for(int I=0; I<12; I++)
switch(i) {
case 0:
case 1:
case 2:
case 3:
case 4:
System.out.println(“i is less than 5”);
break;
case 5:
case 6:
case 7:
case 8:
case 9:
System.out.println(“i is less than 10”);
break;
default:
System.out.println(“i is 10 or more”);
} break;
}
}
while
The general form of while statement is
Initialization
while (test-condition)
{
Body of the loop;
}
The while statement is an entry controlled loop. The test-condition is evaluated and if the condition
is true, then the body of the loop is executed. After execution of the body, the test condition is once
again evaluated and if it is true, the body is executed once again, this process of repeated execution
of the body continues until the test condition finally becomes false and the control is transferred
out of the loop. On exit, the program continues with the statement immediately after the body of
the loop. The body of the loop may have one or more statements. The braces are needed only if the
body contains two or more statements. Consider the following program:
class CalcTotal {
public static void main(String args[ ] ) {
int i, sum;
i = 1;
sum = 0;
while(i <= 10) {
sum = sum + i;
i++;
}
System.out.println(" Addition of numbers through 1...10 is : " + sum);
}}
The output of the program would be…..
Addition of numbers through 1...10 is : 55
do
As we know, in while loop a test the condition before the loop is executed. On some occasions it
might be necessary to execute the body of the loop before the test is performed. Such situation can
be handled with the help of the do statement. this takes the form:
Initialization
do
{
Body of the loop;
}
while (test-condition);
On reaching do statement, the program proceeds to evaluate the body of the loop first. At the end
of the loop, the test condition in the while statement is evaluated. If the condition is true, the
program continues to evaluate the body of the loop once again. This process continues as long as
the condition is true. When the condition becomes false, the loop will be terminated and the control
goes to the statement that appears immediately after the while statement. Since the test-condition
is evaluated at the bottom of the loop, the do….while construct provides an exit-controlled loop
and therefore the body of the loop is always executed at least once. For example, in the following
program test condition is false in the first attempt, still loop is executed only once.
class CalcTotal {
public static void main(String args[ ] ) {
int i, sum;
i = 100;
sum = 0;
do {
sum = sum + i;
i++;
} while(i <= 10);
System.out.println(" Addition of numbers through 1...10 is : " + sum);
}
}
The output of the program would be…..
Addition of numbers through 1...10 is : 100
for
The for loop is another entry controlled loop that provides a simple loop structure. The general
form of the for loop is:
1. Initialization of the control variables is done first, using assignment statement such as, i =
0. The variable i is known as loop-control variable.
2. The value of the control variable is tested using the test-condition. The test condition is a
relational expression, such as i < 10 that determines when the loop will exit. If the condition is true,
the body of the loop is executed; otherwise the loop is terminated and the execution continues with
the statement that immediately follows the loop.
3. When the body of the loop is executed, the control is transferred back to the for statement after
evaluating the last statement in the loop now the control variable is incremented using an
assignment statement such as i++ and the new value of the condition is again tested to see whether
it satisfies the loop condition. If the condition is satisfied, the body of the loop is again executed.
This process continues till the value of the control variable fails to satisfy the test condition.
class CalcTotal {
public static void main(String args[ ] ) {
int i, sum;
sum = 0;
for(i = 1; i <= 10; i++)
sum = sum + i;
System.out.println(" Addition of numbers from 1to 10 is : " + sum);
}
}
The output of the program would be…
Addition of numbers from 1to 10 is : 55
Jump statement
Java supports three jump statements: break, continue, and return. These statements transfer
control to another part of your program.
Using break
In Java, the break statement has three uses. First, in a switch statement to terminate a statement
sequence. Second, it can be used to exit a loop. Third, it can be used a “civilized”
form of goto. By using break, you can force immediate termination of a loop, by passing the
conditional expression and any remaining code in the body of the loop. When a break statement is
encountered inside a loop, the loop is terminated and program control resumes at the next statement
following the loop including infinite loops. The break statement can be used with any of Java’s
loop. When used inside a set of nested loops, the break statement will only break out of the
innermost loop. For example:
class BreakDemo {
public static void main(String args[ ]) {
for(int i = 0; i < 100; i++) {
if(i == 10) break; //terminate loop is I is 10
System.out.println(" i : " + i ) ;
}
System.out.println(" Loop Complete " ) ;
}
}
The output of the program would be..
i:0
i:1
.
.
.
i:9
Loop Complete
The break statement an also be employed by itself to provide a “civilized” form of the goto
statement. Java does not have a goto statement. By using this form of break, you can break out of
one or more blocks of code. These blocks need not be part of a loop or a switch. They can be any
block. The general for of the labeled break statement is shown here:
break label;
Here, label is the name of a label that identifies a block of code. When this form of break executes,
control is transferred out of the names block of code. To name a block, put a label at the start of it.
A label is any valid Java identifier followed by a color. For example, the following program shows
three nested blocks, each with its own label. The break statement causes execution to jump
forward, past the end of the block labeled second, skipping the two prinln() statements.
class BreakDemo {
public static void main(String args[ ]) {
boolean t = true;
first: {
second: {
third: {
System.out.println("Before the break" ) ;
if(t) break second; //break out second block
System.out.println("This won’t execute " ) ;
}
System.out.println("This won’t execute " ) ;
}
System.out.println("This is after second block " ) ;
}
}
}
*/
class Example {
C:\>javac Example.Java
- After compilation compiler will create .class file for each class. If program contain
more than one class, compiler will create separate .class file for each class. (in this
example compiler will create Example.class file, which contain Bytecode for
interpreter or JVM.
To actually run the program, you must use the Java interpreter, called java. To do so, pass the
class name Example as a command-line argument, as shown here:
C:\>java Example
- When you execute the Java interpreter as just shown you are actually specifying the name of
the class that you want interpreter to execute. It will automatically search for a file by that
name that has .class extension. If it finds the file, it will execute the code contained in the
specified class.
This is single-line comment. Java also uses a third style of comment /** …. */ known as
documentation comment. This form of comment is used for generating documentation
automatically. The next line of code is shown here:
This line begins the main() method. This is the line at which program begin executing. All Java
application begins by calling main(). The public keyword is an access specifier, which allows the
programmer to control the visibility of class members. When a class member is preceded by public,
then that member may be accessed by code outside the class in which it is declared. In this main()
must be declared as public, since it must be called by code outside of its class when the program
is started. 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 interpreter before any
objects are made. The keyword void simply tells the compiler that main() does not return a value.
In main() method there is only one parameter String args[] declares a parameter named args,
which is an array of String store character strings. In this case, args receives any command-line
arguments present when the program is executed. The next line of code is shown here. Notice that
it occurs inside main().
This line output the string “This is a simple Java program.” followed by a new line on the screen.
In this statement System is a predefined class that provides access to the system, and out is the
output stream that is connected to the console.