Java Programming Basics and Concepts
Java Programming Basics and Concepts
Overview of Java
Java is a widely used object-oriented programming language and software platform that runs
on billions of devices, including notebook computers, mobile devices, gaming consoles,
medical devices and many others. The rules and syntax of Java are based on the C and C++
languages. One major advantage of developing software with Java is its portability. Once you
have written code for a Java program on a notebook computer, it is very easy to move the
code to a mobile device. When the language was invented in 1991 by James Gosling of Sun
Microsystems (later acquired by Oracle), the primary goal was to be able to "write once, run
anywhere."
It's also important to understand that Java is much different from JavaScript.
Javascript does not need to be compiled, while Java code does need to be compiled. Also,
Javascript only runs on web browsers while Java can be run anywhere.
New and improved software development tools are coming to market at a remarkable
pace, displacing incumbent products once thought to be indispensable. In light of this
continual turnover, Java’s longevity is impressive; more than two decades after its creation,
Java is still the most popular language for application software development—developers
continue to choose it over languages such as Python, Ruby, PHP, Swift, C++, and others. As a
result, Java remains an important requirement for competing in the job market.
Working of Java
2
Java programs are written and saved in a file with extension .java. The program is compiled using javac
(Java Compiler). A class file is generated and it is independent of any platform. To execute class file on
a specific machine, Java Virtual Machine (JVM) of that machine is used.
3
Abstraction
Abstraction is the process of hiding the internal details of an application from the outer world.
Abstraction is used to describe things in simple terms. It’s used to create a boundary between the
application and the client programs. It shows only the necessary information and hides the other
irrelevant information. Abstraction is implemented using Abstraction classes and interfaces . The
problems in Abstraction are solved at design or interface level.
Objects are the building blocks of Object-Oriented Programming. An object contains some
properties and methods. We can hide them from the outer world through access modifiers. We can
provide access only for required functions and properties to the other programs. This is the general
procedure to implement abstraction in OOPS.
Abstraction can be found in practically all real-world machines.
1. Automobile is an excellent illustration of abstraction. Turning the key or pressing the start
button is how you start a car. You don't need to know how your car's engine starts or what
components it contains. The user is completely unaware of the car's internal implementation
and complicated logic.
2. Heating the food in Microwave. We press some buttons to set the timer and type of food.
Finally, we get a hot and delicious meal. The microwave internal details are hidden from us. We
have been given access to the functionality in a very simple manner.
1. Encapsulation: This is the idea of wrapping everything up about a particular thing, whether
a Checking Account or Armadillo, into a defined object with features and behaviors. Once
we do, we can ask the object itself to do what it is supposed to do, whether that is Deposit
Money or Defend Yourself. But nobody outside the object needs to worry about how it
does its jobs. We just tell it to do it and go about our day. If every object, simply minds its
own business and stays out of the business of other objects, all is good with the world.
2. Inheritance: This is the idea that we don’t have to define absolutely everything about an
object over and over again if it shares features and behaviors with other objects. We can
4
define a class for Accounts and then let our Checking Account or Savings Account inherit
all the stuff in common. Likewise, we can define a class for Animals, and let our Armadillo
inherit features like Number Of Legs and Weight as well as behaviors such as Breathe and
Sleep. We call these overarching classes parent classes, and the ones that inherit from
them, child classes. We can then inherit from the child classes and so on. But our Checking
Account is more specialized than our Accounts because we can Write A Check, which we
can’t do with a Savings Account. Our Armadillo can Roll Into A Ball, but other animals such
as a Giraffe don’t have that behavior. Since we go from more general to more specialized,
I like to say that a child is like its parents, but much more special.
3. Polymorphism: This fancy name just means that we can treat the same object as different
things depending on how we need it at different times, and we can treat groups of different
objects that share an ancestor or trait as if they were that ancestor or trait. So, we could
have a set of different Checking, Savings, and Credit Accounts and ask each to Get Balance
so we can figure out how much we have to spend on vacation this year. Or we could ask a
queue of animals to Move Quickly, and not care how the Porpoise or Eagle or Armadillo
would handle that shared behavior. I like to think that we are different things to different
people, so even if not, every Dungeon Master has a spouse to think him or her a nuisance,
we can ask any of them to organize a game for Saturday night.
class Simple{
public static void main(String args[]){
[Link]("Hello Java");
}
}
When we compile Java program using javac tool, the Java compiler
converts the source code into byte code.
5
o public keyword is an access modifier that represents visibility. It means it is visible to all.
o static is a keyword. If we declare any method as static, it is known as the static method.
The core advantage of the static method is that there is no need to create an object to
invoke the static method. The main() method is executed by the JVM, so it doesn't
require creating an object to invoke the main() method. So, it saves memory.
o void is the return type of the method. It means it doesn't return any value.
o main represents the starting point of the program.
o String[] args or String args[] is used for command line argument.
o [Link]() is used to print statement. Here, System is a class, out is an object
of the PrintStream class, println() is a method of the PrintStream class.
7
In Java language, primitive data types are the building blocks of data
manipulation. These are the most basic data types available in Java
language.
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
8
double 0.0d 8 byte
Write a Java program to compute the distance travelled on ‘n’ days, given speed of
light=18600 miles
import [Link].*;
class LightDistance
{
public static void main(String anything[])
{
long speed=186000;
//Read n from the keyboard
short n;
[Link]("Enter the number of days(n)");
Scanner kb=new Scanner([Link]);
n=[Link]();
//Compute distance
//distance=speed*n*24*60*60
long distance=speed*n*24*60*60;
[Link](distance);
}
}
}
Characters in Java
The data type char comes under the characters group that represents symbols i.e. alphabets and
numbers in a character set. The Size of a Java char is 16-bit and the range is between 0 to 65,535. Also,
the standard ASCII characters range from 0 to 127.
9
Syntax:
char variable_name = ‘variable_value’;
}
Literals in Java
Literals in Java are a synthetic representation of boolean, character, numeric, or string data.
They are a means of expressing particular values within a program. They are constant values that
directly appear in a program and can be assigned now to a variable. For example, here is an integer
variable named ‘’/count assigned as an integer value in this statement:
int count = 0;
“int count” is the integer variable, and a literal ‘0’ represents the value of zero.
Therefore, a constant value that is assigned to the variable can be called a literal.
Floating-Point Literals
Floating-point literals are expressed as exponential notations or as decimal fractions. They can
represent either a positive or negative value, but if it’s not specified, the value defaults to positive.
Floating-point literals come in these formats:
• Floating: Floating format single precision (4 bytes) end with an “f” or “F.” Example: 4f.
Floating format double precision (8 bytes) end with a “d” or “D.”
Example: 3.14d.
• Decimal: This format uses 0 through 9 and can have either a suffix or an exponent. Example:
99638.440.
• Decimal in Exponent form: The exponent form may use an optional sign, such as a "-," and
an exponent indicator, such as "e" or "E." Example: 456.5f.
3. Char Literals
Character (Char) literals are expressed as an escape sequence or a character, enclosed in single quote
marks, and always a type of character in Java. Char literals are sixteen-bit Unicode characters ranging
from 0 to 65535. Example: char ch = 077.
11
4. String Literals
String literals are sequences of characters enclosed between double quote ("") marks. These characters
can be alphanumeric, special characters, blank spaces, etc.
Examples: "John", "2468", "\n", etc.
5. Boolean Literals
Boolean literals have only two values and so are divided into two literals:
• True represents a real boolean value
• False represents a false boolean value
So, Boolean literals represent the logical value of either true or false. These values aren't case-sensitive
and are equally valid if rendered in uppercase or lowercase mode. Boolean literals can also use the
values of “0” and “1.”
Examples:
boolean b = true;
boolean d = false;
6. Null Literals
Null literals represent a null value and refer to no object. Nulls are typically used as a marker to indicate
that a reference type object isn’t available. They often describe an uninitialized state in the program.
It is a mistake to try to dereference a null value. Example: Patient age = NULL;
Remember, not everyone divides literals in Java into these six types. Alternative classifications split
literals into as few as four types (Integer, Character, Boolean, and String) or as many as ten (Integer,
Real, Backslash, Character, String, Floating-Point, Boolean, NULL, Class, and Invalid).
Variables in Java
A variable is a container which holds the value while the Java program is executed. A variable is
assigned with a data type. Variable is a name of memory location. There are three types of variables in
java: local, instance and static. A variable is the name of a reserved area allocated in memory. In other
words, it is a name of the memory location. It is a combination of "vary + able" which means its value
can be changed.
12
Declaration, Initialization and Assignment in Java
Declaration: Declaration is when you declare a variable with a name, and a variable can be declared
only once.
Example: int x;, String myName;, Boolean myCondition;
Initialization: Initialization is when we put a value in a variable, this happens while we declare a
variable.
Example: int x = 7;, String myName = "Emi";, Boolean myCondition = false;
Assignment: Assignment is when we already declared or initialized a variable, and we are changing
the value. You can change value of the variable as many time you want or you need.
Example:
int x = 7; x = 12; .......We just changed the value.
String myName = "Emi"; myName = "John" .......We just changed the value.
Boolean myCondition = false; myCondition = true; .......We just changed the value.
Note: In memory will be saved the last value that we put.
}
}
13
Block Scope
If a variable is defined/declared in some block of code, then it exists until the end of that block of code.
Typically, such variables exist between the curly braces in which they are defined. Very often block
scope could be a loop variable. A variable that is declared in a for loop condition is not accessible
outside the loop, unless you defined it beforehand.
14
Widening Type Casting
Converting a lower data type into a higher one is called widening type casting. It is also known
as implicit conversion or casting down. It is done automatically. It is safe because there is no chance to
lose data. It takes place when:
o Both data types must be compatible with each other.
o The target type must be larger than the source type.
byte -> short -> char -> int -> long -> float -> double
For example, the conversion between numeric data type to char or Boolean is not done automatically.
Also, the char and Boolean data types are not compatible with each other.
}
}
15
Automatic Type promotions in Java
Type promotion is a common occurrence in Java programming, which can be achieved
automatically with primitive data types through the use of autotype promotion. It is also referred to as
automatic data type promotion. Below is a diagrammatic illustration of possible type promotions:
In general, the largest data type in an expression is the one that determines the size of the result of that
expression; if you multiply a float and a double, the result will be double; if you add an int and a long,
the result will be long. For example, examine the following expression:
byte a = 40;
byte b = 50;
byte c = 100;
int d = a * b / c;
The result of the intermediate term a*b easily exceeds the range of either of its byte operands. To
handle this kind of problem, Java automatically promotes each byte, short, or char operand to int when
evaluating an expression. This means that the subexpression a*b is performed using integers — not
bytes. Thus, 2,000, the result of the intermediate expression, 50 * 40, is legal even though a and b are
both specified as type byte.
As useful as the automatic promotions are, they can cause confusing compile-time errors. For example,
this seemingly correct code causes a problem:
byte b = 50;
b = b * 2; // Error! Cannot assign an int to a byte!
The code is attempting to store 50 * 2, a perfectly valid byte value, back into a byte variable. However,
because the operands were automatically promoted to int when the expression was evaluated, the
16
result has also been promoted to int. Thus, the result of the expression is now of type int, which cannot
be assigned to a byte without the use of a cast. This is true even if, as in this particular case, the value
being assigned would still fit in the target type.
In cases where you understand the consequences of overflow, you should use an explicit cast, such as
byte b = 50;
b = (byte)(b * 2);
Arrays in Java
An array is a collection of similar type of elements which has contiguous memory location. Java
array is an object which contains elements of a similar data type. Additionally, the elements of an array
are stored in a contiguous memory location. It is a data structure where we store similar elements. We
can store only a fixed set of elements in a Java array. Array in Java is index-based, the first element of
the array is stored at the 0th index, 2nd element is stored on 1st index and so on. Unlike C/C++, we can
get the length of the array using the length member.
In Java, array is an object of a dynamically generated class. Java array inherits the Object class,
and implements the Serializable as well as Cloneable interfaces. We can store primitive values or
17
objects in an array in Java. Like C/C++, we can also create single dimensional or multidimensional arrays
in Java. Moreover, Java provides the feature of anonymous arrays which is not available in C/C++.
Advantages
o Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.
o Random access: We can get any data located at an index position.
Disadvantages
o Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its size at
runtime. To solve this problem, collection framework is used in Java which grows automatically.
Types of Array in java
There are two types of array.
o Single Dimensional Array
o Multidimensional Array
We can declare, instantiate and initialize the java array together by:
int a[]={33,3,4,5};//declaration, instantiation and initialization
18
Multidimensional Arrays in Java
A multidimensional array is an array of arrays. Each element of a multidimensional array is an
array itself. For example,
Here, we have created a multidimensional array named a. It is a 2-dimensional array, that can hold a
maximum of 12 elements. Java uses zero-based indexing, that is, indexing of arrays in Java starts with
0 and not 1.
Let's take another example of the multidimensional array. This time we will be creating a 3-dimensional
array. For example,
Here, data is a 3d array that can hold a maximum of 24 (3*4*2) elements of type String.
int[][] a = {
{1, 2, 3},
{4, 5, 6, 9},
{7},
Let's see how we can use a 3d array in Java. We can initialize a 3d array similar to the 2d array. For
example,
// test is a 3d array
int[][][] test = {
{
{1, -2, 3},
{2, 3, 4}
},
{
{-4, -5, 6, 9},
{1},
{2, 3}
}
};
Basically, a 3d array is an array of 2d arrays. The rows of a 3d array can also vary in length just like in a
2d array.
19
public static void main(String[] any)
{
int[][][] t=new int[3][4][5];
for(int i=0;i<3;i++)
{
for(int j=0;j<4;j++)
{
for(int k=0;k<5;k++)
{
t[i][j][k]=i*j*k;
[Link](t[i][j][k]+" ");
}
[Link]();
}
[Link]();
}
}
}
arr[1]=new int[2];
20
arr[1][0]=0;
arr[1][1]=1;
arr[2]=new int[5];
arr[2][0]=1;
arr[2][1]=5;
arr[2][2]=8;
arr[2][3]=7;
arr[2][4]=6;
arr[3]=new int[1];
arr[3][0]=3;
}
}
21
Operators in Java
Java provides many types of operators which can be used according to the need. They are classified
based on the functionality they provide. In this article, we will learn about Java Operators and learn all
their types. Operators in Java are the symbols used for performing specific operations in Java.
Operators make tasks like addition, multiplication, etc which look easy although the implementation
of these tasks is quite complex.
Types of Operators in Java
There are multiple types of operators in Java all are mentioned below:
1. Arithmetic Operators
2. Unary Operators
3. Assignment Operator
4. Relational Operators
5. Logical Operators
6. Ternary Operator
7. Bitwise Operators
8. Shift Operators
9. instance of operator
1. Arithmetic Operators
They are used to perform simple arithmetic operations on primitive data types.
• * : Multiplication
• / : Division
• % : Modulo
• + : Addition
• – : Subtraction
Example:
// Drive Class
class GFG {
// Main Function
public static void main (String[] args) {
// Arithmetic operators
int a = 10;
int b = 3;
22
}
}
Output
a + b = 13
a-b=7
a * b = 30
a/b=3
a%b=1
2. Unary Operators
Unary operators need only one operand. They are used to increment, decrement, or negate a value.
• – : Unary minus, used for negating the values.
• + : Unary plus indicates the positive value (numbers are positive without this, however). It
performs an automatic conversion to int when the type of its operand is the byte, char, or
short. This is called unary numeric promotion.
• ++ : Increment operator, used for incrementing the value by 1. There are two varieties of
increment operators.
• Post-Increment: Value is first used for computing the result and then
incremented.
• Pre-Increment: Value is incremented first, and then the result is computed.
• – – : Decrement operator, used for decrementing the value by 1. There are two varieties of
decrement operators.
• Post-decrement: Value is first used for computing the result and then
decremented.
• Pre-Decrement: The value is decremented first, and then the result is computed.
• ! : Logical not operator, used for inverting a boolean value.
Example:
// Driver Class
class GFG {
// main function
public static void main(String[] args)
{
// Interger declared
int a = 10;
int b = 10;
23
[Link]("Preincrement : " + (++a));
Output
Postincrement : 10
Preincrement : 12
Postdecrement : 10
Predecrement : 8
3. Assignment Operator
‘=’ Assignment operator is used to assign a value to any variable. It has right-to-left associativity, i.e.
value given on the right-hand side of the operator is assigned to the variable on the left, and therefore
right-hand side value must be declared before using it or should be a constant.
The general format of the assignment operator is:
variable = value;
In many cases, the assignment operator can be combined with other operators to build a shorter
version of the statement called a Compound Statement. For example, instead of a = a+5, we can write
a += 5.
• +=, for adding the left operand with the right operand and then assigning it to the variable
on the left.
• -=, for subtracting the right operand from the left operand and then assigning it to the
variable on the left.
• *=, for multiplying the left operand with the right operand and then assigning it to the
variable on the left.
• /=, for dividing the left operand by the right operand and then assigning it to the variable
on the left.
• %=, for assigning the modulo of the left operand by the right operand and then assigning it
to the variable on the left.
Example:
// Driver Class
class GFG {
// Main Function
public static void main(String[] args)
{
24
// Assignment operators
int f = 7;
[Link]("f += 3: " + (f += 3));
[Link]("f -= 2: " + (f -= 2));
[Link]("f *= 4: " + (f *= 4));
[Link]("f /= 3: " + (f /= 3));
[Link]("f %= 2: " + (f %= 2));
[Link]("f &= 0b1010: " + (f &= 0b1010));
[Link]("f |= 0b1100: " + (f |= 0b1100));
[Link]("f ^= 0b1010: " + (f ^= 0b1010));
[Link]("f <<= 2: " + (f <<= 2));
[Link]("f >>= 1: " + (f >>= 1));
[Link]("f >>>= 1: " + (f >>>= 1));
}
}
Output
f += 3: 10
f -= 2: 8
f *= 4: 32
f /= 3: 10
f %= 2: 0
f &= 0b1010: 0
f |= 0b1100: 12
f ^= 0b1010: 6
f <<= 2: 24
f >>= 1: 12
f >>>= 1: 6
4. Relational Operators
These operators are used to check for relations like equality, greater than, and less than. They return
boolean results after the comparison and are extensively used in looping statements as well as
conditional if-else statements. The general format is,
variable relation_operator value
25
Example:
// Driver Class
class GFG {
// main function
public static void main(String[] args)
{
// Comparison operators
int a = 10;
int b = 3;
int c = 5;
Output
a > b: true
a < b: false
a >= b: true
a <= b: false
a == c: false
a != c: true
5. Logical Operators
These operators are used to perform “logical AND” and “logical OR” operations, i.e., a function similar
to AND gate and OR gate in digital electronics. One thing to keep in mind is the second condition is not
evaluated if the first one is false, i.e., it has a short-circuiting effect. Used extensively to test for several
conditions for making a decision. Java also has “Logical NOT”, which returns true when the condition is
false and vice-versa
Conditional operators are:
• &&, Logical AND: returns true when both conditions are true.
• ||, Logical OR: returns true if at least one condition is true.
• !, Logical NOT: returns true when a condition is false and vice-versa
Example:
26
import [Link].*;
// Driver Class
class GFG {
// Main Function
public static void main (String[] args) {
// Logical operators
boolean x = true;
boolean y = false;
Output
x && y: false
x || y: true
!x: false
6. Ternary operator
The ternary operator is a shorthand version of the if-else statement. It has three operands and hence
the name Ternary.
The general format is:
condition ? if true : if false
The above statement means that if the condition evaluates to true, then execute the statements after
the ‘?’ else execute the statements after the ‘:’.
Example:
Output
Max of three numbers = 30
27
7. Bitwise Operators
These operators are used to perform the manipulation of individual bits of a number. They can be used
with any of the integer types. They are used when performing update and query operations of the
Binary indexed trees.
• &, Bitwise AND operator: returns bit by bit AND of input values.
• |, Bitwise OR operator: returns bit by bit OR of input values.
• ^, Bitwise XOR operator: returns bit-by-bit XOR of input values.
• ~, Bitwise Complement Operator: This is a unary operator which returns the one’s
complement representation of the input value, i.e., with all bits inverted.
// Driver class
class GFG {
// main function
public static void main(String[] args)
{
// Bitwise operators
int d = 0b1010;
int e = 0b1100;
[Link]("d & e: " + (d & e));
[Link]("d | e: " + (d | e));
[Link]("d ^ e: " + (d ^ e));
[Link]("~d: " + (~d));
[Link]("d << 2: " + (d << 2));
[Link]("e >> 1: " + (e >> 1));
[Link]("e >>> 1: " + (e >>> 1));
}
}
Output
d & e: 8
d | e: 14
d ^ e: 6
~d: -11
d << 2: 40
e >> 1: 6
e >>> 1: 6
8. Shift Operators
These operators are used to shift the bits of a number left or right, thereby multiplying or dividing the
number by two, respectively. They can be used when we have to multiply or divide a number by two.
General format-
number shift_op number_of_places_to_shift;
28
• <<, Left shift operator: shifts the bits of the number to the left and fills 0 on voids left as a
result. Similar effect as multiplying the number with some power of two.
• >>, Signed Right shift operator: shifts the bits of the number to the right and fills 0 on voids
left as a result. The leftmost bit depends on the sign of the initial number. Similar effect to
dividing the number with some power of two.
• >>>, Unsigned Right shift operator: shifts the bits of the number to the right and fills 0 on
voids left as a result. The leftmost bit is set to 0.
// Driver Class
class GFG {
// main function
public static void main(String[] args)
{
int a = 10;
Output
a<<1 : 20
a>>1 : 5
29
Some more example programs on Java operators:
[Link](b);
}
}
int i=-1;
int res1=i>>24;
int res2=i>>>24;
[Link](res1);
[Link](res2);
}
}
31
Java's "&&" Operator
The "&&" operator is used for "AND" operations. It tests if each the left-hand side and the proper-hand
side of the operator are authentic. If both operands are authentic, then the expression is genuine.
Otherwise, the expression is fake. One of the primary blessings of the use of the "&&" operator is that
it is able to prevent the assessment of pointless code. For example, if we've an expression like this: "A
&& B", and "A" is false, then there's no need to assess "B". This can improve the efficiency of the
program and keep execution time.
Java's "||" Operator
The "||" operator is used for "OR" operations. It checks if either the left-hand side or the right-hand
side of the operator is true. If either operand is true, then the expression is true. Otherwise, the
expression is false. Like the "&&" operator, the "||" operator can also prevent the evaluation of
unnecessary code. For example, if we have an expression like this: "A || B", and "A" is true, then there
is no need to evaluate "B". This can improve the efficiency of the program and save execution time.
Decision making in Java executes a particular segment of code based on the result of a boolean
[Link] is important because conditions define the flow of programs and the output of a particular
[Link] decision making principles in Java chiefly consist of if else statements, continue, break
and switch statements. It decides the flow of the program control during the execution of the program.
1. If Statement in Java
Java if statement is the simplest decision making statement. It encompasses a boolean condition
followed by a scope of code which is executed only when the condition evaluates to true. However if
there are no curly braces to limit the scope of sentences to be executed if the condition evaluates to
true, then only the first line is executed.
Syntax:
if(condition)
{
//code to be executed
}
32
2. if else statement in Java
This pair of keywords is used to divide a program to be executed into two parts, one being the code to
be executed if the condition evaluates to true and the other one to be executed if the value is false.
However if no curly braces are given the first statement after the if or else keyword is executed.
if(condition)
{
//code to be executed if the condition is true
}
else
{
//code to be executed if the condition is false
}
switch(expression)
{
case <value1>:
//code to be executed
break;
case <value2>:
//code to be executed
break;
default:
//code to be defaultly executed
}
35
1. Initialization: It is the initial condition which is executed once when the loop starts. Here, we
can initialize the variable, or we can use an already initialized variable. It is an optional
condition.
2. Condition: It is the second condition which is executed each time to test the condition of the
loop. It continues execution until the condition is false. It must return boolean value either true
or false. It is an optional condition.
3. Increment/Decrement: It increments or decrements the variable value. It is an optional
condition.
4. Statement: The statement of the loop is executed each time until the second condition is false.
Syntax:
for(initialization; condition; increment/decrement){
//statement or code to be executed
}
Introduction The Java for loop is a control The Java while loop is a The Java do while loop is
flow statement that iterates a control flow statement a control flow statement
part of the programs multiple that executes a part of that executes a part of
times. the programs the programs at least
repeatedly on the basis once and the further
of given boolean execution depends upon
condition. the given boolean
condition.
36
When to use If the number of iteration is If the number of If the number of iteration
fixed, it is recommended to iteration is not fixed, it is is not fixed and you must
use for loop. recommended to use have to execute the loop
while loop. at least once, it is
recommended to use the
do-while loop.
37
Labelled break and continue in Java
In Java, we can label the loops and give them names. These named or labeled loops help in the
case of nested loops when we want to break or continue a specific loop out of those multiple nested
loops. The labeled blocks in Java are logically similar to goto statements in C/C++.
Syntax
A label is any valid identifier followed by a colon. For example, in the following code, we are creating
two labeled statements:
outer_loop:
for (int i = 0; i < [Link]; i++) {
inner_loop:
for (int j = 0; j < [Link]; j++) {
//...
}
//...
}
In the above example, we have two loops, and we have labeled them as outer_loop and inner_loop.
This is helpful when we want to terminate the outer loop from a condition written in the inner loop.
class DownCounter
{
public static void main(String args[])
{
for(int i=10;i>=1;i--)
[Link](i);
[Link]("Happy New Year");
}
}
38
public static void main(String args[])
{
int n=5;
for(int i=0;i<n;i++)
{
for(int j=0;j<=i;j++)
{
[Link]("* ");
}
[Link]();
}
}
}
Java program for array traversal using enhanced for without indexing
class ForArrays
{
int[] a={12,11,9,10,14};
for(int num:a)
[Link](num);
39
}
}
LAB COMPONENT
1. Develop a JAVA program to add TWO matrices of suitable order N (The value of N should be read
from command line arguments).
import [Link].*;
class Matrix
{
public static void readMatrix(int[][] A,int N)
{
Scanner kb=new Scanner([Link]);
for(int i=0;i<=N-1;i++)
{
for(int j=0;j<=N-1;j++)
{
A[i][j]=[Link]();
}
}
}
public static void addMatrix(int[][] A, int[][] B, int[][] C,int
N)
{
for(int i=0;i<=N-1;i++)
{
40
for(int j=0;j<=N-1;j++)
{
C[i][j]=A[i][j]+B[i][j];
}
}
}
public static void printMatrix(int[][] A,int N)
{
for(int i=0;i<=N-1;i++)
{
for(int j=0;j<=N-1;j++)
{
[Link](A[i][j]+" ");
}
[Link]();
}
}
41