Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
16 views

java notes

Uploaded by

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

java notes

Uploaded by

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

First Java Program | Hello World Example

In this section, we will learn how to write the simple program of Java. We can write a simple hello world
Java program easily after installing the JDK.
For creating a program it is necessary to create a class that contains the main() method (entry point of the
program). Before moving forward in this section, let's understand the requirement first.
class Simple
{
public static void main(String args[])
{
System.out.println("Hello Java");
}
}
Parameters used in First Java Program
o class keyword is used to declare a class in Java.
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 does not 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 does not return any value.
o The main() method represents the starting point of the program.
o String[] args or String args[] is used for command line argument. We will discuss it in coming
section.
o System.out.println() is used to print statement on the console. Here, System is a class, out is an
object of the PrintStream class, println() is a method of the PrintStream class. We will discuss the
internal working of System.out.println() statement in the coming section.
Let's see the different codes to write the main method.
public static void main(String[] args)
public static void main(String []args)
public static void main(String args[])
Variables
A variable is a container which holds the value while the program is executed. A variable is assigned
with a data type.
Variable is a name of memory location. There are three types of variables: local, instance and static.
There are two types of data types:
primitive and non-primitive.
Variable
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.
Types of Variables
There are three types of variables:
o local variable
o instance variable
o static variable
1) Local Variable
A variable declared inside the body of the method is called local variable. You can use this variable only
within that method and the other methods in the class aren't even aware that the variable exists.
A local variable cannot be defined with "static" keyword.
2) Instance Variable
A variable declared inside the class but outside the body of the method, is called an instance variable. It is
not declared as static.
It is called an instance variable because its value is instance-specific and is not shared among instances.
3) Static variable
A variable that is declared as static is called a static variable. It cannot be local. You can create a single
copy of the static variable and share it among all the instances of the class. Memory allocation for static
variables happens only once when the class is loaded in the memory.
Example to understand the types of variables
public class A
{
static int m=100;//static variable
void method()
{
int n=90;//local variable
}
public static void main(String args[])
{
int data=50;//instance variable
}
}//end of class
Variable Example: Add Two Numbers
public class Simple
{
public static void main(String[] args)
{
int a=10;
int b=10;
int c=a+b;
System.out.println(c);
}
}
Data Types
Data types specify the different sizes and values that can be stored in the variable. There are two types of
data types in Java:
1. Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float
and double.
2. Non-primitive data types: The non-primitive data types include Classes, Interfaces, and Arrays.
Primitive data types:
1. boolean data type
2. byte data type
3. char data type
4. short data type
5. int data type
6. long data type
7. float data type
8. double data type
Boolean Data Type
In Java, the boolean data type represents a single bit of information with two possible
states: true or false. It is used to store the result of logical expressions or conditions. Unlike other
primitive data types like int or double, boolean does not have a specific size or range. It is typically
implemented as a single bit, although the exact implementation may vary across platforms.
Example:
1. Boolean a = false;
2. Boolean b = true;
One key feature of the boolean data type is its use in controlling program flow. It is commonly employed
in conditional statements such as if, while, and for loops to determine the execution path based on the
evaluation of a boolean expression. For instance, an if statement executes a block of code if the boolean
expression evaluates to true, and skips it if the expression is false.
Byte Data Type
The byte data type in Java is a primitive data type that represents an 8-bit signed two's complement
integer. It has a range of values from -128 to 127. Its default value is 0. The byte data type is commonly
used when working with raw binary data or when memory conservation is a concern, as it occupies less
memory than larger integer types like int or long.
Example:
byte a = 10, byte b = -20
One common use of the byte data type is in reading and writing binary data, such as files or network
streams. Since binary data is often represented using bytes, the byte data type provides a convenient way
to work with such data. Additionally, the byte data type is sometimes used in performance-critical
applications where memory usage needs to be minimized.
Short Data Type
The short data type in Java is a primitive data type that represents a 16-bit signed two's complement
integer. It has a range of values from -32,768 to 32,767. Similar to the byte data type, short is used when
memory conservation is a concern, but more precision than byte is required. Its default value is 0.
Example:
short s = 10000, short r = -5000
In Java, short variables are declared using the short keyword. For example, short myShort =
1000; declares a short variable named myShort and initializes it with the value 1000. As with
the byte data type, short variables must be explicitly cast when used in expressions with larger integer
types to avoid loss of precision.
Int Data Type
The int data type in Java is a primitive data type that represents a 32-bit signed two's complement integer.
It has a range of values from -2,147,483,648 to 2,147,483,647. The int data type is one of the most
commonly used data types in Java and is typically used to store whole numbers without decimal points.
Its default value is 0.
Example:
int a = 100000, int b = -200000
In Java, int variables are declared using the int keyword. For example, int myInt = 100; declares an int
variable named myInt and initializes it with the value 100. int variables can be used in mathematical
expressions, assigned to other int variables, and used in conditional statements.
Long Data Type
The long data type in Java is a primitive data type that represents a 64-bit signed two's complement
integer. It has a wider range of values than int, ranging from -9,223,372,036,854,775,808 to
9,223,372,036,854,775,807. Its default value is 0.0F. The long data type is used when int is not large
enough to hold the desired value, or when a larger range of integer values is needed.
Example:
long a = 100000L, long b = -200000L
The long data type is commonly used in applications where large integer values are required, such as in
scientific computations, financial applications, and systems programming. It provides greater precision
and a larger range than int, making it suitable for scenarios where int is insufficient.
Float Data Type
The float data type in Java is a primitive data type that represents single-precision 32-bit IEEE 754
floating-point numbers. It can represent a wide range of decimal values, but it is not suitable for precise
values such as currency. The float data type is useful for applications where a higher range of values is
needed, and precision is not critical.
Example:
float f1 = 234.5f
One of the key characteristics of the float data type is its ability to represent a wide range of values, both
positive and negative, including very small and very large values. However, due to its limited precision
(approximately 6-7 significant decimal digits), it is not suitable for applications where exact decimal
values are required.
Double Data Type
The double data type in Java is a primitive data type that represents double-precision 64-bit IEEE 754
floating-point numbers. Its default value is 0.0d. It provides a wider range of values and greater precision
compared to the float data type, making it suitable for applications where accurate representation of
decimal values is required.
Example:
double d1 = 12.3
One of the key advantages of the double data type is its ability to represent a wider range of values with
greater precision compared to float. It can accurately represent values with up to approximately 15-16
significant decimal digits, making it suitable for applications that require high precision, such as financial
calculations, scientific computations, and graphics programming.
Char Data Type
The char data type in Java is a primitive data type that represents a single 16-bit Unicode character. It can
store any character from the Unicode character set, that allows Java to support internationalization and
representation of characters from various languages and writing systems.
Example:
char letterA = 'A'
The char data type is commonly used to represent characters, such as letters, digits, and symbols, in Java
programs. It can also be used to perform arithmetic operations, as the Unicode values of characters can be
treated as integers. For example, you can perform addition or subtraction operations on char variables to
manipulate their Unicode values.
Non-Primitive Data Types
In Java, non-primitive data types, also known as reference data types, are used to store complex objects
rather than simple values. Unlike primitive data types that store the actual values, reference data types
store references or memory addresses that point to the location of the object in memory. This distinction
is important because it affects how these data types are stored, passed, and manipulated in Java programs.
Class
One common non-primitive data type in Java is the class. Classes are used to create objects, which are
instances of the class. A class defines the properties and behaviors of objects, including variables (fields)
and methods. For example, you might create a Person class to represent a person, with variables for the
person's name, age, and address, and methods to set and get these values.
Interface
Interfaces are another important non-primitive data type in Java. An interface defines a contract for what
a class implementing the interface must provide, without specifying how it should be implemented.
Interfaces are used to achieve abstraction and multiple inheritance in Java, allowing classes to be more
flexible and reusable.
Arrays
Arrays are a fundamental non-primitive data type in Java that allow you to store multiple values of the
same type in a single variable. Arrays have a fixed size, which is specified when the array is created, and
can be accessed using an index. Arrays are commonly used to store lists of values or to represent matrices
and other multi-dimensional data structures.
Enum
Java also includes other non-primitive data types, such as enums and collections. Enums are used to
define a set of named constants, providing a way to represent a fixed set of values. Collections are a
framework of classes and interfaces that provide dynamic data structures such as lists, sets, and maps,
which can grow or shrink in size as needed.
Overall, non-primitive data types in Java are essential for creating complex and flexible programs. They
allow you to create and manipulate objects, define relationships between objects, and represent complex
data structures. By understanding how to use non-primitive data types effectively, you can write more
efficient and maintainable Java code.
Operators in Java
Operator is a symbol that is used to perform operations. For example: +, -, *, / etc.
There are many types of operators which are given below:
o Unary Operator,
o Arithmetic Operator,
o Shift Operator,
o Relational Operator,
o Bitwise Operator,
o Logical Operator,
o Ternary Operator and
o Assignment Operator.
Unary Operator
The unary operators require only one operand. Unary operators are used to perform various operations
i.e.:
o incrementing/decrementing a value by one
o negating an expression
o inverting the value of a boolean
Unary Operator Example: ++ and --
public class OperatorExample
{
public static void main(String args[])
{
int x=10;
System.out.println(x++);//10 (11)
System.out.println(++x);//12
System.out.println(x--);//12 (11)
System.out.println(--x);//10
}
}
Unary Operator Example: ~ and !
public class OperatorExample
{
public static void main(String args[])
{
int a=10;
int b=-10;
boolean c=true;
boolean d=false;
System.out.println(~a);//-11 (minus of total positive value which starts from 0)
System.out.println(~b);//9 (positive of total minus, positive starts from 0)
System.out.println(!c);//false (opposite of boolean value)
System.out.println(!d);//true
}
}
Arithmetic Operators
Arithmetic operators are used to perform addition, subtraction, multiplication, and division. They act as
basic mathematical operations.
Arithmetic Operator Example
public class OperatorExample
{
public static void main(String args[])
{
int a=10;
int b=5;
System.out.println(a+b);//15
System.out.println(a-b);//5
System.out.println(a*b);//50
System.out.println(a/b);//2
System.out.println(a%b);//0
}
}
Left Shift Operator
The left shift operator << is used to shift all of the bits in a value to the left side of a specified number of
times.
Left Shift Operator Example
public class OperatorExample
{
public static void main(String args[])
{
System.out.println(10<<2);//10*2^2=10*4=40
System.out.println(10<<3);//10*2^3=10*8=80
System.out.println(20<<2);//20*2^2=20*4=80
System.out.println(15<<4);//15*2^4=15*16=240
}
}
Right Shift Operator
The right shift operator >> is used to move the value of the left operand to right by the number of bits
specified by the right operand.
Right Shift Operator Example
public OperatorExample
{
public static void main(String args[])
{
System.out.println(10>>2);//10/2^2=10/4=2
System.out.println(20>>2);//20/2^2=20/4=5
System.out.println(20>>3);//20/2^3=20/8=2
}
}
AND Operator Example: Logical && and Bitwise &
The logical && operator doesn't check the second condition if the first condition is false. It checks the
second condition only if the first one is true.
The bitwise & operator always checks both conditions whether first condition is true or false.
public class OperatorExample
{
public static void main(String args[])
{
int a=10;
int b=5;
int c=20;
System.out.println(a<b&&a<c);//false && true = false
System.out.println(a<b&a<c);//false & true = false
}
}
Ternary Operator
Ternary operator is used as one line replacement for if-then-else statement and used a lot in Java
programming. It is the only conditional operator which takes three operands.
Ternary Operator Example
public class OperatorExample
{
public static void main(String args[])
{
int a=2;
int b=5;
int min=(a<b)?a:b;
System.out.println(min);
}
}
Assignment Operator
Assignment operator is one of the most common operators. It is used to assign the value on its right to the
operand on its left.
Assignment Operator Example
public class OperatorExample
{
public static void main(String args[])
{
int a=10;
int b=20;
a+=4;//a=a+4 (a=10+4)
b-=4;//b=b-4 (b=20-4)
System.out.println(a);
System.out.println(b);
}
}
Keywords
Java keywords are also known as reserved words. Keywords are particular words that act as a key to a
code. These are predefined words by Java so they cannot be used as a variable or object name or class
name.
List of Java Keywords
A list of Java keywords or reserved words are given below:
1. abstract: Java abstract keyword is used to declare an abstract class. An abstract class can provide
the implementation of the interface. It can have abstract and non-abstract methods.
2. boolean: Java boolean keyword is used to declare a variable as a boolean type. It can hold True
and False values only.
3. break: Java break keyword is used to break the loop or switch statement. It breaks the current
flow of the program at specified conditions.
4. byte: Java byte keyword is used to declare a variable that can hold 8-bit data values.
5. case: Java case keyword is used with the switch statements to mark blocks of text.
6. catch: Java catch keyword is used to catch the exceptions generated by try statements. It must be
used after the try block only.
7. char: Java char keyword is used to declare a variable that can hold unsigned 16-bit Unicode
characters
8. class: Java class keyword is used to declare a class.
9. continue: Java continue keyword is used to continue the loop. It continues the current flow of the
program and skips the remaining code at the specified condition.
10. default: Java default keyword is used to specify the default block of code in a switch statement.
11. do: Java do keyword is used in the control statement to declare a loop. It can iterate a part of the
program several times.
12. double: Java double keyword is used to declare a variable that can hold 64-bit floating-point
number.
13. else: Java else keyword is used to indicate the alternative branches in an if statement.
14. enum: Java enum keyword is used to define a fixed set of constants. Enum constructors are
always private or default.
15. extends: Java extends keyword is used to indicate that a class is derived from another class or
interface.
16. final: Java final keyword is used to indicate that a variable holds a constant value. It is used with
a variable. It is used to restrict the user from updating the value of the variable.
17. finally: Java finally keyword indicates a block of code in a try-catch structure. This block is
always executed whether an exception is handled or not.
18. float: Java float keyword is used to declare a variable that can hold a 32-bit floating-point
number.
19. for: Java for keyword is used to start a for loop. It is used to execute a set of
instructions/functions repeatedly when some condition becomes true. If the number of iteration is
fixed, it is recommended to use for loop.
20. if: Java if keyword tests the condition. It executes the if block if the condition is true.
21. implements: Java implements keyword is used to implement an interface.
22. import: Java import keyword makes classes and interfaces available and accessible to the current
source code.
23. instanceof: Java instanceof keyword is used to test whether the object is an instance of the
specified class or implements an interface.
24. int: Java int keyword is used to declare a variable that can hold a 32-bit signed integer.
25. interface: Java interface keyword is used to declare an interface. It can have only abstract
methods.
26. long: Java long keyword is used to declare a variable that can hold a 64-bit integer.
27. native: Java native keyword is used to specify that a method is implemented in native code using
JNI (Java Native Interface).
28. new: Java new keyword is used to create new objects.
29. null: Java null keyword is used to indicate that a reference does not refer to anything. It removes
the garbage value.
30. package: Java package keyword is used to declare a Java package that includes the classes.
31. private: Java private keyword is an access modifier. It is used to indicate that a method or
variable may be accessed only in the class in which it is declared.
32. protected: Java protected keyword is an access modifier. It can be accessible within the package
and outside the package but through inheritance only. It can't be applied with the class.
33. public: Java public keyword is an access modifier. It is used to indicate that an item is accessible
anywhere. It has the widest scope among all other modifiers.
34. return: Java return keyword is used to return from a method when its execution is complete.
35. short: Java short keyword is used to declare a variable that can hold a 16-bit integer.
36. static: Java static keyword is used to indicate that a variable or method is a class method. The
static keyword in Java is mainly used for memory management.
37. strictfp: Java strictfp is used to restrict the floating-point calculations to ensure portability.
38. super: Java super keyword is a reference variable that is used to refer to parent class objects. It
can be used to invoke the immediate parent class method.
39. switch: The Java switch keyword contains a switch statement that executes code based on test
value. The switch statement tests the equality of a variable against multiple values.
40. synchronized: Java synchronized keyword is used to specify the critical sections or methods in
multithreaded code.
41. this: Java this keyword can be used to refer the current object in a method or constructor.
42. throw: The Java throw keyword is used to explicitly throw an exception. The throw keyword is
mainly used to throw custom exceptions. It is followed by an instance.
43. throws: The Java throws keyword is used to declare an exception. Checked exceptions can be
propagated with throws.
44. transient: Java transient keyword is used in serialization. If you define any data member as
transient, it will not be serialized.
45. try: Java try keyword is used to start a block of code that will be tested for exceptions. The try
block must be followed by either catch or finally block.
46. void: Java void keyword is used to specify that a method does not have a return value.
47. volatile: Java volatile keyword is used to indicate that a variable may change asynchronously.
48. while: Java while keyword is used to start a while loop. This loop iterates a part of the program
several times. If the number of iteration is not fixed, it is recommended to use the while loop.

