Unit1 Java
Unit1 Java
[Link]
[Link]
UNIT-I
Foundations of Java: History of Java, Java Features, Variables, Data Types, Operators, Expressions, Control
Statements. Elements of Java - Class, Object, Methods, Constructors and Access Modifiers, Generics, Inner classes,
String class and Annotations.
OOP Principles: Encapsulation – concept, setter and getter method usage, this keyword. Inheritance - concept,
Inheritance Types, super keyword. Polymorphism – concept, Method Overriding usage and Type Casting.
Abstraction – concept, abstract keyword and Interface.
Foundations of Java
Java is a Programming Language and a Platform Independent. Java is a high level, robust, object-
oriented and secure programming language.
Java was developed by Sun Microsystems (which is now the subsidiary of Oracle) in the year 1995. James
Gosling is known as the father of Java. Before Java, its name was Oak. Since Oak was already a registered
company, so James Gosling and his team changed the name from Oak to Java.
Platform: Any hardware or software environment in which a program runs, is known as a platform. Since
Java has a runtime environment (JRE) and API, it is called a platform.
History of Java
The C language developed in 1972 by Dennis Ritchie had taken a decade to become the most popular
language.
In 1979, Bjarne Stroustrup developed C++, an enhancement to the C language with included OOP
fundamentals and features.
A project named “Green” was initiated in December of 1990, whose aim was to create a programming tool
that could render obsolete the C and C++ programming languages.
Finally in the year of 1991 the Green Team was created a new Programming language named “OAK”.
After some time they found that there is already a programming language with the name “OAK”.
So, the green team had a meeting to choose a new name. After so many discussions they want to have a
coffee. They went to a Coffee Shop which is just outside of the Gosling’s office and there they have
decided name as “JAVA”.
Editions of Java
Each edition of Java has different capabilities. There are three editions of Java:
o Java Standard Editions(JSE): It is used to create programs for a desk top computer.
o Java Enterprise Edition (JEE): It is used to create large programs that run on the server and manages
heavy traffic and complex transactions.
Java Micro Edition (JME): It is used to develop applications for small devices such as set-top boxes,
phone, and appliances.
o Standalone Applications: Java standalone applications uses GUI components such as AWT, Swing,
and Java FX. These components contain buttons, list, menu, scroll panel, etc. It is also known as desktop
alienations.
o Enterprise Applications: An application which is distributed in nature is called enterprise applications.
o Web Applications: An applications that run on the server is called web applications. We use JSP,
Servlet, Spring, and Hibernate technologies for creating web applications.
o Mobile Applications: Java ME is a cross-platform to develop mobile applications which run across
smart phones. Java is a platform for App Development in Android.
Applications
According to Sun, 3 billion devices run Java. There are many devices where Java is currently used.
Object-Oriented Programming is a paradigm that provides many concepts, such as inheritance, data
binding, polymorphism, etc.
Simula is considered the first object-oriented programming language. The programming paradigm where
everything is represented as an object is known as a truly object-oriented programming language.
Small talk is considered the first truly object-oriented programming language.
The popular object-oriented languages are Java, C#, PHP, Python, C++, etc
The main aim of object-oriented programming is to implement real-world entities, for example, object,
classes, abstraction, inheritance, polymorphism, etc.
The majority of experts cannot deny the fact that Java is one of the most powerful and effective
languages ever created and is the most widely used programming language in many areas.
But, we also know that every coin has two sides; similarly, Java can not run away from this fact and
therefore it has also got its own limitations and benefits; what we call it is a pros and cons of Java.
We will explain you with the prominent advantages and disadvantages of Java, which will help you have a
clear vision of this language.
Advantages of Java
Java is an Object-Oriented and a general-purpose programming language that helps to create programs
and applications on any platform. Java comes up with a bundle of advantages that lets you stick with it.
1. Java is Simple
Any language can be considered as simple if it is easy to learn and understand. The syntax of Java is
straight forward, easy to write, learn, maintain, and understand, the code is easily debuggable.
Moreover, Java is less complex than the languages like C and C++, because many of the complex
features of these languages are being removed from Java such as explicit pointers concept, storage
classes, operator overloading, and many more.
Java is an object-oriented language that helps us to enhance the flexibility and reusability of the code. Using
the OOPs concept, we can easily reuse the object in other programs.
It also helps us to increase security by binding the data and functions into a single unit and not letting it
be accessed by the outside world. It also helps to organize the bigger modules in to smaller ones so they
are easy to understand.
Java reduces security threats and risks by avoiding the use of explicit pointers. A pointer stores the
memory address of another value that can cause unauthorized access to memory.
This issue is resolved by removing the concept of pointers. Also, there is a Security manager in Java for
each application that allows us to define the access rules for classes.
Java programs are cheap to develop and maintain as these programs are dependent on a specific
hardware infrastructure to run. We can easily execute them on any machine that reduces the extra cost
to maintain.
5. Java is platform-independent
Java offers a very effective boon to its users by providing the feature of platform independence that is
Write Once Run Any where(WORA) feature.
The compiled code, i.e the byte code of java is platform-independent and can run on any machine
irrespective of the operating system. We can run this code on any machine that supports the Java
Virtual Machine(JVM)as shown in the figure below:
Java is a portable language due to its platform independence feature. As the Java code can be run on any
platform, it is portable and can be taken to any platform and can be executed on them. Therefore Java
also provides the advantage of portability.
There is automatic memory management in Java that is managed by the Java Virtual Machine(JVM).
Whenever the objects are not used by programs anymore and they do not refer to anything that they do
not need to be dereferenced or removed by the explicit programming.
Java automatically removes the unused objects with the help of the automatic Garbage Collection process.
Java is a multithreaded language that is in Java more than one thread can run at the same time. A thread is
the smallest unit of a process. Multithreading helps us to gain the maximum utilization of CPU.
Multiple threads share a common memory area and increase the efficiency and performance of the
application. These threads run independently of each other without affecting each other.
10. Java is a high-level programming language
Java is a portable language due to its platform independence feature. As the Java code can be run on any
platform, it is portable and can be taken to any platform and can be executed on them. Therefore Java
also provides the advantage of portability.
There is automatic memory management in Java that is managed by the Java Virtual Machine(JVM).
Whenever the objects are not used by programs anymore and they do not refer to anything that they do
not need to be dereferenced or removed by the explicit programming.
Java automatically removes the unused objects with the help of the automatic Garbage Collection process.
Java is a multithreaded language that is in Java more than one thread can run at the same time. A thread is
the smallest unit of a process. Multithreading helps us to gain the maximum utilization of CPU.
Multiple threads share a common memory area and increase the efficiency and performance of the
application. These threads run independently of each other without affecting each other.
Java programs are more stable as compared to programs of other languages. More over, a new version of
Java is released in no time with more advanced features which makes it more stable.
15. Java is a distributed language
Java is a distributed language as it provides a mechanism for sharing data and programs among multiple
computers that improve the performance and efficiency of the system.
The RMI (Remote Method Invocation) is something that supports the distributed processing in Java.
Moreover, Java also supports Socket Programming and the CORBA technology that helps us to share
objects in a distributed environment.
Java has an efficient memory allocation strategy as it divides the memory mainly in two parts – Heap
Area and Stack Area.
The JVM provides us the memory space for any variable either from the heap area or the stack area.
Whenever we declare a variable JVM gives memory from either stack or heap space.
Disadvantages of Java
To start learning or working upon any programming language you must know its strengths and
weaknesses so that you can utilize the best things out of it and a void causing the circumstances that
portray in the bad side of the language.
Java has also got some drawbacks that you should know before starting over. Let’s discuss the cons of using
Java.
Java is memory-consuming and significantly slower than native languages such as C or C++. It is also
slow compared to other languages like C and C++ because each code has to be interpreted to the machine
level code.
This slow performance is due to the extra level of compilation and abstraction by the JVM. Moreover,
some times the garbage collector leads in the poor performance of Java as it consumes more CPU time.
Though there are many GUI builders in Java for creating the graphical interfaces till they are not suitable
for creating complicated UI. There are many inconsistencies while using them.
There are many popular frameworks such as Swing, SWT, Java FX, JSF for creating GUI. But
they are not mature enough to develop a complex UI. Choosing one of them which can be suitable
for you may require additional research.
4. Java provides no backup facility
Java mainly works on storage and not focuses on the backup of data. This is a major drawback that
makes it lose the interest and ratings among users.
Java requires a significant or major amount of memory space as compared to other languages like C
and C++. During the execution of garbage collection, the memory efficiency and the performance of
the system may be adversely affected.
Java codes are verbose, meaning that there are many words in it and there are many long and complex
sentences that are difficult to read and understand. This can reduce the readability of the code.
Java focuses on being more manageable but at the same time, it has to compromise it with the overly
complex codes and long explanations for each thing.
Simple
Secure
Portable
Object-oriented
Robust
Architecture-neutral (or) Platform Independent
Multi-threaded
Interpreted
High performance
Distributed
Dynamic
Simple
Java programming language is very simple and easy to learn, understand, and code. Most of the syntaxes in java
follow basic programming language C and object-oriented programming concepts are similar to C++.
In a java programming language, many complicated features like pointers, operator overloading, structures,
unions, etc. have been removed. One of the most useful features is the garbage collector it makes java more
simple.
Secure
Java is said to be more secure programming language because it does not have pointers concept, java provides a
feature "applet" which can be embedded into a web application. The applet in java does not allow access to
other parts of the computer, which keeps away from harmful programs like viruses and unauthorized access.
Portable
Portability is one of the core features of java which enables the java programs to run on any computer or
operating system. For example, an applet developed using java runs on a wide variety of CPUs, operating
systems, and browsers connected to the Internet.
Object-oriented
Java is said to be a pure object-oriented programming language. In java, everything is an object. It supports all
the features of the object-oriented programming paradigm. The primitive data types java also implemented as
objects using wrapper classes, but still, it allows primitive data types to archive high-performance.
Robust
Java is more robust because the java code can be executed on a variety of environments, java has a strong
memory management mechanism (garbage collector), java is a strictly typed language, it has a strong set of
exception handling mechanism, and many more.
Multi-threaded
Java supports multi-threading programming, which allows us to write programs that do multiple operations
simultaneously.
Interpreted
Java enables the creation of cross-platform programs by compiling into an intermediate representation called
Java byte code. The byte code is interpreted to any machine code so that it runs on the native machine.
High performance
Java provides high performance with the help of features like JVM, interpretation, and its simplicity.
Distributed
Java programming language supports TCP/IP protocols which enable the java to support the distributed
environment of the Internet. Java also supports Remote Method Invocation (RMI), this feature enables a
program to invoke methods across a network.
Dynamic
Java is said to be dynamic because the java byte code may be dynamically updated on a running system and it
has a dynamic memory allocation and deallocation (objects and garbage collector).
Overview of Java
Java is a computer programming language. Java was created based on C and C++.
Java uses C syntax and many of the object-oriented features are taken from C++.
Before Java was invented there were other languages like COBOL, FORTRAN, C, C++, SmallTalk, etc.
These languages had few disadvantages which were corrected in Java.
Java also innovated many new features to solve the fundamental problems which the previous languages
could not solve.
Java was invented by a team of 13employees of Sun Micro systems, Inc. which is lead by James
Gosling, in 1991.
The team includes persons like Patrick Naughton, Chris Warth, EdFrank, and Mike Sheridan, etc.,
Java was developed as a part of the Green project.
Initially, it was called Oak, later it was changed to Java in 1995.
Java Variables
A variable is a named memory location used to store a data value. A variable can be defined as a
container that holds a data value.
In java, we use the following syntax to create variables.
Syntax
Local variables
Instance variables or Member variables or Global variables
Static variables or Class variables
Final variables
Local variables
The variables declared inside a method or a block are known as local variables. A local variable is
visible within the method in which it is declared.
The local variable is created when execution control enters into the method or block and destroyed after
the method or block execution completed.
Let's look at the following example java program to illustrate local variable in java.
Example
{
public void show()
{
int a = 10; //static intx=100;
[Link]("Inside show method,
a="+a);
}
public void display()
{
int b =20;
[Link]("Inside display method,b="+b);
// trying to access variable 'a' - generates an
ERROR [Link]("Inside display
method,a="+a);
}
public static void main(String args[]) {
LocalVariables obj=new
LocalVariables(); [Link]();
[Link]();
}
}
Output:
Inside display method,b=20
Instance variables or member variables or Global variables
The variables declared inside a class and outside any method, constructor or block are known as instance
variables or member variables.
These variables are visible to all the methods of the class. The changes made to these variables by method
affects all the methods in the class.
These variables are created separate copy for every object of that class.
Let's look at the following example java program to illustrate instance variable in java
Example
int x = 100;
Output:
Static variables are initialized only once, at the start of the program execution. The static variable only
has one copy per class irrespective of how many objects we create.
The static variable is access by using class name.
Let's look at the following example java program to illustrate static variable in java.
Example
The variable created using final keyword acts as constant. All variables like local, instance, and static
variables can be final variables.
Let's look at the following example java program to illustrate final variable in java.
Example
void show() {
[Link]("a = " + a);
// a = 20; // Commented out to prevent the compilation error
}
Output:
a = 10
The following table provides more description of each primitive data type.
Every variable of the non-primitive data type is an object. The non-primitive data types may use
additional methods to perform certain operations.
Java Operators
An operator is a symbol used to perform arithmetic and logical operations. Java provides a rich set of
operators. In java, operators are classified into the following four types.
Arithmetic Operators
Relational (or) Comparison Operators
Logical Operators
Assignment Operators
Bitwise Operators
Conditional Operators
Arithmetic Operators
In java, arithmetic operators are used to performing basic mathematical operations like addition, subtraction,
multiplication, division, modulus, increment, decrement, etc.,
+ Addition 10 + 5 =15
- Subtraction 10 -5 = 5
* Multiplication 10 * 5 = 50
/ Division 10 /5= 2
++ Increment a++
-- Decrement a--
The addition operator can be used with numerical data types and character or string data type. When it is
used with numerical values, it performs mathematical addition and when it is used with character or string
data type values, it performs concatenation (appending).
The modulus (remainder of the division) operator is used with integer data type only.
The increment and decrement operators are used as pre-increment or pre-decrement and post- increment
or post-decrement.
When they are used as pre, the value is get modified before it is used in the actual expression and
when it is used as post, the value is get modified after the actual expression evaluation.
Example
{
public static void main(String[] args)
{
int a = 10, b = 20, result;
[Link]("a="+a+",b="+b);
result = a + b;
[Link]("Addition:"+a+"+"+b+"="+result); result = a - b;
[Link]("Subtraction:"+a+"-"+b+"="+result); result = a * b;
[Link]("Multiplucation:"+a+"*"+b+"="+result); result = b / a;
[Link]("Division:"+b+"/"+a+"="+result); result = b % a;
[Link]("Modulus:"+b+"%"+a+"="+result); result = ++a;
[Link]("Pre-increment:++a="+result); result = b--;
[Link]("Post-decrement:b--="+ result);
}
}
Output:
a=10,b=20
Addition:10+20=30
Subtraction:10-20=-10
Multiplucation:10*20=200
Division:20/10=2
Modulus:20%10=0
Pre-increment:++a=11
Post-decrement:b--=20
Every relational operator has two possible results either TRUE or FALSE. In simple words, the
relational operators are used to define conditions in a program. The following table provides
information about relational operators.
< Returns TRUE if the first value is smaller than second value 10 < 5is FALSE
otherwise returns FALSE
> Returns TRUE if the first value is larger than second value 10> 5isTRUE
otherwise returns FALSE
<= Returns TRUE if the first value is smaller than or equal to 10 <= 5is FALSE
second value otherwise returns FALSE
>= Returns TRUE if the first value is larger than or equal to second 10>= 5isTRUE
value otherwise returns FALSE
== Returns TRUE if both values are equal otherwise returns 10 == 5is FALSE
FALSE
!= Returns TRUE if both values are not equal otherwise returns 10!= 5 isTRUE
FALSE
Look at the following example program.
Example
Output:
10<5isfalse
10>5istrue
10<=5isfalse
10>=5istrue
10==5isfalse
10!=5 istrue
Logical Operators
The logical operators are the symbols that are used to combine multiple conditions in to one condition. The
following table provides information about logical operators.
& Logical AND-Returns TRUE if all conditions are TRUE otherwise returns False & true => false
FALSE
| Logical OR-Returns FALSE if all conditions are FALSE otherwise returns False | true => true
TRUE
^ Logical XOR-Returns FALSE if all conditions are same otherwise returns True ^ true => false
TRUE
! Logical NOT-Returns TRUE if condition is FLASE and returns FALSE if it !false => true
is TRUE
&& short-circuit AND-Similar to Logical AND(&), but once a decision is False & true => false
finalized it does not evaluate remaining.
The operators &,|, and ^ can be used with both Boolean and integer data type values. When they
are used with integers, performs bitwise operations and with Boolean, performs logical
operations.
a = x>y &(z=x+y)>15;
[Link]("a = "+a+ ", and z ="+z);
}
}
Output:
a=false,andz=0
a = false, and z =30
Assignment Operators
The assignment operators are used to assign right-hand side value (R value) to the left-hand side variable (L
value). The assignment operator is used in different variants along with arithmetic operators. The following
table describes all the assignment operators in the java programming language.
+= Add both left and right-hand side values and store the result into left-hand A+= 10
side variable
-= Subtract right-hand side value from left-hand side variable value and store A-=B
*= Multiply right-hand side value with left-hand side variable value and store A*= B
/= Divide left-hand side variable value with right-hand side variable value and A/= B
%= Divide left-hand side variable value with right-hand side variable value and A%= B
|= Logical OR assignment -
[Link]("a="+a); a *= b;
[Link]("a="+a); a /= b;
[Link]("a="+a); a %= b;
[Link]("a="+a); x |= (a>b);
[Link]("x="+x); x &= (a>b);
[Link]("x="+x);
}
}
Output:
a=10,b=20
a=30
a=10
a=200
a=10
a=10
x=true
x=false
Bitwise Operators
The bitwise operators are used to perform bit-level operations in the java programming language.
When we use the bitwise operators, the operations are performed based on binary values.
The following table describes all the bitwise operators in the java programming language.
Let us consider two variables A and B as A = 25 (11001) and B = 20 (10100).
& The result of Bitwise AND is 1 if all the bits are1otherwise it is 0 A&B ⇒16(10000)
^ The result of Bitwise XOR is 0 if all the bits are same otherwise it is 1 A^ B ⇒13(01101)
~ The result of Bitwise once complement is negation of the bit (Flipping) ~A⇒6 (00110)
<< The Bitwise left shift operator shifts all the bits to the left by the specified A<<2⇒100(1100100)
number of positions
>> The Bitwise right shift operator shifts all the bits to the right by the A>>2⇒6 (00110)
specified number of positions
Example
Conditional Operators
The conditional operator is also called a ternary operator because it requires three operands.
This operator is used for decision making. In this operator, first, we verify a condition, then we
perform one operation out of the two operations based on the condition result.
If the condition is TRUE the first option is performed, if the condition is FALSE the second option is
performed. The conditional operator is used with the following syntax.
Syntax
Example
{
public static void main(String[] args)
Output:
C=20
Java Expressions
In any programming language, if we want to perform any calculation or to frame any condition etc., we
use a set of symbols to perform the task.
These set of symbols makes an expression.
In the java programming language, an expression is defined as follows.
An expression is a collection of operators and operands that represents a specific value.
In the above definition, an operator is a symbol that performs tasks like arithmetic operations,
logical operations, and conditional operations, etc.
Operands are the values on which the operators perform the task. Here operand can be a direct value
or variable or address of memory location.
Expression Types
In the java programming language, expressions are divided into THREE types. They are as follows.
Infix Expression
Postfix Expression
Prefix Expression
Infix Expression
The expression in which the operator is used between operands is called infix expression.
The infix expression has the following general structure.
Example
Postfix Expression
The expression in which the operator is used after operands is called postfix expression.
The postfix expression has the following general structure.
Example
Prefix Expression
The expression in which the operator is used before operands is called a prefix expression.
The prefix expression has the following general structure.
Example
if statement
if-else statement
if-elif statement
nested if statement
switch statement
While statement
do-while statement
for statement
for-each statement
Jump Statements
In java, the jump statements are used to terminate a block or take the execution control to the next [Link]
provides the following jump statements.
break
continue
return
If statement in java
In java, we use the if statement to test a condition and decide the execution of a block of statements
based on that condition result.
The if statement checks, the given condition then decides the execution of a block of statements.
If the condition is True, then the block of statements is executed and if it is False, then the block of
statements is ignored.
import [Link];
In the above execution, the number 12 is not divisible by 5. So, the condition becomes False and the condition is
evaluated to False.
import [Link];
public class IfElseStatementTest{
public static void main(String[] args){
Scanner read = new Scanner([Link]);
[Link]("Enter any number: ");
int num = [Link]();
if((num%2) ==0){
[Link]("We are inside the true-block!");
[Link]("Given number is EVEN number!!");
}
else{
[Link]("We are inside the false-block!");
[Link]("Given number is ODD number!!");
}
[Link]("We are outside the if-block!!!");
}
}
Output:
Enter any number: 15
We are inside the false-block!
Given number is ODD number!!
We are outside the if-block!!!
Nested if statement in java
Writing an if statement inside another if-statement is called nested if statement. The general syntax of the nested
if-statement is as follows.
Syntax
if(condition_1){
if(condition_2){
inner if-block of statements;
...
}
...
}
import [Link];
public class NestedIfStatementTest
{
public static void main(String[] args){
Scanner read = new Scanner([Link]);
[Link]("Enter any number: ");
int num = [Link]();
if(num <100){
if (num % 2 == 0)
[Link]("And it is EVEN");
else
[Link]("And it is ODD");
} else
[Link]("Given number is not below 100");
if(condition_1){
condition_1true-
block;
...
}
else if(condition_2){
condition_2 true-block;
condition_1false-
blocktoo;
import [Link];
public class IfElseIfStatementTest{
public static void main(String[] args){
int num1, num2,num3;
Scanner read = new Scanner([Link]);
[Link]("Enter any three numbers:");
num1 = [Link]();
num2=[Link]();
num3 =[Link]();
if(num1>=num2&&num1>=num3)
[Link]("\nThe largest number is"+num1);
else if (num2>=num1 &&num2>=num3)
[Link]("\nThe largest number is"+num2);
else
[Link]("\nThe largest number is"+num3);
[Link]("\nWe are outside the if-block!!!");
}
}
Output:
Enter any three numbers:45
56
25
Whenever the given value matches the value associated with an option, the execution starts from that option. In
the switch statement, every option is defined as a case.
The switch statement has the following syntax and execution flow diagram.
Java Program
import [Link];
public class SwitchStatementTest {
public static void main(String[] args){
Scanner read = new Scanner([Link]);
[Link]("Press any digit: ");
int value=[Link]();
switch( value )
{
case 0: [Link]("ZERO") ; break ;
case 1: [Link]("ONE") ; break ;
case 2: [Link]("TWO") ; break ;
case 3:[Link]("THREE");break;
case 4: [Link]("FOUR") ; break ;
case 5: [Link]("FIVE") ; break ;
case 6: [Link]("SIX") ; break ;
case 7:[Link]("SEVEN");break;
case 8: [Link]("EIGHT") ; break ;
case 9: [Link]("NINE") ; break ;
default: [Link]("Not a Digit") ;
}
}
}
Output:
Press any digit: 4
FOUR
Java Iterative Statements
The java programming language provides a set of iterative statements that are used to execute a statement or a
block of statements repeatedly as long as the given condition is true. The iterative statements are also known as
looping statements or repetitive statements. Java provides the following iterative statements.
for statement
for-each statement
While statement
do-while statement
Output:
i= 0
i= 1
i= 2
i= 3
i= 4
i= 5
i= 6
i= 7
i= 8
i= 9
Statement after for!
for-each statement in java
The Java for-each statement was introduced since Java 5.0 version. It provides an approach to
traverse through an array or collection in Java.
The for-each statement also known as enhanced for statement. The for-each statement executes the
block of statements for each element of the given array or collection.
In for-each statement, we cannot skip any element of given array or collection.
The for-each statement has the following syntax and execution flow diagram.
Java Program
for(int i : arrayList)
{
[Link]("i= "+i);
}
[Link]("Statement after for-each!");
}
}
Output:
i= 10
i= 20
i= 30
i= 40
i= 50
Statement after for-each!
Java Program
The do-while statement is also known as the Exit control looping statement. The do- while statement has the
following syntax.
{
public static void main(String[]args)
int num = 1;
do {
[Link](num);
num++;
}while(num <= 10);
[Link]("Statement after do-while!");
}
}
Output:
1
2
3
4
5
6
7
8
9
10
Statement after do-while!
Java Jump Statements
The java programming language supports jump statements that used to transfer execution control from one line
to another line. The java programming language provides the following jump statements.
Break statement
Continue statement
The break statement in java is used to terminate a switch or looping statement. That means the break
statement is used to come out of a switch statement and a looping statement like while, do-while, for,
and for-each.
Using the break statement outside the switch or loop statement is not allowed.
The following picture depicts the execution flow of the break statement.
Java Program
public class JavaBreakStatement {
public static void main(String[] args) {
int list[]={10,20,30,40,50};
for(int i :list){
if(i==30)
break;
[Link](i);
} }
}
Output:
10
20
The continue statement is used to move the execution control to the beginning of the looping
statement. When the continue statement is encountered in a looping statement, the execution control
skips the rest of the statements in the looping block and directly jumps to the beginning of the loop.
The continue statement can be used with looping statements like while, do-while, for, and for-each.
When we use continue statement with while and do-while statements, the execution control directly
jumps to the condition. When we use continue statement with for statement the execution control
directly jumps to the modification portion (increment/decrement/any modification) of the for loop.
The continue statement flow of execution is as shown in the following figure.
Let's look at the following example java code.
Java Program
Output:
10
20
40
50
Labeled break and continue statement in java
The java programming language doesnot support goto statement, alternatively, the break and continue
statements can be used with label.
The labelled break statement terminates the block with specified label. The labbeled contonue
statement takes the execution control to the beginning of a loop with specified label.
Let's look at the following example java code.
Java Program
import [Link];
public class JavaLabelledStatement
{
public static void main(String args[])
{
Scanner read = new Scanner([Link]);
reading:
{
[Link]("Enter a even number:");
int value = [Link]();
verify:if(value%2 ==0)
{
[Link]("\nYou won!!!");
[Link]("Your scoreis"+i*10+"out of 30.");
break reading;
}
else
{
[Link]("\nSorry try again!!!");
[Link]("You let with"+(3-i)+"more options...");
continue reading;
}
}
}
}
Output:
Enter a even number:4
You won!!!
Your scoreis10out of 30.
Enter a even number:6
You won!!!
Your scoreis20out of 30.
Enter a even number:10
You won!!!
Your scoreis30out of 30.
Return statement in java
In java, the return statement used to terminate a method with or without a value. The return statement
takes the execution control to the calling function. That means the return statement transfer the
execution control from called function to the calling function by carrying a value.
Java allows the use of return-statement with both, with and without return type methods.
In java, the return statement used with both methods with and without return type. In the case of a
method with the return type, the return statement is mandatory, and it is optional for a method without
return type.
When a return statement used with a return type, it carries a value of return type. But, when it is used
without a return type, it does not carry any value. Instead, simply transfers the execution control.
Let's look at the following example java code.
Java Program
import [Link];
int readValue() {
Scanner read = new Scanner([Link]);
[Link]("Enter any number: ");
return [Link] = [Link]();
}
Create a Method
A method must be declared within a class. It is defined with the name of the method, followed by
parentheses (). Java provides some pre-defined methods, such as [Link](), but you
can also create your own methods to perform certain actions:
// code to be executed
Call a Method
To call a method in Java, write the method's name followed by two parentheses () and a
semicolon;
In the following example, myMethod() is used to print a text (the action), when it is called:
Example
public class Main {
static void myMethod() {
[Link]("I just got executed!");
}
public static void main(String[] args)
{
myMethod();
}
}
Example
public class Main {
static void myMethod() {
[Link]("I just got executed!");
}
public static void main(String[] args) {
myMethod();
myMethod();
myMethod();
}
}
// I just got executed!
// I just got executed!
// I just got executed!
Method Overloading
Method Overloading in Java allows a class to have multiple methods with the same name but
different parameters, enabling compile-time polymorphism.
Methods can share the same name if their parameter lists differ.
Cannot overload by return type alone; parameters must differ.
The compiler chooses the most specific match when multiple methods could apply.
The different ways of method overloading in Java are mentioned below:
Method overloading can be achieved by changing the number of parameters when passing to
different methods.
import [Link].*;
class Product
{
public int multiply(int a, int b) // Multiplying two integer values
{
int prod = a * b;
return prod;
}
public int multiply(int a, int b, int c) // Multiplying three integer values
{
int prod = a * b * c;
return prod;
}
}
class pro{
Explanation:
Two methods have the same name but different number of parameters.
Compiler selects the correct method based on how many arguments are passed.
Output
6
6.0
Explanation:
Methods differ in parameter types (int vs double).
Compiler matches the method based on the exact data type of arguments.
3. Changing the Order of Parameters
Method overloading can also be implemented by rearranging the parameters of two or more
overloaded methods.
class Student {
public void studentId(String name, int rollNo)
{
[Link]("Name: " + name+ ", Roll-No: " + rollNo);
}
public void studentId(int rollNo, String name){
Explanation:
Methods have the same name but parameter order is different.
Compiler identifies which method to call based on sequence of arguments.
The Java Math Class
The Java Math class provides several built-in methods to perform mathematical operations. It is
part of the [Link] package, so you do not need to import it. All methods in the Math class are
static, meaning you call them directly using [Link]().
Commonly Used Math Methods
[Link](10,
[Link](x, y) Returns the highest value 20
20)
[Link](10,
[Link](x, y) Returns the lowest value 10
20)
[Link](x + " raised to power " + y + " is: " + [Link](x, y));
}
Output:
Square root of 25 is: 5.0
Arrays in Java
An array is a collection of variables of the same data type stored in contiguous memory
locations. Arrays have a fixed length once they are created.
numbers[1] = 20;
Elements of an array can be accessed by their position, called the index. In Java, array indexing
starts from 0 (not 1). To access an element, provide the index inside square brackets [] along
with the array name.
class GFG{
}
}
Output
12 2
To update an element at a specific index in an array, use the assignment operator = while
accessing the array element and assign a new value.
class GFG{
Output
90
3. Traverse Array
Traversing an array means accessing each element one by one. In Java, arrays can be easily
traversed using a loop where the loop variable runs from 0 to [Link] - 1.
class GFG{
Output
2 4 8 12 16
4. Size of Array
The size of an array refers to the number of elements it can hold. To find the size of array java
provides a built-in property called length.
class GFG{
Output
Size of array: 5
class Student {
public int roll_no;
public String name;
Output
Element at 0 : { 1 aman }
Element at 1 : { 2 vaibhav }
Element at 2 : { 3 shikar }
Element at 3 : { 4 dharmesh }
Element at 4 : { 5 mohit }
JVM throws ArrayIndexOutOfBoundsException to indicate that the array has been accessed
with an illegal index. The index is either negative or greater than or equal to the size of an
array.
public class Geeks {
public static void main(String[] args)
{
int[] arr = new int[4];
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
[Link](
"Trying to access element outside the size of array");
[Link](arr[5]);
}
}
Output: