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

Java First Unit

The document provides an overview of Java programming, focusing on key concepts such as abstraction, encapsulation, inheritance, polymorphism, dynamic binding, and message passing. It discusses the benefits and applications of object-oriented programming (OOP), the evolution of Java, its features, and how it differs from C and C++. Additionally, it outlines the Java environment, including the Java Development Kit (JDK) and the structure of Java programs, including applets and their execution.

Uploaded by

iamavp1234
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Java First Unit

The document provides an overview of Java programming, focusing on key concepts such as abstraction, encapsulation, inheritance, polymorphism, dynamic binding, and message passing. It discusses the benefits and applications of object-oriented programming (OOP), the evolution of Java, its features, and how it differs from C and C++. Additionally, it outlines the Java environment, including the Java Development Kit (JDK) and the structure of Java programs, including applets and their execution.

Uploaded by

iamavp1234
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 37

Java Programmimg

Unit 1

Abstraction and Encapsulation


 Wrapping up of data and methods into a single unit (class) is known as Encapsulation.
 Encapsulated data is not accessible to the outside world.
 Methods in the class only can access the data.
 These methods provide the interface between the object’s data and the program.
 This insulation of data from direct access by the program is called data hiding.
Abstraction is a way of managing problem complexity by focusing on the essential details and
ignoring lower level details.

Forms of Abstractions in Programming World:


• Procedural Abstraction
• Data Abstraction

Procedural Abstraction:
 Procedural abstraction provides mechanisms for abstracting well defined procedures or
operations as entities.
 The implementation of the procedure requires a number of steps to be performed.
 In a Bank, credit and debit operations which involves various steps is a well defined
procedural abstraction.
Data Abstraction

 Data abstraction refers to, providing only essential information to the outside world and
hiding their background details, i.e., to represent the needed information in program
without presenting the details.
 Data abstraction is a programming (and design) technique that relies on the separation of
interface and implementation.
Real Life Example: TeleVision, which you can turn on and off, change the channel, adjust the
volume, and add external components such as speakers, VCRs, and DVD players, BUT you do not
know its internal details, that is, you do not know how it receives signals over the air or through a
cable, how it translates them, and finally displays them on the screen.

Inheritance
 Inheritance concept in OOP allows us to create a new class using existing classes.
 Objects of one class acquires the properties of another class.
 Class which is giving its properties is known as Base Class or Super Class.
 Class which acquires the properties is known as Derived or Sub Class
Additional functionality can be added to derived class (Extensibility). New class will have the
combined features of both.
 Using inheritance the hierarchical relationships are established. For example, Grand Father,
Son and Grand Son hierarchy.
inheritance allows the reusability of existing operations and extending the basic unit of a class
without creating from the scratch.

Real Life Example A bike manufacturer uses same mechanism of existing version of the bike while
launching a new version with some added functioflai1tes. This allows him to save time and efforts.

Polymorphism
 The word polymorphism means the ability to appear in many forms.
 In object oriented programming polymorphism refers to a programming language’s ability to
process objects differently depending on their data type or class.
 It is the ability to redefine methods for derived classes.
 An operation may exhibit different behavior in different instances. The behavior depends on
the types of data used in the operation.
polymorphism allows objects having different internal structures to share the same external
interface

Shape is the base class, where Circle, Box and Triangle are derived classes but having same external
interface Draw() to draw their respective shapes.

Shape Draw()

CircleDraw() Box Draw() Triangle Draw()

Examples: Addition Operation: For o numbers + operator produces the sum. For two strings, it
produces the concatenation of the strings to produce the third string. A word in English having
several different meanings dependingonthe context.

Dynamic Binding
 Binding refers to the linking of a procedure call to the code to be executed in response to the
call.
 Dynamic binding is determining the method to invoke at runtime instead of at compile time.
Dynamic binding is also referred to as late binding.
 It is associated with inheritance and polymorphism.
 Static binding occurs at compile time, while dynamic binding occurs at run time.
 Static binding uses data type, whereas dynamic binding uses object types.
Message Passing
 Objects communicates with each other by sending and receiving information.
 Message for an object is a request for execution of a procedure. It will invoke a method in the
receiving object.
 Objects can be created and destroyed.
 Communication with an object is feasible as long as it is alive.
 Two objects can communicate by passing each otherts objects to their methods

Example:
Employee.salaray(name);

Here, Employee is the object, salary is the message, name is the information sent.

Employee.Salary(BankAccount Act);

Here, Employee calls its own method Salary and passes BankAccount object Act to it. In this way
two objects of Employee and BankAccount classes communicate.

Benefits of OOP

The following are the benefits of OOP:


 Solutions to many problems associated with software quality
 Greater Programmer Productivity and hence lesser maintenance cost
 Redundant code is eliminated through inheritance
 We can build our programs from standard working modules without writing from scratch
 Data hiding enhances security
 Multiple objects can coexist without interference
 Objects in problem domain can be mapped with objects in programming
 Workload in a software project can be partitioned based on objects
 Data-centered design approach enables us to capture more details of a model
 Object oriented systems can be easily upgraded (scalable)
 Message Passing Systems make interface easier with external systems
 Software complexity can be easily managed

Applications of OOP
The following are the application areas of OOP:
 User Interface design in windowing systems
 Real-business systems
 Real-time systems
 Object-Oriented databases
 Hypertext, hypermedia and expertext
 Al and Expert Systems
 Neural Networks and Parallel Programming
 Decision Support and Office Automation Systems
 CAD(Computer Aided Design), CAM(Computer Aided Manufacturing),
 CIM (Computer Integrated Manufacturing) systems

Java Evolution
Java is a general-purpose, object-oriented programming language developed by Sun Microsystems,
USA in 1991.
 Originally called Oak by James Gosling, one of the inventors of the language
 Initially, Software for consumer electronic devices were designed using Java.
 Java overcomes the limitations of C and C++ such as portability and reliability.
 Problematic sources in C and C++ were removed in Java
 Java was made as a simple, reliable, portable and powerful language

1990 -Sun microsystems started developing a software for consumer electronic devices
l991 - The new language is named as Oak
1992 -The team own as Green Project demonstrated their applications developed in oak.
1993 -Development of web applet for WWW graphical environment
1994 -Development of web browser Hot Java
1995 -Oak was renamed as Java
1996 -Java Development Kit 1.0 (JDK) was released. Java established itself as leader of internet
programming
1997 -JDK 1.1 released
1998 -JAVA 2 released with JDK 1.2
1999 -J2SE (JAVA 2 Standard Edition), J2EE (JAVA 2 Enterprise Edition)
2000 -J2SE with SDK 1.3 was released
2002- J2SE with SDK 1.4 was released
2004- J2SE with JDK 5.0 (Instead of JDK 1.5) was released. It is known as J2SE 5.0