Control Statements | Control Flow


Java compiler executes the code from top to bottom. The statements in the code are executed according to
the order in which they appear. However, Java provides statements that can be used to control the flow of
Java code. Such statements are called control flow statements. It is one of the fundamental features of
Java, which provides a smooth flow of program.
Java provides three types of control flow statements.
1. Decision Making statements
o if statements
o switch statement
2. Loop statements
o do while loop
o while loop
o for loop
o for-each loop
3. Jump statements
o break statement
o continue statement
Decision-Making statements:
As the name suggests, decision-making statements decide which statement to execute and when.
Decision-making statements evaluate the Boolean expression and control the program flow depending
upon the result of the condition provided. There are two types of decision-making statements in Java, i.e.,
If statement and switch statement.
1) If Statement:
In Java, the "if" statement is used to evaluate a condition. The control of the program is diverted
depending upon the specific condition. The condition of the If statement gives a Boolean value, either true
or false. In Java, there are four types of if-statements given below.
1. Simple if statement
2. if-else statement
3. if-else-if ladder
4. Nested if-statement
Let's understand the if-statements one by one.
1) Simple if statement:
It is the most basic statement among all control flow statements in Java. It evaluates a Boolean expression
and enables the program to enter a block of code if the expression evaluates to true.
Syntax of if statement is given below.
if(condition)
{
statement 1; //executes when condition is true
}
Consider the following example in which we have used the if statement in the java code.
Student.java
public class Student
{
public static void main(String[] args)
{
int x = 10;
int y = 12;
if(x+y > 20)
{
System.out.println("x + y is greater than 20");
}
}
}
2) if-else statement
The if-else statement is an extension to the if-statement, which uses another block of code, i.e., else block.
The else block is executed if the condition of the if-block is evaluated as false.
Syntax:
if(condition)
{
statement 1; //executes when condition is true
}
Else
{
statement 2; //executes when condition is false
}
Consider the following example.
Student.java
public class Student
{
public static void main(String[] args)
{
int x = 10;
int y = 12;
if(x+y < 10)
{
System.out.println("x + y is less than 10");
}
else
{
System.out.println("x + y is greater than 20");
}
}
}
3) if-else-if ladder:
The if-else-if statement contains the if-statement followed by multiple else-if statements. In other words,
we can say that it is the chain of if-else statements that create a decision tree where the program may enter
in the block of code where the condition is true. We can also define an else statement at the end of the
chain.
Syntax of if-else-if statement is given below.
if(condition 1)
{
statement 1; //executes when condition 1 is true
}
else if(condition 2)
{
statement 2; //executes when condition 2 is true
}
else
{
statement 2; //executes when all the conditions are false
}
Consider the following example.
Student.java
public class Student
{
public static void main(String[] args)
{
String city = "Dar Es Salaam";
if(city == "Arusha")
{
System.out.println("city is Arusha ");
}
else if (city == "Mbeya")
{
System.out.println("city is Mbeya ");
}
else if(city == "Mwanza")
{
System.out.println("city is Mwanza ");
}
else
{
System.out.println(city);
}
}
}
4. Nested if-statement
In nested if-statements, the if statement can contain a if or if-else statement inside another if or else-if
statement.
Syntax of Nested if-statement is given below.
if(condition 1)
{
statement 1; //executes when condition 1 is true
if(condition 2)
{
statement 2; //executes when condition 2 is true
}
Else
{
statement 2; //executes when condition 2 is false
}
}
Consider the following example.
Student.java
public class Student
{
public static void main(String[] args)
{
String address = " Dar Es Salaam, Tanzania ";
if(address.endsWith("Tanzania "))
{
if(address.contains("Arusha"))
{
System.out.println("Your city is Arusha");
}
else if(address.contains("Mbeya"))
{
System.out.println("Your city is Mbeya");
}
else
{
System.out.println(address.split(",")[0]);
}
}
else
{
System.out.println("You are not living in Tanzania ");
}
}
}
Switch Statement:
Switch statements are similar to if-else-if statements. The switch statement contains multiple blocks of
code called cases and a single case is executed based on the variable which is being switched. The switch
statement is easier to use instead of if-else-if statements. It also enhances the readability of the program.
Points to be noted about switch statement:
o The case variables can be int, short, byte, char, or enumeration. String type is also supported since
version 7 of Java
o Cases cannot be duplicate
o Default statement is executed when any of the case doesn't match the value of expression. It is
optional.
o Break statement terminates the switch block when the condition is satisfied.
It is optional, if not used, next case is executed.
o While using switch statements, we must notice that the case expression will be of the same type
as the variable. However, it will also be a constant value.
The syntax to use the switch statement is given below.
switch (expression)
{
case value1:
statement1;
break;
.
.
.
case valueN:
statementN;
break;
default:
default statement;
}
Consider the following example to understand the flow of the switch statement.
Student.java
public class Student implements Cloneable
{
public static void main(String[] args)
{
int num = 2;
switch (num)
{
case 0:
System.out.println("number is 0");
break;
case 1:
System.out.println("number is 1");
break;
default:
System.out.println(num);
}
}
}
}
While using switch statements, we must notice that the case expression will be of the same type as the
variable. However, it will also be a constant value. The switch permits only int, string, and Enum type
variables to be used.
Loop Statements
In programming, sometimes we need to execute the block of code repeatedly while some condition
evaluates to true. However, loop statements are used to execute the set of instructions in a repeated order.
The execution of the set of instructions depends upon a particular condition.
We have three types of loops that execute similarly. However, there are differences in their syntax and
condition checking time.
1. for loop
2. while loop
3. do-while loop
Let's understand the loop statements one by one.
For loop
In Java, for loop is similar to C and C++. It enables us to initialize the loop variable, check the condition,
and increment/decrement in a single line of code. We use the for loop only when we exactly know the
number of times, we want to execute the block of code.
for(initialization, condition, increment/decrement)
{
//block of statements
}
Example
public class Calculattion
{
public static void main(String[] args)
{
// TODO Auto-generated method stub
int sum = 0;
for(int j = 1; j<=10; j++)
{
sum = sum + j;
}
System.out.println("The sum of first 10 natural numbers is " + sum);
}
For-each loop
Java provides an enhanced for loop to traverse the data structures like array or collection. In the for-each
loop, we don't need to update the loop variable. The syntax to use the for-each loop in java is given
below.
for(data_type var : array_name/collection_name)
{
//statements
}
}
public class Calculation
{
public static void main(String[] args)
{
// TODO Auto-generated method stub
String[] names = {"Java","C","C++","Python","JavaScript"};
System.out.println("Printing the content of the array names:\n");
for(String name:names)
{
System.out.println(name);
}
}
}
While loop
The while loop is also used to iterate over the number of statements multiple times. However, if we don't
know the number of iterations in advance, it is recommended to use a while loop. Unlike for loop, the
initialization and increment/decrement doesn't take place inside the loop statement in while loop.
It is also known as the entry-controlled loop since the condition is checked at the start of the loop. If the
condition is true, then the loop body will be executed; otherwise, the statements after the loop will be
executed.
The syntax of the while loop is given below.
while(condition)
{
//looping statements
}
public class Calculation
{
public static void main(String[] args)
{
// TODO Auto-generated method stub
int i = 0;
System.out.println("Printing the list of first 10 even numbers \n");
while(i<=10)
{
System.out.println(i);
i = i + 2;
}
}
}
Do-while loop
The do-while loop checks the condition at the end of the loop after executing the loop statements. When
the number of iteration is not known and we have to execute the loop at least once, we can use do-while
loop.
It is also known as the exit-controlled loop since the condition is not checked in advance. The syntax of
the do-while loop is given below.
do
{
//statements
}
while (condition);
Example
public class Calculation
{
public static void main(String[] args)
{
// TODO Auto-generated method stub
int i = 0;
System.out.println("Printing the list of first 10 even numbers \n");
do
{
System.out.println(i);
i = i + 2;
}while(i<=10);
}
}
Jump Statements
Jump statements are used to transfer the control of the program to the specific statements. In other words,
jump statements transfer the execution control to the other part of the program. There are two types of
jump statements in Java, i.e., break and continue.
Break statement
As the name suggests, the break statement is used to break the current flow of the program and transfer
the control to the next statement outside a loop or switch statement. However, it breaks only the inner
loop in the case of the nested loop.
The break statement cannot be used independently in the Java program, i.e., it can only be written inside
the loop or switch statement.
The break statement example with for loop
Consider the following example in which we have used the break statement with the for loop.
BreakExample.java
public class BreakExample
{
public static void main(String[] args)
{
// TODO Auto-generated method stub
for(int i = 0; i<= 10; i++)
{
System.out.println(i);
if(i==6)
{
break;
}
}
}
}
Java continue statement
Unlike break statement, the continue statement doesn't break the loop, whereas, it skips the specific part
of the loop and jumps to the next iteration of the loop immediately.
Consider the following example to understand the functioning of the continue statement in Java.
public class ContinueExample
{
public static void main(String[] args)
{
// TODO Auto-generated method stub
for(int i = 0; i<= 2; i++)
{
for (int j = i; j<=5; j++)
{
if(j == 4)
{
continue;
}
System.out.println(j);
}
}
}
}
Function
Java is one of the most popular programming languages in the world, and one of its key features is its
ability to define and use functions. Functions in Java are blocks of code that perform a specific task, and
they are used to organize code and make it more modular and reusable. In this article, we will explore the
basics of Java functions, including how to define them, how to pass parameters, and how to return values.
Defining a Function
In order to define a function in Java, you use the keyword "public" (or "private" or "protected") followed
by the return type of the function, then the name of the function, and finally a set of parentheses
containing any parameters the function may take. For example, here is a simple function that takes no
parameters and returns nothing:
public void sayHello()
{
System.out.println("Hello, world!");
}
In this case, the function is called "sayHello", it takes no parameters (i.e., the parentheses are empty), and
it returns nothing (i.e., the return type is "void"). To call this function from another part of your code, you
simply write its name followed by a set of parentheses, like this:
sayHello();
Passing Parameters to a Java Function
Functions can also take one or more parameters, which are passed in as values when the function is
called. To define a function that takes one or more parameters, you simply list them inside the parentheses
when you define the function. Here's an example of a function that takes two parameters (both of type
"int") and returns their sum:
public int add(int a, int b)
{
return a + b;
}
In this case, the function is called "add", it takes two parameters (both of type "int"), and it returns their
sum (also of type "int"). To call this function and pass in two values, you would write:/p>
int result = add(5, 7);
In this case, the values 5 and 7 are passed in as the values of the "a" and "b" parameters, respectively, and
the result of the function (12) is assigned to the "result" variable.
Returning Values from a Java Function
Functions in Java can also return a value, which is specified by the return type of the function. To define a
function that returns a value, you simply specify the return type (which can be any data type, including
objects) before the function name, like this:
public int doubleValue(int a)
{
return a * 2;
}
In this case, the function is called "doubleValue", it takes one parameter (an integer), and it returns twice
the value of that parameter. To call this function and get the result, you would write:
int result = doubleValue(5);
In this case, the value 5 is passed in as the value of the "a" parameter, and the result of the function (10) is
assigned to the "result" variable.
Functions are an important part of any programming language, and Java is no exception. With Java
functions, you can organize your code into modular, reusable blocks, and pass in values and return results
as needed. By mastering the basics of Java functions, you will be well on your way to becoming a skilled
Java programmer. Functions in Java are also commonly known as methods, and they play a key role in
structuring and organizing code. By encapsulating blocks of code into functions, you can create reusable
and modular code that can be called from other parts of the program.
Functions can take zero or more parameters as input, and they can return a value or perform an action
without returning a value. The return type of a function is specified by placing the data type of the return
value before the name of the function.
Here's an example Java program with input and output that demonstrates Java functions:
FunctionExample.java
import java.util.Scanner;
public class FunctionExample
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int num1 = scanner.nextInt();
System.out.print("Enter another number: ");
int num2 = scanner.nextInt();
int sum = add(num1, num2);
System.out.println("The sum of " + num1 + " and " + num2 + " is " + sum + ".");
public static int add(int a, int b)
{
return a + b;
}
}
Arrays
An array is typically a grouping of elements of the same kind that are stored in a single, contiguous block
of memory.
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.
In contrast to C/C++, the length member allows us to obtain the array's length. We must utilise the sizeof
operator in C/C++.
An object of a dynamically formed class is called an array in Java. Java arrays implement the Serializable
and Cloneable interfaces and derive from the Object class. In Java, an array can hold objects or primitive
values. Java allows us to create single- or multi-dimensional arrays, just like C/C++ does.
Additionally, C/C++ does not support the anonymous array functionality that Java does.

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: Arrays have a fixed size and do not grow dynamically at runtime.
Types of Array in java
There are two types of array.
Single Dimensional Array
Multidimensional Array
Single-Dimensional Array in Java
A single-dimensional array in Java is a linear collection of elements of the same data type. It is declared
and instantiated using the following syntax:
dataType[] arr; (or)
dataType []arr; (or)
dataType arr[];
Instantiation of an Array in Java
arrayRefVar=new datatype[size];
Example of Java Array
Let's see the simple example of java array, where we are going to declare, instantiate, initialize and
traverse an array.
//Java Program to illustrate how to declare, instantiate, initialize
//and traverse the Java array.
class Testarray
{
public static void main(String args[])
{
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}
}
Declaration, Instantiation and Initialization of Array
You can declare, instantiate, and initialize an array in a single line, as demonstrated below:
int a[]={33,3,4,5};//declaration, instantiation and initialization
Let's see the simple example to print this array.
//Java Program to illustrate the use of declaration, instantiation
//and initialization of Java array in a single line
class Testarray1
{
public static void main(String args[])
{
int a[]={33,3,4,5};//declaration, instantiation and initialization
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}
}
For-each Loop for Array
We can also print the Java array using for-each loop. The Java for-each loop prints the array elements one
by one. It holds an array element in a variable, then executes the body of the loop.
The syntax of the for-each loop is given below:
for(data_type variable:array)
{
//body of the loop
}
Testarray1.java
//Java Program to print the array elements using for-each loop
class Testarray1
{
public static void main(String args[])
{
int arr[]={33,3,4,5};
//printing array using for-each loop
for(int i:arr)
System.out.println(i);
}
}
Passing Array to a Method in Java
We can pass the Java array to the method so that we can reuse the same logic on any array. When we pass
an array to a method in Java, we are essentially passing a reference to the array. It means that the method
will have access to the same array data as the calling code, and any modifications made to the array
within the method will affect the original array.
Testarray2.java
//Java Program to demonstrate the way of passing an array
//to method.
class Testarray2
{
//creating a method which receives an array as a parameter
static void min(int arr[])
{
int min=arr[0];
for(int i=1;i<arr.length;i++)
if(min>arr[i])
min=arr[i];
System.out.println(min);
}
public static void main(String args[])
{
int a[]={33,3,4,5};//declaring and initializing an array
min(a);//passing array to method
}
}
Returning Array from the Method
In Java, methods are not limited to returning simple data types or objects; they can also return arrays. This
feature allows for more flexibility in method design and enables developers to encapsulate complex logic
for generating arrays within methods.
TestReturnArray.java
//Java Program to return an array from the method
class TestReturnArray
{
//creating method which returns an array
static int[] get()
{
return new int[]{10,30,50,90,60};
}
public static void main(String args[])
{
//calling method which returns an array
int arr[]=get();
//printing the values of an array
for(int i=0;i<arr.length;i++)
System.out.println(arr[i]);
}
}
Multidimensional Array in Java
A multidimensional array in Java is an array of arrays where each element can be an array itself. It is
useful for storing data in row and column format.
Syntax to Declare Multidimensional Array in Java
dataType[][] arrayRefVar; (or)
dataType [][]arrayRefVar; (or)
dataType arrayRefVar[][]; (or)
dataType []arrayRefVar[];
Example to instantiate Multidimensional Array in Java
int[][] arr=new int[3][3];//3 row and 3 column
Example to initialize Multidimensional Array in Java
arr[0][0]=1;
arr[0][1]=2;
arr[0][2]=3;
arr[1][0]=4;
arr[1][1]=5;
arr[1][2]=6;
arr[2][0]=7;
arr[2][1]=8;
arr[2][2]=9;
Example of Multidimensional Java Array
Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional array.
TestMultiArray.java
class TestMultiArray
{
public static void main(String args[])
{
int arr[][] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; // 3x3 matrix
// Printing the 2D array
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
}
Addition of Two Matrices in Java
A fundamental operation in linear algebra and computer science, matrix addition is frequently utilised in a
variety of applications, including scientific computing, computer graphics, and image processing. To
create a new matrix with the same dimensions as the original, matching elements from each matrix must
be added when adding two matrices in Java. This Java program shows how to add matrices effectively by
using stacked loops to do a basic example of the process.
ArrayAddition.java
//Java Program to demonstrate the addition of two matrices in Java
class ArrayAddition
{
public static void main(String args[])
{
//creating two matrices
int a[][]={{1,3,4},{3,4,5}};
int b[][]={{1,3,4},{3,4,5}};
//creating another matrix to store the sum of two matrices
int c[][]=new int[2][3];
//adding and printing addition of 2 matrices
for(int i=0;i<2;i++)
{
for(int j=0;j<3;j++)
{
c[i][j]=a[i][j]+b[i][j];
System.out.print(c[i][j]+" ");
}
System.out.println();//new line
}
}
}

You might also like