0% found this document useful (0 votes)
3 views29 pages

Introduction to Java Programming Concepts

The document provides an introduction to Java programming, covering fundamental concepts of object-oriented programming such as classes, objects, inheritance, polymorphism, abstraction, and encapsulation. It also discusses Java's history, features, development environment, data types, tokens, variables, and arrays. Additionally, it includes code examples and explanations of Java's syntax and structure.

Uploaded by

tammanihalane
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views29 pages

Introduction to Java Programming Concepts

The document provides an introduction to Java programming, covering fundamental concepts of object-oriented programming such as classes, objects, inheritance, polymorphism, abstraction, and encapsulation. It also discusses Java's history, features, development environment, data types, tokens, variables, and arrays. Additionally, it includes code examples and explanations of Java's syntax and structure.

Uploaded by

tammanihalane
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java Programming

Introduction to JAVA
Basic concepts of object oriented programming
Object:
This is the basic unit of object oriented programming. That is both data and method that operate
on data are bundled as a unit called as object. It is a real world entity (Ex:a person, book,
tables, chairs etc…)

Class:
Class is a collection of objects or class is a collection of instance variables and [Link]
you define a class, you define a blueprint for an object. This doesn't actually define any data, but
it does define what the class name means, that is, what an object of the class will consist of
and what operations can be performed on such an object.

Abstraction:
Data abstraction refers to, providing only essential information to the outside word and hiding
their background details ie. to represent the needed information in program withoutpresenting the
details.
For example, a database system hides certain details of how data is stored and created and
maintained. Similar way, C++ classes provides different methods to the outside world without
giving internal detail about those methods and data.

Encapsulation:
Encapsulation is placing the data and the methods/fUNCTions that work on that data in the
same place. While working with procedural languages, it is not always clear which functions
work on which variables but object-oriented programming provides you framework to place the
data and the relevant functions together in the same object.

Inheritance:
One of the most useful aspects of object-oriented programming is code reusability. As the
name suggests Inheritance is the process of forming a new class from an existing class that is
from the existing class called as base class, new class is formed called as derived class.
This is a very important concept of object oriented programming since this feature helps to
reduce the code size.

Polymorphism:
The ability to use a method/function in different ways in other words giving different meaning
for method/ functions is called polymorphism. Poly refers many. That is a single
method/function functioning in many ways different upon the usage is called polymorphism.

Prepared by Dr. Mahesh Huddar Page 2


Java Programming

Java History:

Java is a general-purpose object oriented programming language developed by sun


Microsystems of USA in the year 1991. The original name of Java is Oak. Java was designed for
thedevelopment of the software for consumer electronic devices like TVs, VCRs, etc.

Introduction:Java is a general purpose programming language. We can develop two typesof


Java application. They are:
(1). Stand alone Java application.
(2). Web applets.
Stand alone Java application:Stand alone Java application are programs written inJava
to carry out certain tasks on a certain stand alone system. Executing a stand-alone Java program
contains two phases:
(a) Compiling source coded into bytecode using javac compiler.
(b) Executing the bytecodede program using Java interpreter.
Java applet: Applets are small Java program developed for Internet application. An
applet located on a distant computer can be downloaded via Internet and execute on local
computer.

Java Environment:
Java environment includes a large number of development tools and hundreds of classes
and methods. The Java development tools are part of the systems known as Java development
kit (JDK) and the classes and methods are part of the Java standard library known as Java
standard Library (JSL) also known as application program interface (API).

Prepared by Dr. Mahesh Huddar Page 3


Java Programming

Java Features:
(1) Compiled and Interpreted
(2) Architecture Neutral/Platform independent and portable
(3) Object oriented
(4) Robust and secure.
(5) Distributed.
(6) Familiar, simple and small.
(7) Multithreaded and interactive.
(8) High performance
(9) Dynamic and extendible.

1. Compiled and Interpreted


Usually a computer language is either compiled or interpreted. Java combines both these
approaches; first java compiler translates source code into bytecode instructions.
Bytecodes are not machine instructions and therefore, in the second stage, java interpreter
generates machine code that can be directly executed by the machine that is running the
java program.

2. Architecture Neutral/Platform independent and portable


The concept of Write-once-run-anywhere (known as the Platform independent) is one of
the important key feature of java language that makes java as the most powerful language.
Not even a single language is idle to this feature but java is closer to this feature. The
programs written on one platform can run on any platform provided the platform must
have the JVM.

3. Object oriented
In java everything is an Object. Java can be easily extended since it is based on the Object
[Link] is a pure object oriented language.

4. Robust and secure.


Java is a robust language; Java makes an effort to eliminate error situations by emphasizing
mainly on compile time error checking and runtime checking. Because of absence of
pointers in java we can easily achieve the security.

5. Distributed.
Java is designed for the distributed environment of the [Link] applications can open
and access remote objects on internet as easily as they can do in the local system.

6. Familiar, simple and small.


Java is designed to be easy to learn. If you understand the basic concept ofOOP

Prepared by Dr. Mahesh Huddar Page 4


Java Programming

java would be easy to master.

7. Multithreaded and interactive.


With Java's multi-threaded feature, it is possible to write programs that can do many tasks
simultaneously. This design feature allows developers to construct smoothly running
interactive applications.

8. High performance
Because of the intermediate bytecode java language provides high performance

9. Dynamic and extendible.


Java is considered to be more dynamic than C or C++ since it is designed to adapt to an
evolving environment. Java programs can carry extensive amount of run-time information that
can be used to verify and resolve accesses to objects on run-time.

Java Development kits (java software:jdk1.6): Java development kit comes with a number of
Java development tools. They are:
(1) Appletviewer: Enables to run Java applet.
(2) javac: Java compiler.
(3) java : Java interpreter.
(4) javah : Produces header files for use with native methods.
(5) javap : Java disassembler.
(6) javadoc : Creates HTML documents for Java source code file.
(7) jdb : Java debugger which helps us to find the error.

Prepared by Dr. Mahesh Huddar Page 5


Java Programming

private String name;


private int age;

// Constructor
public Student(String name, int age) {
[Link] = name;
[Link] = age;
}

// Method from interface


public void display() {
[Link]("Student Name: " + name);
[Link]("Student Age: " + age);
}
}

// (6) Main Method Class


public class MainProgram {
public static void main(String[] args) {
// Creating object of Student class
Student s1 = new Student("Rahul", 21);
[Link]();

// Using imported Helper class (Assume it exists)


[Link]();

// Program ends here


[Link]("Program execution completed.");
}
}

Prepared by Dr. Mahesh Huddar Page 7


Java Programming

Java Tokens

Constants:
Constants in Java refers to fixed value that do not change during theexecution of program. Java
supported constants are given below:

(1) Integer constants: An integer constant refers to a sequence of digits. There are three types of
integer namely decimal integer, octal integer andhexadecimal integer.
For example: 123, -321
(2) Real constants: Any real world number with a decimal point is known as real constants.
For example : 0.0064, 12e-2 etc.
(3) Single character constants: A single character constant contains a single character enclosed
with in a pair of single quotes.
For example: m = 5
(4) String constants : A string constant is a sequence of character enclosed with double quotes.
For example: “hello”, “java” etc.
(5) Backslash character constants: Java supports some backslash constants those are used in
output methods. They are :
1. \b Backspace
2. \f Form feed
3. \n New Line
4. \r Carriage return.
5. \t Horizontal tab.
6. \‟ Single quotes.
7. \” Double quotes
8. \\ Back slash

Data Types in Java:


In java, data types are classified into two catagories :

1. Primitive Data type


2. Non-Primitive Data type

Prepared by Dr. Mahesh Huddar Page 8


Java Programming

