Java Unit1 Languagebasics
Java Unit1 Languagebasics
Java was originally designed for interactive television, but it was too advanced
technology for the digital cable television industry at the time. The history of Java
starts with the Green Team. Java team members (also known as Green Team),
initiated this project to develop a language for digital devices such as set-top boxes,
televisions, etc. However, it was best suited for internet programming. Later, Java
technology was incorporated by Netscape.
The principles for creating Java programming were "Simple, Robust, Portable,
Platform-independent, Secured, High Performance, Multithreaded, Architecture
Neutral, Object-Oriented, Interpreted, and Dynamic". Java was developed by James
Gosling, who is known as the father of Java, in 1995. James Gosling and his team
members started the project in the early '90s.
3) Firstly, it was called "Greentalk" by James Gosling, and the file extension was .gt.
4) After that, it was called Oak and was developed as a part of the Green project.
According to James Gosling, "Java was one of the top choices along with Silk". Since
Java was so unique, most of the team members preferred Java than other names.
8) Java is an island in Indonesia where the first coffee was produced (called Java
coffee). It is a kind of espresso bean. Java name was chosen by James Gosling while
having a cup of coffee nearby his office.
11) In 1995, Time magazine called Java one of the Ten Best Products of 1995.
12) JDK 1.0 was released on January 23, 1996. After the first release of Java, there
have been many additional features added to the language. Now Java is being used
in Windows applications, Web applications, enterprise applications, mobile
applications, cards, etc. Each new version adds new features in Java.
Features of Java
The primary objective of Java programming language creation was to make it
portable, simple and secure programming language. Apart from this, there are also
some excellent features which play an important role in the popularity of this
language. The features of Java are also known as Java buzzwords.
A list of the most important features of the Java language is given below.
1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Interpreted
9. High Performance
10. Multithreaded
11. Distributed
12. Dynamic
Simple
Java is very easy to learn, and its syntax is simple, clean and easy to understand.
According to Sun Microsystem, Java language is a simple programming language
because:
o Java syntax is based on C++ (so easier for programmers to learn it after C++).
o Java has removed many complicated and rarely-used features, for example, explicit
pointers, operator overloading, etc.
o There is no need to remove unreferenced objects because there is an Automatic
Garbage Collection in Java.
Object-oriented
Java is an object-oriented programming language. Everything in Java is an object.
Object-oriented means we organize our software as a combination of different types
of objects that incorporate both data and behavior.
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
Platform Independent
There are two types of platforms software-based and hardware-based. Java provides
a software-based platform.
The Java platform differs from most other platforms in the sense that it is a software-
based platform that runs on top of other hardware-based platforms. It has two
components:
1. Runtime Environment
2. API(Application Programming Interface)
Java code can be executed on multiple platforms, for example, Windows, Linux, Sun
Solaris, Mac/OS, etc. Java code is compiled by the compiler and converted into
bytecode. This bytecode is a platform-independent code because it can be run on
multiple platforms, i.e., Write Once and Run Anywhere (WORA).
Secured
Java is best known for its security. With Java, we can develop virus-free systems. Java
is secured because:
o No explicit pointer
o Java Programs run inside a virtual machine sandbox
Java language provides these securities by default. Some security can also be
provided by an application developer explicitly through SSL, JAAS, Cryptography, etc.
Robust
The English mining of Robust is strong. Java is robust because:
Architecture-neutral
Java is architecture neutral because there are no implementation dependent features,
for example, the size of primitive types is fixed.
In C programming, int data type occupies 2 bytes of memory for 32-bit architecture
and 4 bytes of memory for 64-bit architecture. However, it occupies 4 bytes of
memory for both 32 and 64-bit architectures in Java.
Portable
Java is portable because it facilitates you to carry the Java bytecode to any platform.
It doesn't require any implementation.
High-performance
Java is faster than other traditional interpreted programming languages because Java
bytecode is "close" to native code. It is still a little bit slower than a compiled
language (e.g., C++). Java is an interpreted language that is why it is slower than
compiled languages, e.g., C, C++, etc.
Distributed
Java is distributed because it facilitates users to create distributed applications in
Java. RMI and EJB are used for creating distributed applications. This feature of Java
makes us able to access files by calling the methods from any machine on the
internet.
Multi-threaded
A thread is like a separate program, executing concurrently. We can write Java
programs that deal with many tasks at once by defining multiple threads. The main
advantage of multi-threading is that it doesn't occupy memory for each thread. It
shares a common memory area. Threads are important for multi-media, Web
applications, etc.
Dynamic
Java is a dynamic language. It supports the dynamic loading of classes. It means
classes are loaded on demand. It also supports functions from its native languages,
i.e., C and C++.
Java Architecture
Java Architecture is a collection of components, i.e., JVM,
JRE, and JDK. It integrates the process of interpretation and compilation. It defines
all the processes involved in creating a Java program. Java Architecture explains
each and every step of how a program is compiled and executed.
JVM, first of all, loads the code into memory and verifies it. After that, it executes the code
and provides a runtime environment. Java Virtual Machine (JVM) has its own architecture,
which is given below:
JVM Architecture
JVM is an abstract machine that provides the environment in which Java bytecode is
executed. The falling figure represents the architecture of the JVM.
ClassLoader: ClassLoader is a subsystem used to load class files. ClassLoader first loads the
Java code whenever we run it.
Class Method Area: In the memory, there is an area where the class data is stored during
the code's execution. Class method area holds the information of static variables, static
methods, static blocks, and instance methods.
Heap: The heap area is a part of the JVM memory and is created when the JVM starts
up. Its size cannot be static because it increase or decrease during the application
runs.
Stack: It is also referred to as thread stack. It is created for a single execution thread. The
thread uses this area to store the elements like the partial result, local variable, data used for
calling method and returns etc.
Native Stack: It contains the information of all the native methods used in our application.
Execution Engine: It is the central part of the JVM. Its main task is to execute the byte code
and execute the Java classes. The execution engine has three main components used for
executing Java classes.
o Interpreter: It converts the byte code into native code and executes. It
sequentially executes the code. The interpreter interprets continuously and
even the same method multiple times. This reduces the performance of the
system, and to solve this, the JIT compiler is introduced.
o JIT Compiler: JIT compiler is introduced to remove the drawback of the
interpreter. It increases the speed of execution and improves performance.
o Garbage Collector: The garbage collector is used to manage the memory,
and it is a program written in Java. It works in two phases,
i.e., Mark and Sweep. Mark is an area where the garbage collector identifies
the used and unused chunks of memory. The Sweep removes the identified
object from the Mark
Java Native Interface works as a mediator between Java method calls and native
libraries.
Java Run-time Environment (JRE) is the part of the Java Development Kit (JDK). It is a
freely available software distribution which has Java Class Library, specific tools, and a
stand-alone JVM. It is the most common environment available on devices to run
java programs. The source Java code gets compiled and converted to Java bytecode.
If you wish to run this bytecode on any platform, you require JRE. The JRE loads
classes, verify access to memory, and retrieves the system resources. JRE acts as a
layer on the top of the operating system.
It also includes:
o Technologies which get used for deployment such as Java Web Start.
o Toolkits for user interface like Java 2D.
o Integration libraries like Java Database Connectivity (JDBC) and Java
Naming and Directory Interface (JNDI).
o Libraries such as Lang and util.
o Other base libraries like Java Management Extensions (JMX), Java Native
Interface (JNI) and Java for XML Processing (JAX-WS).
JDK is an acronym for Java Development Kit. The Java Development Kit (JDK) is a
software development environment which is used to develop java applications and
applets. It physically exists. It contains JRE + development tools.
JDK is an implementation of any one of the below given Java Platforms released by
Oracle corporation:
The JDK contains a private Java Virtual Machine (JVM) and a few other resources such
as an interpreter/loader (Java), a compiler (javac), an archiver (jar), a documentation
generator (Javadoc) etc. to complete the development of a Java Application.
Components of JDK
Following is a list of primary components of JDK:
appletviewer: This tool is used to run and debug Java applets without a web browser.
java: The loader for Java applications. This tool is an interpreter and can
interpret the class files generated by the javac compiler. Now a single
launcher is used for both development and deployment. The old
deployment launcher, jre, no longer comes with Sun JDK, and instead it
has been replaced by this new java loader.
javac: It specifies the Java compiler, which converts source code into Java
bytecode.
jar: The specifies the archiver, which packages related class libraries into a
single JAR file. This tool also helps manage JAR files.
javah: the C header and stub generator, used to write native methods.
jinfo: This utility gets configuration information from a running Java process or
crash dump.
jmap: Oracle jmap - Memory Map- This utility outputs the memory map for
Java and can print shared object memory maps or heap memory details
of a given process or core dump.
jps: Java Virtual Machine Process Status Tool lists the instrumented HotSpot
Java Virtual Machines (JVMs) on the target system.
jstack: It is a utility that prints Java stack traces of Java threads (experimental).
Policytool: It specifies the policy creation and management tool, which can
determine policy for a Java runtime, specifying which permissions are
available for code from various sources.
xjc: It is the part of the Java API for XML Binding (JAXB) API. It accepts an
XML schema and generates Java classes.
These are three main components of Java Architecture. The execution of a program is
done with all these three components.
Java Comments
The Java comments are the statements in a program that are not executed by the
compiler and interpreter.
Single line comments starts with two forward slashes (//). Any text in front of // is
not executed by Java.
Syntax:
1. //This is single line comment
CommentExample1.java
1. public class CommentExample1 {
2. public static void main(String[] args) {
3. int i=10; // i is a variable with value 10
4. System.out.println(i); //printing the variable i
5. }
6. }
Output:
10
Multi-line comments are placed between /* and */. Any text between /* and */ is not
executed by Java.
Syntax:
1. /*
2. This
3. is
4. multi line
5. comment
6. */
CommentExample2.java
1. public class CommentExample2 {
2. public static void main(String[] args) {
3. /* Let's declare and
4. print variable in java. */
5. int i=10;
6. System.out.println(i);
7. /* float j = 5.9;
8. float k = 4.4;
9. System.out.println( j + k ); */
10. }
11. }
Output:
10
Syntax:
1. /**
2. *
3. *We can use various tags to depict the parameter
4. *or heading or author name
5. *We can also use HTML tags
6. *
7. */
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.
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
The Boolean data type specifies one bit of information, but its "size" can't be defined
precisely.
Example:
1. Boolean one = false
The byte data type is used to save memory in large arrays where the memory savings
is most required. It saves space because a byte is 4 times smaller than an integer. It
can also be used in place of "int" data type.
Example:
1. byte a = 10, byte b = -20
The short data type can also be used to save memory just like byte data type. A short
data type is 2 times smaller than an integer.
Example:
1. short s = 10000, short r = -5000
Int Data Type
The int data type is a 32-bit signed two's complement integer. Its value-range lies
between - 2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its minimum
value is - 2,147,483,648and maximum value is 2,147,483,647. Its default value is 0.
The int data type is generally used as a default data type for integral values unless if
there is no problem about memory.
Example:
1. int a = 100000, int b = -200000
Example:
1. long a = 100000L, long b = -200000L
Example:
1. float f1 = 234.5f
Double Data Type
The double data type is a double-precision 64-bit IEEE 754 floating point. Its value
range is unlimited. The double data type is generally used for decimal values just like
float. The double data type also should never be used for precise values, such as
currency. Its default value is 0.0d.
Example:
1. double d1 = 12.3
Example:
1. char letterA = 'A'
Java Variables
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.
There are two types of data types in Java: 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.
1. int data=50;//Here data is variable
Types of Variables
There are three types of variables in Java:
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 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.
Output:
20
Output:
10
10.0
Output:
10.5
10
Output:
130
-126
Output:
20
Operators in Java
Operator in Java is a symbol that is used to perform operations. For example: +, -,
*, / etc.
There are many types of operators in Java 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.
Arithmetic multiplicative * / %
additive + -
equality == !=
bitwise exclusive OR ^
bitwise inclusive OR |
logical OR ||
Ternary ternary ? :
Output:
10
12
12
10
Output:
22
21
Output:
-11
9
false
true
Output:
15
5
50
2
0
Output:
21
Output:
40
80
80
240
Output:
2
5
2
Output:
5
5
-5
1073741819
The bitwise & operator always checks both conditions whether first condition is true
or false.
1. public class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=5;
5. int c=20;
6. System.out.println(a<b&&a<c);//false && true = false
7. System.out.println(a<b&a<c);//false & true = false
8. }}
Output:
false
false
false
10
false
11
The bitwise | operator always checks both conditions whether first condition is true
or false.
1. public class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=5;
5. int c=20;
6. System.out.println(a>b||a<c);//true || true = true
7. System.out.println(a>b|a<c);//true | true = true
8. //|| vs |
9. System.out.println(a>b||a++<c);//true || true = true
10. System.out.println(a);//10 because second condition is not checked
11. System.out.println(a>b|a++<c);//true | true = true
12. System.out.println(a);//11 because second condition is checked
13. }}
Output:
true
true
true
10
true
11
Output:
Another Example:
1. public class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=5;
5. int min=(a<b)?a:b;
6. System.out.println(min);
7. }}
Output:
Output:
14
16
Output:
13
9
18
9
Output:
1. public class OperatorExample{
2. public static void main(String args[]){
3. short a=10;
4. short b=10;
5. a=(short)(a+b);//20 which is int now converted to short
6. System.out.println(a);
7. }}
Output:
20
Syntax:
1. Destination_datatype = (target_datatype) variable;
2. (data_type) it is known as casting operator
1. float b = 3.0;
2. int a = (int) b; // converting a float value into integer
AreaOfRectangle.c
1. #include<stdio.h>
2. #include<conio.h>
3. void main()
4. {
5. printf("\n Welcome to Javatpoint tutorials ");
6. float x = 3.5, y = 4.5; // the size of float variable is 4 byte.
7. int area; // the size of the int variable is 2 bytes.
8. area = (int) x * y; // after conversion the product converts into integer
9. printf("\n Area of a Rectangle is : %d", area);
10. printf("\n Here, we convert float data type into the Int data type");
11. getch();
12. }
Output:
Suppose, we have an int data type and want to convert it into a float data type.
These are data types compatible with each other because their types are numeric,
and the size of int is 2 bytes which is smaller than float data type. Hence, the
compiler automatically converts the data types without losing or truncating the
values.
1. int a = 20;
2. Float b;
3. b = a; // Now the value of variable b is 20.000 /* It defines the conversion of int data type to
float data type without losing the information. */
In the above example, the int data type is converted into the float, which has a larger
size than int, and hence it widens the source data type.
1. #include<stdio.h>
2. #include<conio.h>
3. void main()
4. {
5. printf("\n Welcome to Javatpoint tutorials ");
6. int x = 3, y = 4; // the size of int variable is 2 byte.
7. float area; // the size of float variable is 4 bytes.
8. area = x * y; /* It is a type conversion that automatically converted by the compiler at the
compile time of a program. */
9. printf("\n Area of a Rectangle is : %f", area);
10. printf("\n Here, we convert int data type to the float data type");
11. getch();
12. }
Output:
2 It can be used both compatible data type Type conversion is only used with compatible
and incompatible data type. data types, and hence it does not require any
casting operator.
4 It is used while designing a program by It is used or take place at the compile time of a
the programmer. program.
5 When casting one data type to another, When converting one data type to another, the
the destination data type must be destination type should be greater than the
smaller than the source data. source data type.
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
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.
1. if(condition) {
2. statement 1; //executes when condition is true
3. }
Consider the following example in which we have used the if statement in the java
code.
Student.java
Student.java
1. public class Student {
2. public static void main(String[] args) {
3. int x = 10;
4. int y = 12;
5. if(x+y > 20) {
6. System.out.println("x + y is greater than 20");
7. }
8. }
9. }
Output:
x + y is greater than 20
2) if-else statement
Syntax:
1. if(condition) {
2. statement 1; //executes when condition is true
3. }
4. else{
5. statement 2; //executes when condition is false
6. }
Student.java
1. public class Student {
2. public static void main(String[] args) {
3. int x = 10;
4. int y = 12;
5. if(x+y < 10) {
6. System.out.println("x + y is less than 10");
7. } else {
8. System.out.println("x + y is greater than 20");
9. }
10. }
11. }
Output:
x + y is greater than 20
3) if-else-if ladder:
1. if(condition 1) {
2. statement 1; //executes when condition 1 is true
3. }
4. else if(condition 2) {
5. statement 2; //executes when condition 2 is true
6. }
7. else {
8. statement 2; //executes when all the conditions are false
9. }
Student.java
1. public class Student {
2. public static void main(String[] args) {
3. String city = "Delhi";
4. if(city == "Meerut") {
5. System.out.println("city is meerut");
6. }else if (city == "Noida") {
7. System.out.println("city is noida");
8. }else if(city == "Agra") {
9. System.out.println("city is agra");
10. }else {
11. System.out.println(city);
12. }
13. }
14. }
Output:
Delhi
4. Nested if-statement
1. if(condition 1) {
2. statement 1; //executes when condition 1 is true
3. if(condition 2) {
4. statement 2; //executes when condition 2 is true
5. }
6. else{
7. statement 2; //executes when condition 2 is false
8. }
9. }
Student.java
1. public class Student {
2. public static void main(String[] args) {
3. String address = "Delhi, India";
4.
5. if(address.endsWith("India")) {
6. if(address.contains("Meerut")) {
7. System.out.println("Your city is Meerut");
8. }else if(address.contains("Noida")) {
9. System.out.println("Your city is Noida");
10. }else {
11. System.out.println(address.split(",")[0]);
12. }
13. }else {
14. System.out.println("You are not living in India");
15. }
16. }
17. }
Output:
Delhi
Switch Statement:
In Java, 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.
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.
1. switch (expression){
2. case value1:
3. statement1;
4. break;
5. .
6. .
7. .
8. case valueN:
9. statementN;
10. break;
11. default:
12. default statement;
13. }
Consider the following example to understand the flow of the switch statement.
Student.java
1. public class Student implements Cloneable {
2. public static void main(String[] args) {
3. int num = 2;
4. switch (num){
5. case 0:
6. System.out.println("number is 0");
7. break;
8. case 1:
9. System.out.println("number is 1");
10. break;
11. default:
12. System.out.println(num);
13. }
14. }
15. }
Output:
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.
In Java, 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
1. for(initialization, condition, increment/decrement) {
2. //block of statements
3. }
Consider the following example to understand the proper functioning of the for loop
in java.
Calculation.java
1. public class Calculattion {
2. public static void main(String[] args) {
3. // TODO Auto-generated method stub
4. int sum = 0;
5. for(int j = 1; j<=10; j++) {
6. sum = sum + j;
7. }
8. System.out.println("The sum of first 10 natural numbers is " + sum);
9. }
10. }
Output:
1. for(data_type var : array_name/collection_name){
2. //statements
3. }
Consider the following example to understand the functioning of the for-each loop
in Java.
Calculation.java
1. public class Calculation {
2. public static void main(String[] args) {
3. // TODO Auto-generated method stub
4. String[] names = {"Java","C","C++","Python","JavaScript"};
5. System.out.println("Printing the content of the array names:\n");
6. for(String name:names) {
7. System.out.println(name);
8. }
9. }
10. }
Output:
Java
C
C++
Python
JavaScript
1. while(condition){
2. //looping statements
3. }
The flow chart for the while loop is given in the following image.
Calculation .java
1. public class Calculation {
2. public static void main(String[] args) {
3. // TODO Auto-generated method stub
4. int i = 0;
5. System.out.println("Printing the list of first 10 even numbers \n");
6. while(i<=10) {
7. System.out.println(i);
8. i = i + 2;
9. }
10. }
11. }
Output:
0
2
4
6
8
10
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.
1. do
2. {
3. //statements
4. } while (condition);
The flow chart of the do-while loop is given in the following image.
Consider the following example to understand the functioning of the do-while loop
in Java.
Calculation.java
1. public class Calculation {
2. public static void main(String[] args) {
3. // TODO Auto-generated method stub
4. int i = 0;
5. System.out.println("Printing the list of first 10 even numbers \n");
6. do {
7. System.out.println(i);
8. i = i + 2;
9. }while(i<=10);
10. }
11. }
Output:
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.
The break statement cannot be used independently in the Java program, i.e., it can
only be written inside the loop or switch statement.
Consider the following example in which we have used the break statement with the
for loop.
BreakExample.java
1. public class BreakExample {
2.
3. public static void main(String[] args) {
4. // TODO Auto-generated method stub
5. for(int i = 0; i<= 10; i++) {
6. System.out.println(i);
7. if(i==6) {
8. break;
9. }
10. }
11. }
12. }
Output:
0
1
2
3
4
5
6
Calculation.java
1. public class Calculation {
2.
3. public static void main(String[] args) {
4. // TODO Auto-generated method stub
5. a:
6. for(int i = 0; i<= 10; i++) {
7. b:
8. for(int j = 0; j<=15;j++) {
9. c:
10. for (int k = 0; k<=20; k++) {
11. System.out.println(k);
12. if(k==5) {
13. break a;
14. }
15. }
16. }
17.
18. }
19. }
20.
21.
22. }
Output:
0
1
2
3
4
5
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.
1. public class ContinueExample {
2.
3. public static void main(String[] args) {
4. // TODO Auto-generated method stub
5.
6. for(int i = 0; i<= 2; i++) {
7.
8. for (int j = i; j<=5; j++) {
9.
10. if(j == 4) {
11. continue;
12. }
13. System.out.println(j);
14. }
15. }
16. }
17.
18. }
Output:
0
1
2
3
5
1
2
3
5
2
3
5
Java Arrays
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 C/C+
+, we need to use the sizeof operator.
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 objects in an array in Java. Like C/C++, we can also create
single dimentional or multidimentional 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.
1. dataType[] arr; (or)
2. dataType []arr; (or)
3. dataType arr[];
1. 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.
1. //Java Program to illustrate how to declare, instantiate, initialize
2. //and traverse the Java array.
3. class Testarray{
4. public static void main(String args[]){
5. int a[]=new int[5];//declaration and instantiation
6. a[0]=10;//initialization
7. a[1]=20;
8. a[2]=70;
9. a[3]=40;
10. a[4]=50;
11. //traversing array
12. for(int i=0;i<a.length;i++)//length is the property of array
13. System.out.println(a[i]);
14. }}
Test it Now
Output:
10
20
70
40
50
1. int a[]={33,3,4,5};//declaration, instantiation and initialization
1. //Java Program to illustrate the use of declaration, instantiation
2. //and initialization of Java array in a single line
3. class Testarray1{
4. public static void main(String args[]){
5. int a[]={33,3,4,5};//declaration, instantiation and initialization
6. //printing array
7. for(int i=0;i<a.length;i++)//length is the property of array
8. System.out.println(a[i]);
9. }}
Test it Now
Output:
33
3
4
5
1. for(data_type variable:array){
2. //body of the loop
3. }
Let us see the example of print the elements of Java array using the for-each loop.
1. //Java Program to print the array elements using for-each loop
2. class Testarray1{
3. public static void main(String args[]){
4. int arr[]={33,3,4,5};
5. //printing array using for-each loop
6. for(int i:arr)
7. System.out.println(i);
8. }}
Output:
33
3
4
5
Let's see the simple example to get the minimum number of an array using a
method.
1. //Java Program to demonstrate the way of passing an array
2. //to method.
3. class Testarray2{
4. //creating a method which receives an array as a parameter
5. static void min(int arr[]){
6. int min=arr[0];
7. for(int i=1;i<arr.length;i++)
8. if(min>arr[i])
9. min=arr[i];
10.
11. System.out.println(min);
12. }
13.
14. public static void main(String args[]){
15. int a[]={33,3,4,5};//declaring and initializing an array
16. min(a);//passing array to method
17. }}
Test it Now
Output:
dataType[][] arrayRefVar; (or)
dataType [][]arrayRefVar; (or)
dataType arrayRefVar[][]; (or)
dataType []arrayRefVar[];
1. int[][] arr=new int[3][3];//3 row and 3 column
1. arr[0][0]=1;
2. arr[0][1]=2;
3. arr[0][2]=3;
4. arr[1][0]=4;
5. arr[1][1]=5;
6. arr[1][2]=6;
7. arr[2][0]=7;
8. arr[2][1]=8;
9. arr[2][2]=9;
Example of Multidimensional Java Array
Let's see the simple example to declare, instantiate, initialize and print the
2Dimensional array.
1. //Java Program to illustrate the use of multidimensional array
2. class Testarray3{
3. public static void main(String args[]){
4. //declaring and initializing 2D array
5. int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
6. //printing 2D array
7. for(int i=0;i<3;i++){
8. for(int j=0;j<3;j++){
9. System.out.print(arr[i][j]+" ");
10. }
11. System.out.println();
12. }
13. }}
Test it Now
Output:
1 2 3
2 4 5
4 4 5