JAVA Features
The inventors of Java wanted to design a language that is portable, reliable and distributed but
simple.Fol1owing are the features of Java:

JAVA2 Features J2SE 5.0 Features


Compiled and Interpreted Ease of development
Platform- Independent and Portable Scalability and Performance
Objected – Oriented Monitoring and Manageability
Robust and Secure Desktop Client
Distributed Core XML Support
Familiar, Simple and Small Supplementary character support
Multithreaded and Interactive JDBC RowSet
High Performance
Dynamic and Extensible

Compiled and Interpreted - Java is both compiled and interpreted. It is a two-stage process. Java
compiler translates source code into byte code. Java interpreter generates machine code for the target
machine that is running the Java program.
Platform Independent and Portable - Java programs are portable. That is, they can be easily moved
from one computer to another, anywhere and anytime. Platform Independent means, changes and
upgrades in operating systems, processors and system resources will not force any changes in Java
programs. This is why Java is suitable for programming on Internet which connects different kinds of
systems worldwide. Size of the primitive data types is machine independent.
 Object Oriented - Java is true object-oriented language. Almost everything in java is an
object. All program code and data reside within objects and classes. Java comes with
extensive set of classes arranged in packages. Object model of Java is simple and easy to
extend.
 Robust and Secure - Java is Robust in the following ways:
• It provides many safeguards to ensure reliable code
• Strict compile time and run time checking for data types
• As it is garbage collected language, it relieves programmers from memory
management problems.
• Exception handling features which eliminates the risk of system crash.
 Security is a primary concern for a language like Java used in Internet programming.
 Java ensures no viruses are communicated with an applet
 It checks all memory access.
 Absence of pointers in java avoids unauthorized access to memory locations.

Distributed - Java is used for creating applications on networks.


 Distributed applications can share both data and programs.
 It can open and access remote objects on remote locations.
 It enables multiple programmers at multiple remote locations to collaborate and work together
on a single project.

Simple, Small and Familiar- Java is simple in the following ways:


 Java does not support problematic features of C and C++ such as unreliable code.
Java does not use pointers, preprocessor directives, header files, goto etc.
 It also eliminates multiple inheritance and operator overloading.
 Familiar in that it follows C or C++ syntax. Java uses many constructs of C and C++. Java is
also called a simplified version of C++.

Multithreaded and Interactive


 Multithreaded means handling multiple tasks simultaneously.
 Application need not wait for one task to complete before beginning another task.
 We can listen to audio clip while scrolling a page and also downloading an applet
 This multithreaded feature greatly improves interactive nature of graphics applications.
 Java RunTime contains tools for multiprocess synchronization

High Performance
 Java interpretation is fast and comparable to native C/C++.
 Java architecture reduces overheads during runtime.
 Multithreading also enhances overall execution speed of Java Programs

Dynamic and Extensible


 Java is capable of dynamically linking in new class libraries, methods and objects.
 Dynamically select the class type through query and can decide whether to link or not.
 Java is Extensible in that it supports functions written in C or C++, called native methods. Native
functions are linked dynamically at run time.
How Java differs from C and C++
 Although Java was modeled on C and C++, it differs from them in many ways. it does not
include number of features available in C and C++.

Differences between Java and C


Java does not include:
 Keywords sizeofand typedef
 Data Types structand Union
 Type modifier keywords auto, extern, register, signed and unsigned
 Explicit Pointer type
 Preprocessors #define, #include and #ifdef
 void- Functions with no arguments are declared with empty brackets and not void.
 new operators such as instanceof and>>> are included
 labeled break and continue statements are included
 object oriented features are included

Differences between Java and C++


Java does not include:
 Java is true object oriented language whereas C++ is C with object oriented extension
Java does not support:
o Operator overloading
o Template classes
o Multiple inheritance
o Global variable declaration
o Pointers
o Destructor function is replaced with finalizer() function
o Header files

Java and Internet


 Java is strongly associated with the Internet.
 Internet users can use Java to create applet programs and run them locally using a” Java-
enabled browser” such as HotJava.
 Java applets have made the Internet a true extension of the storage system of the local
computer. Applets from web pages can be downloaded and run locally.
 Internet users can also setup their websites containing java applets that could be used by other
remote users of Internet.
 This feature made Java most popular programming language for Internet.
 Java was meant to be used in distributed environments such as Internet. Since, both the Web
and Java share the same philosophy Java could be easily incorporated into the Web system.
 Before Java, the World Wide Web was limited to the display of still images and texts.
• Incorporation of Java into Web pages has made it capable of supporting animation, graphics, games,
and a wide range of special effects.
Remote Local Computer
Computer

Remote Applet

Internet

Java Support Systems

Systems supporting Java for delivering information on the Internet:

Internet Connection Local computer should be connected to Internet

Web Server A program that responds and services our request

Web Browser A program that provides access to WWW and runs Java Applets

HTML A language for creating hypertext for Web

APPLET tag HTML tag that places Java applets on web page

Java Code Java code for defining applets

ByteCode Compiled Java Code given in APPLET tag and transferred to the user computer

Java Environment
Java Environment or Architecture includes a large number of development tools called Java
Development Kit(JDK) and the classes and methods called Java Standard Library(JSL). JSL is also
known as API(Application Programming Interface).

Java Development Kit


Java Development Kit contains a collection of tools that are used for developing and running
Java Programs.

They are:
appletviewer- to run Java applets by reading and interpreting bytecodes
javac - Java compiler translates source code to bytecode and stores in .class file.
Java - Java interpreter
javap- Java disassembler to convert bytecode into program description
javah - to handle C header file
javadoc - to create java documentation as HTML files, using documentation comments included in
source code.
jdb - Java debugger for debugging a java program to find errors
The flowchart given below shows the process of building and running Java application programs:

Text Editor

Java Source Java doc HTML files

Javac

Java Class File Javah Header Files

Java Jdb

Java Program Output

Application programming Interface (API)


Java Standard Library (or API) includes hundreds of classes and methods grouped into
several functional packages. Most commonly used packages are:

Package Purpose
Language Support package Java.lang Class for the implementation of basic features of java
Utilities packages Java.util Classes for the utility functions such as date, time etc.
Input/output Package Java.io Classes for i/o opertations
Networking package Java.net Classes for communicating with other computers via
internet
AWT package Java.awt Classes that implement platform-independent
Applet package Java.applet Classes that provides basic functionality for applets

Overview of Java Language


Java is a general purpose, OOP language. We can develop two types of Java programs:
 Stand-alone applications
 Web applets
Executing a Stand-alone application involves the following two steps:
1. compiling source code into bytecode using javac compiler
2. Executing the bytecode program using java interpreter
Applet
 Applet are small Java programs developed for internet applications.
 An applet located on a distant computer (Server) can be downloaded via Internet and executed
on a local computer (Client).
 Applet can be created for doing everything from simple animated graphics to complex games
and utilities.
 Applets cannot read and write files that stand-alone applications can do.
 An applet can only be run within a Web browser.

The following are the sequence of operations for running an applet:

Java Source Code —> Java Compiler —> Java Enabled Web Browser —> Output

Java Program Structure


A java program is basically a collection of classes. A class is defined by a set of declaration
statementsand methods containing executable statements.
The general structure of a Java program is shown below:

Documentation Section
Package Statement
Import Statements
Interface Statements
Class Definitions
Main Method Class
{
Main Method Definition

Main Method Class is essential and all the other entries are optional.

Documentation Section
The documentation section contains comments about the program being written: In addition to two
types of comments in C and C++, Java includes a third type called documentation comment.
 Single line comment begins with//(double slash)
 Multi line comment begins with /* and ends with */
 Documentation comment begins with /** and ends with */

Single and multiline comments tell why, what and how of the program being written.

Documentation comments are written with special documentation tags as shown below
/** @author Kumar */
/** @version 1.1 */
/** @since 2015-03-31 */
javadoc utility collects these doc tags to create documentation about the program in the form of
HTML file.

Package Statement
 The first statement in a Java program is package statement.
 This statement declares a package name and informs the compiler that the classes defined
here, belongs to this package.
 package statement is optional, if we omit, java creates an empty package for it.
 A named package can contain any number of classes
Example:

package employee;

classemp\
{
------
}

Here, class emp belongs to employee package.

Import Statement
Next to package statement, there may be a number of import statements. This is equivalent to
#include statement in C/C++.
Examples:
importemployee.emp;

instructs the interpreter to load emp class alone that belong to employee package.

import employee.* ;
instructs the interpreter to load all the classes contained in employee package. * denotes all classes.

Interface Statements
An interface is like a class but includes a group of method declarations. It is optional, and
used only when multiple inheritance is implemented.

Class Definitions
A Java program may contain multiple class definitions. Classes are the primary and essential
elementsof a Java program. A simple Java program may contain only this pan. The main method
creates objectsof various classes and establishes communication between them. On reaching the end
of main, theprogram terminates and the control passes back to the operating system.

A Simple Java Program

// Displaying welcome message


class Hello
{

public static void rnain(String args[])

System.out.println(“Hello Welcome to Java”);


}

}
Explanation:

 classis a keyword that declares a new class


Java is a pure object-oriented program. Everything must be inside a class
 Hello is a Java identifier coined by the user to specify name of the class
 Class definition begins with opening brace { and ends with closing brace }
 There is no semicolon(;) at the end of class definition as in C++
 main() function(method) is similar to C and C++ main() function
 Java program execution begins at main() method
 Java program may contain any number of classes, but one of them must include main method.
 Keyword public is an access specifier that declares main as public method(unprotected) and
make it accessible to all other classes.
 Keyword static makes the main method belong to entire class and not for any object, because
interpreter uses this method before any objects are created.
 Keyword void states that the main method does not return any value
 String args[] declares args array of type String which is used to pass command- line
parameters while executing a Java program.
 System.out.println function displays the string Hello Welcome to Java. It is similar to
printf() in C and cout<< in C++. println always inserts a new line at the end of the output.

Java Tokens
Smallest individual units in a program are known as tokens. The compiler recognizes them. In
simple terms, a Java program is a collection of tokens; comments and white spaces. Java language
includes five types of tokens. They are:
Reserved keywords
Identifiers
Literals
Operators
Separators

Java Character Set


The smallest units of Java language are the characters used to write Tokens. These characters
are defined by the Unicode character set, an emerging standard that tries to create for a large number
of scripts worldwide.

Unicode Character Set


 The Unicode is a 16-bit character coding system and currently supports more than 34,000
defined characters derived from 24 languages in countries all over the World.
 ASCII character set is a subset of uiicode character set.

Keywords
 Keywords are essential part of a language definition.
 Java language reserved 50 words-as keywords.
 Keywords have specific meaning in Java.
 We can’t use them as names of variables, classes, methods and so on.
 Java is case-sensitive.
 All the keywords are to be written in lower-case letters.
The following are keywords in Java.

abstract boolean Case default else final goto if


assert break Catch do enum finally implements
byte Char double extends float import
Class for Instanceof
Const interface
Continue
Long native package return short this void
new private static throw volatile
protected strictfp throws while
public super transient
switch try
synchronized
Identifiers
 Identifiers in Java are the names of variables, methods, classes, packages, objects, labels and
interfaces.
 Identifiers are programmer-defined tokens.

The following are the rules for making an identifier:


1. They can have alphabets
2. They must not begin with a digit
3. Upper case and Lower case letters are distinct
4. They can be of any length

As a good programming practice, the following conventions are used by programmers:


 Identifier must be meaningful name suggestive of its use
 Short enough to be quickly arid easily typed and long enough to be descriptive
 When more than one words are used, the first letter is capitalized from the second word
onwards
 Private and local variables are written with lower case letters combined with underscore
character.
 All class names and interface names start with upper case letter
 Variables that represent constant values use all Upper case letters

Examples:
Public methods
average sum
Identifiers with more than one word:
dayTemperature firstDayOfMoflth totalMarks
Private and Local variables(Iower case letters only)
length batch_strength
All classes and interfaces (each words first letter should be in upper case)
Student HelloJava Vehicle MotorCycle

Variables that represent constant values (all upper case letters and underscore between the words)
TOTAL FMAX PRINCIPAL_AMOUNT
Java Separators
Separators define the shape and function of code in a Java program. They are symbols used
for grouping and arranging the code.

Parentheses 0 To enclose parameters in function definition and invocation, to specify