Data Type Default Value Default size


boolean False 1 bit
char '\u0000' 2 byte
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
float 0.0f 4 byte
double 0.0d 8 byte

Integers Type:
Java provides four types of Integers. They are byte, sort, Int, long. Allthese are sign, positive or
negative.
Byte:The smallest integer type is byte. This is a signed 8-bit type that has a rangefrom –128 to
127. Bytes are useful for working with stream or data from a network or [Link] are also
useful for working with raw binary data. A byte variable is declared with thekeyword “byte”.
byte b, c;
Short:Short is a signed 16-bit type. It has a range from –32767 to 32767. Thisdata type is most rarely used
specially used in 16 bit computers. Short variables are declared using the keyword short.
short a, b;
int:The most commonly used Integer type is int. It is signed 32 bit type has arange from –
2147483648 to 2147483648.
int a, b, c;
Prepared by Dr. Mahesh Huddar Page 9
Java Programming

long:Long is a 64 bit type and useful in all those occasions where Int is not enough.
The range of long is very large.
long a, b;

Floating point types:


Floating point numbers are also known as real numbers are useful when evaluating a
expression that requires fractional precision. The two floating-point data types are float and
double.

float:The float type specifies a single precision value that uses 32-bit storage.
Float keyword is used to declare a floating point variable.
float a, b;
double: Double DataTips is declared with double keyword and uses 64-bit value.

Characters:
The Java data type to store characters is char. char data type of Java usesUnicode to represent
characters. Unicode defines a fully international character set that can have all the characters of
human language. Java char is 16-bit type. The range is 0 to 65536.

Boolean:
Java has a simple type called boolean for logical values. It can have only one oftwo possible
values. They are true or false.

Key Words:
Java program is basically a collection of classes. A class is defined by a set of declaration
statements and methods containing executable statements. Most statement contains an expression
that contains the action carried out on data. The compiler recognizes the tokens for building up
the expression and statements. Smallest individual units of programs are known as tokens. Java
language includes five types of tokens. They are
(a) Reserved Keyword
(b) Identifiers
(c) Literals.
(d) Operators
(e) Separators.

(1) Reserved keyword: Java language has 60 words as reserved keywords. They implement
specific feature of the language. The keywords combined with operators and separators
according to syntax build the Java language.
(2) Identifiers: Identifiers are programmer-designed token used for naming classes methods
variable, objects, labels etc. The rules for identifiers are
Prepared by Dr. Mahesh Huddar Page 10
Java Programming

1. They can have alphabets, digits, dollar sign and underscores.


2. They must not begin with digit.
3. Uppercase and lower case letters are distinct.
4. They can be any lengths.

(3) Literals: Literals in Java are sequence of characters that represents constant values to be stored
in variables. Java language specifies five major types of Literals. They are:
1. Integer Literals.
2. Floating-point Literals.
3. Character Literals.
4. String Literals.
5. Boolean Literals.
(4) Operators: An operator is a symbol that takes one or more arguments and operates on
them to produce an result.
(5) Separators: Separators are the symbols that indicates where group of code aredivided and
arranged. Some of the operators are:

1. Parenthases()
2. Braces{ }
3. Brackets [ ]
4. Semicolon ;
5. Comma ,
6. Period .

Java character set:


The smallest unit of Java language are its character set used to write Java tokens. This character
are defined by unicode character set that tries to create character for a large number of character
worldwide.
The Unicode is a 16-bit character coding system and currently supports 34,000 defined
characters derived from 24 languages of worldwide.

Variables:
A variable is an identifier that denotes a storage location used to store a datavalue. A variable
may have different value in the different phase of the program. To declare one identifier as a
variable there are certain rules. They are:
1. They must not begin with a digit.
2. Uppercase and lowercase are distinct.
3. It should not be a keyword.
4. White space is not allowed.

Prepared by Dr. Mahesh Huddar Page 11


Java Programming

Declaring Variable: One variable should be declared before using.


The syntax is
Data-type variblaname1, variablename2, ............................ variablenameN;

Initializing a variable:A variable can be initialize in two ways. They are

(a) Initializing by Assignment statements.


(b) Initializing by Read statements.
Initializing by assignment statements:
One variable can be initialize usingassignment statements. The syntax is :
Variable-name = Value;

Initialization of this type can be done while declaration.

Initializing by read statements:Using read statements we can get the values inthe variable.

Scope of Variable: Java variable is classified into three types. They are
(a) Instance Variable
(b) Local Variable
(c) Class Variable
Instance Variable: Instance variable is created when objects are instantiated and therefore
they are associated with the object. They take different values for eachobject.
Class Variable: Class variable is global to the class and belongs to the entire set of object
that class creates. Only one memory location is created for each class variable.
Local Variable: Variable declared inside the method are known as local variables. Local
variables are also can be declared with in program blocks. Program blocks can be nested.
But the inner blocks cannot have same variable that the outer blocks arehaving.

Prepared by Dr. Mahesh Huddar Page 12


Java Programming

Arrays in Java
Arraywhich stores a fixed-size sequential collection of elements of the same type.
An array is used to store a collection of data, but it is often more useful to think of anarray as a
collection of variables of the same type.

Declaring Array Variables:

To use an array in a program, you must declare a variable to reference the array, and youmust
specify the type of array the variable can reference. Here is the syntax for declaring an array
variable:

dataType[] arrayRefVar; or dataType arrayRefVar[];

Example:

The following code snippets are examples of this syntax:

int[] myList; or int myList[];

Creating Arrays:

You can create an array by using the new operator with the following syntax:

arrayRefVar = new dataType[arraySize];

The above statement does two things:

• It creates an array using new dataType[arraySize];


• It assigns the reference of the newly created array to the variable arrayRefVar.

Declaring an array variable, creating an array, and assigning the reference of the array tothe
variable can be combined in one statement, as shown below:

dataType[] arrayRefVar = new dataType[arraySize];

Alternatively you can create arrays as follows:

dataType[] arrayRefVar = {value0, value1, ..., valuek};

Prepared by Dr. Mahesh Huddar Page 13


Java Programming

The array elements are accessed through the index. Array indices are 0-based; that is,they
start from 0 to [Link]-1.

Example:

Following statement declares an array variable, myList, creates an array of 10 elements of


double type and assigns its reference to myList:

double[] myList = new double[10];

Following picture represents array myList. Here, myList holds ten double values and the
indices are from 0 to 9.

Processing Arrays:

When processing array elements, we often use either for loop or foreach loop because allof the
elements in an array are of the same type and the size of the array is known.
Example:
Here is a complete example of showing how to create, initialize and process arrays:

// Program to demonstrate array operations


public class TestArray
{
public static void main(String[] args)
{
double[] myList = {1.9, 2.9, 3.4, 3.5};

// Print all the array elements


[Link]("Array elements:");
for (int i = 0; i < [Link]; i++)

Prepared by Dr. Mahesh Huddar Page 14


Java Programming

{
[Link](myList[i] + " ");
}

// Adding all elements


double total = 0;
for (int i = 0; i < [Link]; i++)
{
total += myList[i];
}
[Link]("Total is " + total);

// Finding the largest element


double max = myList[0];
for (int i = 1; i < [Link]; i++)
{
if (myList[i] > max)
{
max = myList[i];
}
}
[Link]("Max is " + max);
}
}

This would produce the following result:

1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5

Prepared by Dr. Mahesh Huddar Page 15


Java Programming

The foreach Loop


JDK 1.5 introduced a new for loop known as for-each loop or enhanced for loop, which enables
you to traverse the complete array sequentially without using an index variable.

Example:

The following code displays all the elements in the array myList:public
// Program to demonstrate array traversal
class TestArray
{
public static void main(String[] args)
{
double[] myList = {1.9, 2.9, 3.4, 3.5};

// Print all the array elements


for (double element : myList)
{
[Link](element);
}
}
}

This would produce the following result:

1.9
2.9
3.4
3.5

Prepared by Dr. Mahesh Huddar Page 16


Java Programming

Type Casting in Java


Sometimes, it is necessary to store a value of one data type into a variable of another data type.
This process is called Type Casting.
In simple terms:
Type Casting means converting a value from one data type into another.

Example
int x = 10; // Integer type
byte y = (byte) x; // Explicit type casting (int → byte)
Here, the integer value 10 stored in variable x is explicitly cast into a byte type and stored in variable y.

Types of Type Casting


1. Implicit Type Casting (Widening Conversion)
o Performed automatically by Java.
o Happens when a smaller data type is assigned to a larger data type.
o No data is lost.
o Example:
int a = 100;
double b = a; // int → double (automatic widening)
[Link](b); // Output: 100.0

2. Explicit Type Casting (Narrowing Conversion)


o Done manually by the programmer using a cast operator.
o Used when a larger data type is converted into a smaller data type.
o May cause data loss or precision loss.
o Example:
double a = 99.99;
int b = (int) a; // double → int (explicit narrowing)
[Link](b); // Output: 99

Prepared by Dr. Mahesh Huddar Page 17


Java Programming

Java operators:
Java operators can be categorized into the following ways:
1. Arithmetic operator
2. Relational operator
3. Logical operator
4. Assignment operator
5. Increment and Decrement operator
6. Conditional operator
7. Bitwise operator
8. Special operator

1. Arithmetic Operator
The Java arithmetic operators are:
• + : Addition
• - : Subtraction
• * : Multiplication
• / : Division
• % : Remainder

2. Relational Operator
• < : Is less than
• <= : Is less than or equal to
• > : Is greater than
• >= : Is greater than or equal to
• == : Is equal to
• != : Is not equal to

3. Logical Operators
• && : Logical AND
• || : Logical OR
• ! : Logical NOT

4. Assignment Operator
• += : Plus and assign to
• -= : Minus and assign to
• *= : Multiply and assign to
• /= : Divide and assign to
• %= : Mod and assign to
• = : Simple assign to

Prepared by Dr. Mahesh Huddar Page 18


Java Programming

5. Increment and Decrement Operator


• ++ : Increment by one (Pre/Post)
• -- : Decrement by one (Pre/Post)

6. Conditional Operator
• Known as the ternary operator.
• Syntax:
• Exp1 ? Exp2 : Exp3

7. Bitwise Operator
Bitwise operators manipulate data at the bit level and are used for testing bits.
• & : Bitwise AND
• | : Bitwise OR

8. Special Operator
• instanceof operator:
Returns true if the object on the left-hand side is an instance of the class given on the right-hand side.
Example:
• person instanceof Student
• Dot operator (.):
Used to access the instance variables or methods of a class object.

Example Programs

// Arithmetic Operations Program


class ArithmeticOp {
public static void main(String args[]) {
float a = 20.5f;
float b = 6.4f;

[Link]("a = " + a);


[Link]("b = " + b);
[Link]("a + b = " + (a + b));
}
}

// Bitwise Logic Program


class BitLogic {
public static void main(String args[]) {
String binary[] = {
"0000", "0001", "0010", "0011",

Prepared by Dr. Mahesh Huddar Page 19


Java Programming

"0100", "0101", "0110", "0111",


"1000", "1001", "1010", "1011",
"1100", "1101", "1110", "1111"
};

int a = 3;
int b = 6;

int c = a | b; // OR
int d = a & b; // AND
int e = a ^ b; // XOR
int f = (~a & b) | (a & ~b); // Equivalent to XOR

[Link]("a or b : " + binary[c]);


[Link]("a and b : " + binary[d]);
[Link]("a xor b : " + binary[e]);
[Link]("(~a&b)|(a&~b): " + binary[f]);
}
}