precedence for expression and type casting
braces { } to define block of code for classes, methods and local scopes, also to enclose
values for array initialization
Semicolon ; used to separate statements
Comma, used to separate variables in declaration
Period . used to separate packages from sub packages and reference variables from
member data or member method of a class

Java Statements
 A statement is an executable combination of tokens ending with a semicolon.
 There are 8 types of statements in Java

1 Empty Statement Do nothing statement that contains semicolon only

2 Labelled Statement Any statement beginning with a label e.g. first: a = 2;


3 Expression Statement Most statements are expression statements. They are Assignment,
Increment, Decrement, method call and allocation expression
statements.
4 Selection Statement To select one of several control paths or flows. They are if, if-else
and switch
5 Iteration Statement They specify how statements are repeatedly executed (looping). They
are for, while and do
6 Jump Statement They pass control to beginning or end of current block.They are
break, continue, return and throw
7 Synchronization They handle issues with Multithreading
statement
8 Guarding Statement For safe handling of code that may cause exception. They are try,
catch and finally
Implementing a Java Program
There are 3 steps in implementation.
 Creating the program
 Compiling the program
 Running the program
Note: Java Development Kit (JDK) must be installed in the system.

Creating the program


 Source Code Oava program) can be created using any text editor like Notepad. Edit, etc.
 The program should be saved in a file name with extension .java. e.g. Hello.java
 The filename should be same as the class name that contains main method.

Compiling the program


Run the javac compiler with the name of the source code file on the command line. For
example,

D:\jdkl.3\bin>javac Hello.java

If there are no errors in source code, java compiler creates a file called Hello.class containing
bytecodeS of the program. .class extension is automatically given by the compiler.

Running the Program


Java interpreter is used to run Java Stand-alone program. Appletviewer is used to run Java
applets. Run the Java interpreter with class name(that contains main method) alone without
extension .java or .class. For example,

D:\jdkl.3\bin> Java Hello

Machine Neutral Code


 The java compiler converts the source code into bytecode. The byte code is machine-
independent.
 It can be run on any machine.
 Program compiled on IBM machine will run on Macintosh machine without any
modifications.
 Java interpreter translates the bytecode into machine-specific code.
 Java Interpreter is therefore specifically written for each type of machine for conversion of
bytecode into specific machine code.

Java Virtual Machine(JVM)


Java compiler produces an intermediate code known as bytecode for a machine that does not
exist. This machine is called Java Virtual Machine. Hence, bytecode is known as virtual machine.

Java Program —* Java Compiler —* Bytecode(virtual machine) —* Java Interpreter — Machine Code (Real Machine)

Command-Line Arguments to a Java Program