Prepared by Dr. Mahesh Huddar Page 20


Java Programming

Control Statements
Decision Making Statements in Java

1. Simple if Statement
The general form of a simple if statement is:
if (test_expression)
{
statement_block1;
}
statement_block2;

class SimpleIf {
public static void main(String[] args) {
int number = 10;

if (number > 0) {
[Link](number + " is positive.");
}

[Link]("Program ended.");
}
}

2. if-else Statement
The general form of an if-else statement is:
if (test_expression)
{
statement_block1;
} else
{
statement_block2;
}

class IfElse {
public static void main(String[] args) {

Prepared by Dr. Mahesh Huddar Page 21


Java Programming

int number = 7;

if (number % 2 == 0) {
[Link](number + " is even.");
} else {
[Link](number + " is odd.");
}
}
}

3. else-if Ladder
The general form of an else-if ladder is:
if (test_expression1)
{
statement_block1;
}
else if (test_expression2)
{
statement_block2;
}
else
{
statement_block3;
}

class ElseIfLadder {
public static void main(String[] args) {
int marks = 72;

if (marks >= 90) {


[Link]("Grade: A");
} else if (marks >= 75) {
[Link]("Grade: B");
} else if (marks >= 50) {
[Link]("Grade: C");
} else {
[Link]("Grade: F");
}
}
}
Prepared by Dr. Mahesh Huddar Page 22
Java Programming

4. Nested if-else Statement


The general form of a nested if-else statement is:
if (test_expression1)
{
if (test_expression2)
{
statement_block1;
}
else
{
statement_block2;
}
}
else
{
statement_block3;
}

class NestedIfElse {
public static void main(String[] args) {
int a = 25, b = 40, c = 30;

if (a > b) {
if (a > c) {
[Link]("Largest: " + a);
} else {
[Link]("Largest: " + c);
}
} else {
if (b > c) {
[Link]("Largest: " + b);
} else {
[Link]("Largest: " + c);
}
}
}
}

Prepared by Dr. Mahesh Huddar Page 23


Java Programming

5. switch Statement
The general form of a switch statement is:
switch (expression)
{
case value1:
block1;
break;

case value2:
block2;
break;

// More cases...

default:
default_block;
break;
}

class SwitchExample {
public static void main(String[] args) {
int day = 3;

switch (day) {
case 1:
[Link]("Monday");
break;
case 2:
[Link]("Tuesday");
break;
case 3:
[Link]("Wednesday");
break;
case 4:
[Link]("Thursday");
break;
case 5:
[Link]("Friday");
break;
case 6:
[Link]("Saturday");

Prepared by Dr. Mahesh Huddar Page 24


Java Programming

break;
case 7:
[Link]("Sunday");
break;
default:
[Link]("Invalid day number.");
break;
}
}
}

Prepared by Dr. Mahesh Huddar Page 25


Java Programming

Loops In Java:
In looping a sequence of statements are executed until a number of time or untilsome condition
for the loop is being satisfied. Any looping process includes following four steps:
(1) Setting an initialization for the counter.
(2) Execution of the statement in the loop
(3) Test the specified condition for the loop.
(4) Incrementing the counter.

Java includes three loops. They are:

1. While loop:
The general structure of a while loop is:

Initialization;
while (test_condition)
{
// body of the loop
}

Example: Print numbers from 1 to 5 using while loop


class WhileExample
{
public static void main(String[] args)
{
int i = 1; // Initialization

while (i <= 5) // Test condition


{
[Link]("Number: " + i);
i++; // Increment
}
}
}

Output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5

Prepared by Dr. Mahesh Huddar Page 26


Java Programming

2. Do while loop:
The general structure of a do while loop is:

Initialization;
do {
// body of the loop
} while (test_condition);

Example: Print numbers from 1 to 5 using do-while loop


class DoWhileExample
{
public static void main(String[] args)
{
int i = 1; // Initialization

do
{
[Link]("Number: " + i);
i++; // Increment
} while (i <= 5); // Test condition
}
}

Output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5

3. For loop :
The general structure of for loop is:
For ( Initialization ; Test condition ; Increment)
{
body of the loop;
}

Example: Print numbers from 1 to 5 using for loop


class ForExample
{
public static void main(String[] args)

Prepared by Dr. Mahesh Huddar Page 27


Java Programming

{
for (int i = 1; i <= 5; i++) // Initialization; condition; increment
{
[Link]("Number: " + i);
}
}
}

Output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5

More about Loops:

1. Break Statement
• The break statement is used to terminate a loop immediately.
• Control jumps out of the loop and continues with the next statement after the loop.
Example: Stop loop when number = 3
class BreakExample
{
public static void main(String[] args)
{
for (int i = 1; i <= 5; i++)
{
if (i == 3)
{
break; // exits the loop when i = 3
}
[Link]("Number: " + i);
}
[Link]("Loop ended.");
}
}

Output:

Prepared by Dr. Mahesh Huddar Page 28


Java Programming

Number: 1
Number: 2
Loop ended.

2. Continue Statement
• The continue statement is used to skip the current iteration of the loop.
• Control jumps to the next iteration of the loop without executing the remaining statements in the
current loop body.
Example: Skip printing number 3
class ContinueExample
{
public static void main(String[] args)
{
for (int i = 1; i <= 5; i++)
{
if (i == 3)
{
continue; // skips printing when i = 3
}
[Link]("Number: " + i);
}
}
}

Output:
Number: 1
Number: 2
Number: 4
Number: 5

3. Labeled Loops
• A label can be given to a loop.
• Using the label name with break or continue, we can control outer loops from inside inner
loops.

Prepared by Dr. Mahesh Huddar Page 29


Java Programming

Example: Break outer loop using label


class LabeledLoopExample
{
public static void main(String[] args)
{
outerLoop: // label for the outer loop
for (int i = 1; i <= 3; i++)
{
for (int j = 1; j <= 3; j++)
{
if (i == 2 && j == 2)
{
break outerLoop; // breaks the outer loop
}
[Link]("i = " + i + ", j = " + j);
}
}
[Link]("Loop ended.");
}
}

Output:
i = 1, j = 1
i = 1, j = 2
i = 1, j = 3
i = 2, j = 1
Loop ended.

Advantages of Java
1. Open Source
o Java is open source, so developers do not need to pay heavy license fees each year.
2. Platform Independent
o Programs written in Java can run on any platform that has a Java Virtual Machine
(JVM).
o This makes Java a “write once, run anywhere” language.
3. Rich API
o Java provides a vast collection of built-in APIs (for networking, I/O, utilities, XML
parsing, database connectivity, etc.) that developers can easily use.
4. Automatic Memory Management
o Java has a garbage collector that automatically frees unused memory, reducing

Prepared by Dr. Mahesh Huddar Page 30


Java Programming

chances of memory leaks.


5. Robust Exception Handling
o Java provides strong exception handling mechanisms, ensuring stable and error-
resistant applications.
6. Multi-Platform and Web Support
o Java supports development across multiple platforms (Windows, Linux, macOS,
Android).
o It also has built-in support for web services.
7. Dynamic Web Applications
o With technologies like JSP, Servlets, Spring, Hibernate, and frameworks, Java can be
used to build dynamic and enterprise-level web applications.
8. Object-Oriented and Modular
o Java is object-oriented, which allows developers to create modular programs and
reusable code, making projects easier to maintain and scale.
9. Multithreading Support
o Java provides built-in support for multithreading, allowing multiple tasks to run in
parallel within a program.

Prepared by Dr. Mahesh Huddar Page 31

You might also like