Command line arguments are parameters passed to main() method from command line while
executing a program. Any argument provided in the command line are passed to String array args[j as
its elements. For example,

D:\jdkl.3\bin> java Test ABC Java 123

Here, the command line arguments contain 3 values. They are assigned as String value elements of
the array args[] as
args[0]—>ABC
args[11 —> Java
args[21 —>123
Constants, Variables and Data Types

A programming language processes certain kinds of data consisting of numbers, characters


and strings to produce output known as information.

Constants
Constants in Java are fixed values that do not change during the execution of a program. The
values are also called literals.

Literals
Literals are constants values to be stored in variables. Five types of literals in Java are:
o Integer literals
o Floating point literals
o Character literals
o String literals
o Boolean literals
 Each of them is associated with a data type.
 Type tells how the values behave and stored.

Java Constants

Numeric Non-Numeric
Constants Constants

Integer Real Single String Constants


Constants Constants Character Constant

Integer Constants
An integer constant is a sequence of digits. There are 3 types: decimal integer, octal integer
and hexadecimal integer.
Decimal integers consists of digits 0 to 9.
They can be negative (preceded by - sign)
Examples : 329 -45 78234

Octal integers consists of digits 0 to 7 with a leading 0.


Examples: 0145 0777 0126

Hexadecimal integers consists of digits 0 to 9 and alphabets A through F preceded by OX or Ox.


Alphabets A through F represent numbers 10, 11, 12, 13, 14 and 15 respectively.

Examples: 0X123 OXA2B OxFFI

Real Constants
 Real constants are used to represent quantities that vary continuously such as distance,
temperature, height, prices etc.
 These quantities are numbers with fractional parts.
 There are two notations used in real constant representation, namely, Decimal Notation and
Exponential notation.
 Constants may or may not have digits before or after the decimal point.
 Decimal point is compulsory

Examples: Decimal Notation: 0.0001 -0.56 532.12


21. .95 -.23

The general form of exponential notation is: mantissa e exponent

Mantissa is a real number in decimal notation. Exponent can be a +ve or -ye integer.

Example: 123.82 can be written as 1.2382e2 or 1.2382E2, where e2 stands for 102 -3 .08E-2

Exponent notation is useful for representing very large or very small numbers.

Single Character Constants


A single character constant or simply character constant contains a single character enclosed
within a pair of single quote marks(’). Example: ‘m’ ‘f ‘5’ ‘‘(space)

String Constants
A string constant is a sequence of characters enclosed between double quotes. The characters
may be alphabets, digits, special characters and blank spaces.

Example: “Welcome” “2015” “*_*_*_**_“ “ “(blank spaces)

Backslash Character Constants


Java supports some special backslash character constants that are used in output methods.
\n Inserts a new line in output
\f Form feed - Moves the paper in printer to next page
\b Erases one character to the left of cursor - Equivalent to backspace character in keyboard
\r Carriage Return - Moves the cursor to the beginning of the line
\t Moves cursor to next tab position (Horizontal Tab)
\v Vertical space between lines (Vertical Tab)
\‘ To get single quote in output
\‘ To get double quote in output
\\ To get backslash character in output

Variables
 A variable is an identifier that denotes a storage location used to store a data value.
 A variable may take different values at different times during the execution of a program.
 Variable names may consists of alphabets, digits, underscore ( _ )and dollar character, subject
to the following conditions:
o They must not begin with a digit
o Uppercase and lower case are distinct. i.e. Total, total and TOTAL are different
variable names.
o It should not be a keyword.
o White space (space bar) is not allowed.
o Variable names can be of any length

Data Types
 Data types specify the size and type of values that can be stored in a variable.
 Java language is rich in its data types.
 There are two major categories namely, primitive types(built-in or intrinsic) and
derived(reference) types

Data Type in Java

Primitive (Built-In) Non-Primitive(derived)

Numeric Non-Numeric Class Array Interface

Integer Floating Point Character Boolean

Integer Types
 Integer types can hold whole numbers (34, -78, 1000)
 Java supports 4 types of integers.
 They are: byte, short, intand long
 All integer types are signed one. unsigned type is not supported by Java

Table shows each type, their memory size and values that can be stored in them:

Type Memory Size Minimum Value Maximum value


Byte 1 byte -128 +127
Short 2 bytes -32768 +32767
Int 4 bytes -214,74,83,648 +214,74,83,647
Long 8 bytes -9,223,372,036,854,775,808 -9,223,3 72,036,854,775,807

 Wider the data types, they require more memory and longer execution time.
 We have to choose smaller type for small numbers to improve execution speed.
 long values are appended with character I or L. Example: a = 123456L
Floating Point Types
 Floating point types can hold numbers containing fractiohal part(real numbers) such as
12.45, -0.03
 There are two kinds of floating point storage namely, float and double.
 float type values are single precision numbers (6 decimals accuracy)
 double types values are double precision numbers (12 decimals accuracy)
 float type values are appended with for F. Example d=34.567F
 doubletype values are used when greater precision is needed in computation.
 By default all floating point values are treated as double.
 Explicitly double type values are appended with d or D.
Example m =234.34217890d

Type Memory Size Minimum Value Maximum Value


Float 4 bytes 3.4e-38 +3.4e+38
Double 8 bytes 1.7e-308 1.7e+308

Boolean
 boolean data type represents one bit of information.
 There are only two possible values: true and false.
 This data type is used for simple flags that track true/false conditions.

Character
 The size of char type is 2 bytes, but it can hold single Unicode character
 Unicode character set is an international character mapping scheme that supports more than
50 languages all over the world.
 Minimum value is ‘\u0000’ (or 0).
 Maximum value is ‘\uffff (or 65,535).
Variable Declaration
Variable declaration perform three things:
1. It tells the compiler what the variable name is.
2. it specifies the type of data the variable can hold.
3. Scope of the variable is determined by its place of declaration.

General form of declaration:


type variable1, variable2 variableN;

o More than one variable of same data type can be declared in a line
o Each one is separated by a comma
o Declaration must end in a semicolon (;)

Examples:
int quantity;
float angle, height;
double radius;
byte slno;
char sex;

Assigning values to variables


By default, Java assigns 0 to numeric variables, ‘\u0000’ to character variables, false to boolean
variables.

We can assign values to variables in two ways:


1. Using assignment statement
2. Using read statement

Assignment statement:
start=0;
end=15;
sex=’M’;

Multiple assignments:
X= y = z = 0;
At the time of declaration:
inta=5;
double d =75.36;
long b = 1234567L;
float m = 5.67f;
char sex=M’;
byte s=5;
short k=32000;
Read Statement:
Variables can be given values interactively through keyboard using readLine() method as shown
below:
DatalnputStream d new DatalnputStream(System.in);
inta;
float b;
a Integer.parselnt(d.readLine());
b = Float.valueOf(d.readLine()).floatValue();

Scope of variables
Area of the program where the program is accessible is called its scope.
Java variables are classified into three kinds:
o instance variables
 class variables
 localvaries
 instance variable is declared inside a class
 instance variables are created when objects are created
 they take different values for each object
 separate memory location is allocated for them
 class variables are global to a class
 they belong to entire set of objects
 only one memory location is allocated for them
 local variables are declared and used inside methods
 they are not available outside the method definition
 local variables can be declared inside program blocks ({ })
 when program control leaves the block, all the variables inside the block are destroyed and
memory freed.

Symbolic Constant
Certain constants may appear repeatedly in a number of places of a program.
Assignment of a symbolic name to such constants relieves us from typing the same value in
all the places. Symbolic constant is declared with the keyword final as given below:

final type symbolic value;


Examples:
finalint QUANTITY = 100;
final intPASS_MAR3O;
final float Pl3.l4l59
Advantages:
o Modifiability
oUnderstandability

Modifiability means, the modification of the value is done in one place only, which changes the
value in all the formulas which use it. Using symbolic constants in place of literals makes the
program easy to understand.

For example, Area_Of_Circle=3.14 * r * r;


Area_of_Cylinder = 3.14 * r * r * h;
Circumference= 2 * 3.14 * r;

After defining a symbolic constant P1, final float P1 = 3.14f; the same formulae are in more
understandable form as shown below:

Area_of_Circle =P1 * r * r;
Area_of_Cylinder = P1 * r * r * h;
Circumference = 2 * P1 * r;

Moreover, accuracy can be improved by modifying the value in one place as final float P1 = 3.141
59f;

Note that:
o Symbolic name declaration takes the same form as variable declaration.
o They are written in uppercase letter (not a rule) to differentiate them from variables.
o After declaration, symbolic constants should not be assigned any other value.
o They cannot be declared inside a method. They should be declared as class data members or
in interface.

Type Casting (Explicit Type Conversion)


Type casting is storing a value of one type into a variable of another type. To do so, we must
cast the value to be stored by preceding it with the type name in parentheses.

Syntax: type variable1 = (type) variable2;

Examples:
Int m=50;
long n = (long) m; // which stores the value as long integer
float a = (float) m; //which stores the value 50 as 50.0

 float, double integer types can be cast to any other type except boolean
 Casting to smaller type can result in a loss of data
 Casting a float value to integer results in loss of fractional part.

Automatic Conversion(Implicit Type Conversion)


Automatic conversion between one type to another without type casting is possible for certain
data types. Java performs the conversion automatically. Assigning a smaller type to larger type is
called widening and larger type to smaller type is narrowing. Narrowing may result in loss of data.

Examples:
Byte b=75;
int a = b; // widening
long a =100L;
int b = a; // narrowing

char c = ‘A’;
int n = c; // It stores the ASCII value of A, 65 in integer variable n.

int n=65;
char c =n; //It stores the character ‘A’ corresponding to the ASCII value 65 in variable c.

Display of Values in Output


Print() method of outclass in System packagedisplays the given set of results and wait in the same
line until a new line character is encountered.

println() method (print in a line) method of out class in System package displays a given set of results on a
line followed by a line feed (\n).

Examples:
system.out.Print(”Oh!“);
system.out.print(“God! \n”);
System.out.Print(“save me”);
output: Oh! God!
Save me
Here, Oh! and God! are displayed in the same line and \n inserts a line feed. Save me is
displayed on the next line.

Operators and Expressions


 An operator is a symbol that tells the computer to perform certain mathematical or logical
manipulations.
 Java supportS a rich set of operators.

Operators in Java are categorized as follows:


1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Increment and Decrement Operators
6. Conditional Operator
7. Bitwise Operators
8. Special Operators

1.Arithmetic Operators
 Arithmetic operators are used to construct mathematical expressions.
 Arithmetic operators can operate on any built-in java numeric data types

Operator Meaning
+ Addition or unary plus
- Subtraction or unary minus
* Multiplication
/ Division
% Modula Division(Remainder)

Examples: a+b a-b a*b a/b a%b a*b

Here, a and b are called operands which can be variables or constants.

 If both operands are integer, integerarithmetic is performed and the result is integer e.g.
5/2=2 (result is not 2.5)
 If both operands are real, floating point arithmetic is performed and the result is real
2.2/1 .1=2.0
 For modulo division, sign of the results is always sign of the first operand
e.g. -l0 % 3= -l and l0 %-3= l
 If one of the operands is integer and the other is real, the expression is called mixedmode
arithmetic expression. Computer performs higher order arithmetic. i.e. integer is converted to
real and the arithmetic is performed. Compared to integer, real is higher order, compared to
float, double is higher order.
2.Relational Operators
 Relational operators compare two quantities.
 We take decision depending on their outcome.
 An expression containing relational operator is called relational expression.
 The value of a relational expression (outcome) is either true or false.

Syntax: ae-1 relational operator ae-2

ac-1 and ae-2 can be variables or constants or arithmetic expressions. Arithmetic expressions are
evaluated first before comparison.

if your age is 20, then comparison with relational operator ‘>‘

age> 17 results in a value true.

if your age is 16, it results in a value false.

Operator Meaning
< Is less than
> Is greater than
<= Is less than or equal
>= Is greater than or equal
== Is equal to
!= Is not equal to

Examples:
a=5, b=8, c=10, d=7

a+b>c+dcompares 5+8>10+7, i.e. 13> 17 which is false


8 and 10 are not compared first. Hence, Arithmetic expressions are evaluated first before comparison.

3. Logical Operators
 Logical operators are used to form compound conditions by combining tw or more relations.
 Two or more relational expressions are combined to form logical expressions or compound
relational expression.
 Logical expressions result in true or false values.
 Java has three frequently used logical operators:
&&-Logical AND
|| - Logical OR
! - Logical NOT

Examples: if (experience>=5 && age<=35) mark =5; Here, the if statement checks the test
condition experience >=5 and age <=3 5, if both conditions are true the result will be true and 5
marks will be given to a candidate attending an interview. If one or both of them is false, the result
will be false.

if(experience =>5 j age<=25) mark 2; Here, if anyone of the condition is true, the result will be true
and 2 marks will be given to a candidate attending an interview. If both of them is false, the result
will be false.
Logical NOT operator complements false to true and vice versa. !(age>35) if age is 36 then condition
is true, ! will make it false. If age is 20 the condition is false. ! will make it true.

4. Assignment Operator
 Assignment operator = is used to assign the value of an expression to a variable.
 Java also supports shorthand assignment operators +=, -=, ,/=, %=.

Syntax of assignment operator: v op= exp;


v - variable, op - operators exp - expression.
x =x + 5; can be written in short form as x+=5; where x is accessed from memory only once.

Examples:
a=a+5; a+=5;
aa- b; a-b;
a a * (x+y); a = (x+y);
a’a/5, a15;
aa%S; a%5;

Uses of short hand operator:


1. left hand side variable need not be repeated on right-hand side
2. statement is concise and easier to read.
3. results in more efficient code.
5. Increment and Decrement Operators
 Java has increment and decrement operators: ++ and
 The operator ++ adds I to the operand.
 The operator -- subtracts I from the operand.
 They are used in prefix (pre increment/decrement) or postfix(post increment/decrement)
position of a variable. They have same meaning w1n they form statements independently.
 They behave differently in expressions.

Examples:
a = 5;
a++; or ++a; mean the same, which increments the value of a by 1 and it becomes 6.

case 1: b=++a;
case2: b=a++;
o In case 1, Pre increment increments the value of a and assign the result 6 to b.
o In case 2, Post increment assigns the current value of a 5 to b and then increments it to 6.
o In both cases, value of a becomes 6, but what is assigned to b is different.

6. Conditional Operator
 The conditional operator is a temary operator.
 It requires three operands.
Syntax: expi ?exp2 : exp3

 The operator? evaluatesexpifirst.


 If it is true, then exp2 is evaluated and it becomes the value of the conditional expression.
 If expi is false, exp3 is evaluated and it becomes the value of the conditional expression.
Example:
Exp1 exp2 exp3
v = (a> b) ?x+y :p+q;

suppose, a = 5 and b = 3, then variable v is assigned the value of x+y.


suppose, if a = I and b = 7, then variable v is assigned the value of p+q;

7. Bitwise Operators
 Bitwise operators manipulate data values at bit level.
 They are used for testing the bits or shifting them to the left or right.
 Bitwise operators cannot be applied to float or double.
& - Bitwise AND
|-Bitwise OR
^- Bitwise Exclusive OR
~- Bitwise NOT (l’s complement)
<<-Shift left
>> - Shift right
>>> - Shift right with zero fill
Examples:
inta=5, b=4,c;

Bitwise & operator- c =a & b; Bitwise operator-c =a | b;


Binary value of a =101 a & b yields the result= 101
Binary value of b= 100 (produces 1 if anyone of them is i, produces
a & b yields the result = 100 0 if both are 0*s)
(produces 1 if both are l’s otherwise 0)
Bitwise ~ operator - c = -a; ~101yields the result 010(converts 0 to 1, and 1 to 0)

Bitwise ExclusiveOR operator ^-c= a ^ b yields the result 001


a 101
b--> 100
a ^ b 001 It gives 0 when bits are same and 1 when bits are different.

Shift left operator <<


a<<1; Shifts the binary value of a by one position left

1 0 1

The first bit 1moves out, following bits are moved 1 position left. The last position is filled with 0.
The value becomes 010. Similarly, the right shift>> moves the last bit out and the blank in first
position is filled with 0. If the number is negative, it fills the blank position with 1.

1 0 1

>>> right shift with zero fill, fills the blank position always with zero irrespective of the sign of the
number.
8. Special Operators
 Java supportS two special operators
 They are: instanceof operator and .(dot) member operator
instanceof operator returns true if an object belongs to aclass we check.
Example mango instanceof fruit yields the result true if mango is an object of class fruit.
false otherwise.

dot operator is used to access the instance variables and methods of objects.
employee.age - accesses the age data member of employee object
employee.Tax_calc() - access the Tax_calc() method of employee object

Operator precedence and associativity


 Each operator in java has precedence associated with it.
 Precedence determines how the expression containing more than one operator is evaluated
 Operator with higher precedence is evaluated first
 Operators with same precedence or evaluated either from left to right or from right to left
which is called associativity
Associativit
Operator Rank
y
.(dot) member operator
() function call Left to
1
and expression in parentheses Right
[] Array element reference
-unary minus
++ Increment
-- Decrement Right to
2
!Logical Negation Left
~ l’s complement
(type) casting
* multiplication
Left to
/ division 3
Right
% modulus
+ addition Left to
4
-subtraction Right
<<left shift
Left to
>> right shift 5
Right
>>> right shift with zero fill
<less than
Left to right
<= less than or equal to
6
> greater than
>= greater than or equal to Instance of
= = equality
Left to right 7
!=inequality
& bitwise AND Left to right 8
^ bitwise XOR Left to right 9
| bitwise OR Left to right 10
&& logical AND Left to right 11
|| logical OR Left to right 12
?: conditional Right to left 13
= assignment
Right to left 14
op= shorthand assignment

Example:
x =10;
y=5;
if(x == 10+15 && y<10)

Order of evaluation Result


10+ 15 25
x==25 false
y<10 true
false&& true false
The compound condition x ==25 && y <10 is false.

Decision Making and Branching


 Statements in a Java program normally executes sequentially in the given order
 In many situations, we have to change the order of execution based on certain conditions. This
is known as Decision making.
 Decision making involves condition checking and then directing the computer to execute
certain statements.
 When a program breaks the sequential flow and jumps to another part of the code, it is called
branching.

Java supports the following statements for decision making or control statements:
1.ifstatement
2.switch statement
3. Conditional operator?: statement
The if Statement
The ifstatement is a decision making statement used to control the flow of execution of
statements. It is a dual alternative decision statement.

Syntax: if(test expression)


 It allows the computer to evaluate the test expression.
 Based on the outcome of the test expression as true or false, it transfers the control to a
particular statement.
 There are two paths to follow one for true and another for false value of test expression.

Different forms of if statement based on the complexity of the conditions to be tested:

1.Simpleif statement
2. if.. else statement
3. Nested if..else statement
4. elseif ladder

1.Simpleif statement
if(test expression)
{
statement-block
}
statement-X
o Statement-block may be a single statement or a group of statements.
o If test expression is true then the statement-block is executed otherwise it is skipped and the
execution will jump to statement-x.
o If the condition is true both the statement-block and statement-X are executed.
Example:
ticketprice = 100;

if(age>=65)
{
tic ket_price5 0;
}
System.out.println(ticket_price);
The if statement given above fix the ticket_price as 50 for senior citizens and 100 for others.

2.if.. else statement


if(test expression)
{
True-block-statement(s);
}
else
{
False-block-statement(s);
}
statement-X;
If the test expression is true, True-block-statements following the if statement are executed otherwise
the False-block-statements are executed. Control is transferred to statement-x after executing anyone
of the blocks.

Example:
if(sex’m’)
{
boy_countboy_count+ 1;
}
else
{
girl_count= girl_count+ 1;
}
start=l;

If sex is equal to ‘m’ (male), the statement boy_count=boy_count+ 1 is executed and the control is
transferred to statement start= 1.

3.Nestedif.. else statements


More than one if..else statement is used in nested form when a series of decisions are to be
made.

Syntax:
if (test condition-i)
{
if(test condition-2)
{
statement-i;
}
else
{
statement-2;
}
}
else
{
Statement-3
}
statement-x;

 If the test condition-I is false, the statement3 will be executed.


 If the test is true, then the test conditiofl2 is tested.
 If test conditi02 is true, statement-I will be executed otherwise, statement2 mill be executed.
 When writing if else statements, care should be taken to match every if with an else.

Example:

if(sex== ‘m’)
{
if (age> 50)
{
medical_leave_days=30;
}
else
{
medical_leave_days=20;
}
}
else
{
medical_leae_Y5 = 50;
}
System.out.Println(sex + “ “+medical_leave_days);

Here, male employees aged more than 50 years are given 30 days of medical Icave and 20 days for
those males aged upto 50. For females it is 50 days with no restriction on age limit.

4. else if ladder
else if ladder is used when multipath decision are made. It is called as ladder as each statement
associated with else is another if statement.
Syntax: if (condition-i)
statement-i;
else if(condition-2)
statement-2;
else if (condition-3)
statement-3;
------------
else if(condition-n)
statement-n;
else
default-statement;
statement-x;
 The conditions are evaluated from top.
 As soon as the true condition is found, the statement associated with it is executed and the
control is transferred to statement-x.
 If all the conditions are false, the default-statement is executed.

Example:
if(marks> 74)
grade =“Distinction”;
else if(marks>59)
grade=”First”;
else if(marks>49)
grade=” Second”;
else if(marks> 39)
grade=”Third”;
else grade = “Fail”;
5. Swtich Statement
When the number of alternatives increases, use of else if ladder makes the program difficult to read
and understand. Java supports another multi-way decision statement called switch statement. Switch
statement test the value of the given variable against a list of case values. When the match is found,
block of statements associated with a case is executed. If no match is found, default block is executed.

Syntax: switch(expression)
{
case value-1:
block-1;
break;
case value-2:
block-2;
break;
case value-3:

block-3;
break;
--------------
default:
default-block;
}
statement-X;
 The expression is an integer expression or characters. value-1, value-2…... are constants or
constant expressions.
 They are called case labels. The value of the expression is successively compared against
value-1, value-2…
 When a match is found, block of statements that follow the case is executed.
 break causes exit from switch statement.
 default is an optional case. Block of statements in default case is executed if there is no match
with other cases.

Example:
switch(n)
{
case I: System.out.println(”ONE”);
break;
case 2: System.out.println(”TWO”);
break;
case 3 :System.out.println(”THREE”);
break;
case 4:System.out.println (”F0UR”)
break;
defauit:System.out.println(“Value of n should be in the range 1 -4”);
}
?: Operator
This operator has been discussed in Java Operators section.
 This operator takes three operands.
 It is known as conditional operator.
 It makes two-way decisions.
 It can be nested for more complex decisions
 Use of conditional operator makes the code concise and efficient, but realability is
poor when it is nested.

Syntax: conditional expression ?expressioni : expression2

The conditional expression is evaluated first. If the result is true, expression 1 is evaluated and
returned as value of the conditional expression, otherwise, expression2 is evaluated and returned.
Example: if(a> b)

big=a;
else
big=b;
The if statement given above can be written as
big= (a >b) ? a : b;
sign=(x==0)?0 : (x <0)? -l : +1 ;//Nested?:to get sign ofa number as 0 or-i or +1.

Looping –

 The process of repeatedly executing a block of statements is known as Looping.


 A statement block may be executed from 0 to infinite number of times.
 A sequence of statements are executed until some conditions are met.
 A loop consists of two parts namely control statement and body of the loop.
 Control statement tests the conditions and directs the repeated execution.
 Depending on the position of the control statement in the loop, there are two types of
loop namely entry-controlled and exit-controlled loop.
 Entry-controlled loop tests the condition before the start of the loop. If the condition is
not satisfied, the body of the loop will not be executed.
 Exit-controlled loop tests the condition at the end of the body of the loop. Body is
executed unconditionally for the first time.

Java provides the following three types of loop:


1.forloop
2. while loop
3. do while loop
for loop
 for loop is an entry-controlled loop.
 It provides aconcise loop control structure.

Syntax: for(initialization; test condition ; increment)


{
Body of the loop
}
statement-x;
 Initialization of loop control variable(index variable) is done first using assignment statement
like i=l, count0 etc.
 Test condition is a relational expression such as i <100 which determines when the loop will
exit. if the condition is true, body of the loop is executed otherwise, the loop is terminated and
the execution continues with the statementx.
 When the body of the loop is executed, control is transfeff back to for statement. Now, the
control variable is incremented like i i +1 or count count+2 and the condition is tested again.
This continues till the value of control variable fails to satisfy the condition.
 Braces are optional if the body contains a single statement.
 If the condition fails at the very first test, body of the loop will not be executed at all.

Examples:
for(i=4 ;i< =10;i=i+l)
{
system.out.println(i);
}
system.out.println(“LOOP OVER”);

Here, loop control variable i varies from1 to 10 and the body of the loop is executed 10 times. It
displays every value of i (l,2,3...10). When i is incremented to 11, loop exits and displays LOOP
OVER message.

for(i=10; i>=1; i =i - 1)
{
System.out.println(i)
}
System.out.println(“LOOP OVER”) ;

Here, for loop allows negative increment. Values from 10 to 1 are printed in decreasing order.

Nesting of for loops


Nesting of for loop means giving one for statement inside another for statement. While
nesting, for loops must be properly indented to enable the user to understand the body of each for
loop.
for(i=l ;i<=5 ;i++)
{
for(j=1 ;j<=10;j++)
{
product=i *j;
System.out.println( j+” x “+i+” = “+p);
}
System.out.print(”\n”);
}

The above program code will print multiplication table I to 5 with 10 entries for each table as shown
below:
1x1= 1
2x1= 2
3 x 1=3
-----
-----
10x 1= 10
upto 5 tables.

while Loop

The while is an entry-controlled loop.

Syntax: initialization
while (test condition)
{
body of the loop
} Statement-x;
 Test condition is evaluated and if the condition is true, then the body of the loop is executed.
 The process is repeated until the test condition finally becomes false.
 When the condition becomes false, control is transferred out of the loop and Statement-x
following the loop is executed.
 Compared to for loop initialization is done outside the loop, increment is inside the body of
the loop.
 Body of the loop may have one or more statements. Braces are needed only if the body
contains two or more statements.
n= 1;
sum=0;
while(n<=10)
{
sum = sum + n;
n = n +1;
}
This while loop finds the sum of numbers 1+2+3+4..upto 10. The condition may also be written as
n<11.

DatalnputStream ds =new DatalnputStream(System.in);


n=-1;
while(n<0)
{
System.out.println(“Please enter a positive number”);
n = Integer.parselnt(ds.readLine());
}

This while loop repeats the input statement until the user enters a positive value for n. Initially a
negative va’ue is given to n to make the condition true when tested for the first time.

do while loop
do while loop is exitcontroed loop. It is used when we want to execute the body of the loop
before the test is performed.

Syntax: initialization;
do
{
Body of the loop;
}
while (test condition);
statement-x;
 On reaching the do statement, body of the loop is executed first.
 Test condition is evaluated at the end of the loop.
 If the condition is true, the program continues to evaluate the body of the loop once again.
 The process continues until the condition remains true.
 Loop terminates when the condition becomes false and statemefltx following the loop will be
executed.
 do while loop is suitable for menudriVen program5 where the menu is to be displayed first
followed by user response in making a choice from the menu.

Example:
i =101;
do
{
System.out.println(i);
i=i+l;
}
while(i<100);

Here, initial value of i (101) is displayed even though the condition is false. When it tests the
condition at the end of the loop, the condition becomes false( 102 <=100 is false) and the loop is
terminated, do while loop executes the body atleast once irrespective of the true or false nature of the
test condition.

Jumps in Loops
It may be desirable to perform early exit from a loop before its normal exit. It may be
necessary to skip part of the loop and continue with next value of loop c ntrol variable.

break statement
 break statement performs early exit (aborting the ioop based on some conditions)
 on encountering break statement, the ioop is immediately stopped and the statement following
the body of the ioop is executed.
 When the loops are nested, break statement exits from the loop containing it. i.e. break will
exit only a single loop

continue statement
 continue statement causes the ioop to be continued with next iteration
 It skips any statements given after the continue statement until the end of the body of the
loop.
 It causes the control to go directly to the test condition and continues the loop with next
value of the ioop control variable.
 continue statement restarts the current loop.

Labelled Loops
 Any statement or block of statements can be given a label. A label is a valid Java variable
name followed by a colon(:).
 With the use of labels, we can break any loop in case of nested loops.
 With the use of labels, we can continue any loop in case of nested loops.

labelled continue

Example:
outer: for(i=1 ;i<=1000;i++)
{
inner: for(j=1 ;j<=500;j++)
{
if(i % 8 = =0) continue outer;
if(i == 750) continue inner;
-----
-----
}
}

Here, if the value of i is a multiple of 8 (8, 16, 24,32 and so on) , next iteration of i loopwhose label is
outer: is continued skipping remaining part of the inner ioop. If i reaches the value 750, remaining
part of the j loop is skipped and the next iteration of j loop is continued.

You might also like