0% found this document useful (0 votes)
26 views59 pages

Java Unit1 Languagebasics

Java was originally created for television devices but was better suited for internet use. It was developed by James Gosling and team at Sun Microsystems in the 1990s. Java is an object-oriented language that is portable, platform independent and secure. It allows applications to run on any device that supports Java without needing to be recompiled.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
26 views59 pages

Java Unit1 Languagebasics

Java was originally created for television devices but was better suited for internet use. It was developed by James Gosling and team at Sun Microsystems in the 1990s. Java is an object-oriented language that is portable, platform independent and secure. It allows applications to run on any device that supports Java without needing to be recompiled.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 59

History of JAVA

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.

Currently, Java is used in internet programming, mobile devices, games, e-business


solutions, etc. Following are given significant points that describe the history of Java.

1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java


language project in June 1991. The small team of sun engineers called Green Team.

2) Initially it was designed for small, embedded systems in electronic appliances like


set-top boxes.

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.

Why Java was named as "Oak"?


5) Why Oak? Oak is a symbol of strength and chosen as a national tree of many
countries like the U.S.A., France, Germany, Romania, etc.

6) In 1995, Oak was renamed as "Java" because it was already a trademark by Oak


Technologies.

Why Java Programming named "Java"?


7) Why had they chose the name Java for Java language? The team gathered to
choose a new name. The suggested words were "dynamic", "revolutionary", "Silk",
"jolt", "DNA", etc. They wanted something that reflected the essence of the
technology: revolutionary, dynamic, lively, cool, unique, and easy to spell, and fun to
say.

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.

9) Notice that Java is just a name, not an acronym.

10) Initially developed by James Gosling at Sun Microsystems (which is now a


subsidiary of Oracle Corporation) and released in 1995.

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.

Object-oriented programming (OOPs) is a methodology that simplifies software


development and maintenance by providing some rules.

Basic concepts of OOPs are:

1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
Platform Independent

Java is platform independent because it is different from other languages like C, C+


+, etc. which are compiled into platform specific machines while Java is a write once,
run anywhere language. A platform is the hardware or software environment in
which a program runs.

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

o Classloader: Classloader in Java is a part of the Java Runtime Environment (JRE)


which is used to load Java classes into the Java Virtual Machine dynamically. It adds
security by separating the package for the classes of the local file system from those
that are imported from network sources.
o Bytecode Verifier: It checks the code fragments for illegal code that can violate
access rights to objects.
o Security Manager: It determines what resources a class can access such as reading
and writing to the local disk.

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:

o It uses strong memory management.


o There is a lack of pointers that avoids security problems.
o Java provides automatic garbage collection which runs on the Java Virtual Machine to
get rid of objects which are not being used by a Java application anymore.
o There are exception handling and the type checking mechanism in Java. All these
points make Java robust.

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 supports dynamic compilation and automatic memory management (garbage


collection).

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.

Java Architecture can be explained by using the following steps:

o There is a process of compilation and interpretation in Java.


o Java compiler converts the Java code into byte code.
o After that, the JVM converts the byte code into machine code.
o The machine code is then executed by the machine.

The following figure represents the Java Architecture in which each step is


elaborate graphically.
Components of Java Architecture
The Java architecture includes the three main components:

o Java Virtual Machine (JVM)


o Java Runtime Environment (JRE)
o Java Development Kit (JDK)

Java Virtual Machine


The main feature of Java is WORA. WORA stands for Write Once Run Anywhere. The
feature states that we can write our code once and use it anywhere or on any operating
system. Our Java program can run any of the platforms only because of the Java Virtual
Machine. It is a Java platform component that gives us an environment to execute java
programs. JVM's main task is to convert byte code into machine code.

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

Java Native Interface works as a mediator between Java method calls and native
libraries.

Java Runtime Environment


It provides an environment in which Java programs are executed. JRE takes our Java
code, integrates it with the required libraries, and then starts the JVM to execute it

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).

What does JRE consist of?


JRE consists of the following components:

o Deployment technologies such as deployment, Java plug-in, and Java Web


Start.
o User interface toolkits, including Abstract Window Toolkit (AWT), Swing, Java
2D, Accessibility, Image I/O, Print Service, Sound, drag, and drop (DnD) and
input methods.
o Integration libraries including Interface Definition Language (IDL), Java
Database Connectivity (JDBC), Java Naming and Directory Interface (JNDI),
Remote Method Invocation (RMI), Remote Method Invocation Over Internet
Inter-Orb Protocol (RMI-IIOP) and scripting.
o Other base libraries, including international support, input/output (I/O),
extension mechanism, Beans, Java Management Extensions (JMX), Java Native
Interface (JNI), Math, Networking, Override Mechanism, Security, Serialization
and Java for XML Processing (XML JAXP).
o Lang and util base libraries, including lang and util, zip, Java Archive (JAR),
instrument, reflection, Collections, Concurrency Utilities, management,
versioning, Logging, Preferences API, Ref Objects and Regular Expressions.
o Java Virtual Machine (JVM), which comprise of Server Virtual Machine and
Java HotSpot Client.

How does JRE work with JVM?


JRE has an instance of JVM with it, library classes and development tools. 

Java Development Kit


It is a software development environment used in the development of Java
applications and applets. Java Development Kit holds JRE, a compiler, an interpreter
or loader, and several development tools in it.

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:

o Standard Edition Java Platform


o Enterprise Edition Java Platform
o Micro Edition Java Platform

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.

apt: It is an annotation-processing tool.

extcheck: it is a utility that detects JAR file conflicts.

idlj: An IDL-to-Java compiler. This utility generates Java bindings from a


given Java IDL file.

jabswitch: It is a Java Access Bridge. Exposes assistive technologies on Microsoft


Windows systems.

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.

javadoc: The documentation generator, which automatically generates


documentation from source code comments

jar: The specifies the archiver, which packages related class libraries into a
single JAR file. This tool also helps manage JAR files.

javafxpackager It is a tool to package and sign JavaFX applications.


:

jarsigner: the jar signing and verification tool.

javah: the C header and stub generator, used to write native methods.

javap: the class file disassembler.

javaws: the Java Web Start launcher for JNLP applications.

JConsole: Java Monitoring and Management Console.

jdb: the debugger.

jhat: Java Heap Analysis Tool (experimental).

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.

jmc: Java Mission Control

jps: Java Virtual Machine Process Status Tool lists the instrumented HotSpot
Java Virtual Machines (JVMs) on the target system.

jrunscript: Java command-line script shell.

jstack: It is a utility that prints Java stack traces of Java threads (experimental).

jstat: Java Virtual Machine statistics monitoring tool (experimental).


jstatd: jstat daemon (experimental).

keytool: It is a tool for manipulating the keystore.

pack200: JAR compression tool.

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.

VisualVM: It is a visual tool integrating several command-line JDK tools and


lightweight [clarification needed] performance and memory profiling
capabilities

wsimport: It generates portable JAX-WS artifacts for invoking a web service.

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.

Why do we use comments in a code?


o Comments are used to make the program more readable by adding the details of the
code.
o It makes easy to maintain the code and to find the errors easily.
o The comments can be used to provide information or explanation about the variable,
method, class, or any statement.
o It can also be used to prevent the execution of program code while testing the
alternative code.
Types of Java Comments
There are three types of comments in Java.

1. Single Line Comment


2. Multi Line Comment
3. Documentation Comment

1) Java Single Line Comment


The single-line comment is used to comment only one line of the code. It is the
widely used and easiest way of commenting the statements.

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  

Let's use single line comment in a Java program.

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

2) Java Multi Line Comment


The multi-line comment is used to comment multiple lines of code. It can be used to
explain a complex code snippet or to comment multiple lines of code at a time (as it
will be difficult to use single-line comments there).

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. */    

Let's use multi-line comment in a Java program.

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

3) Java Documentation Comment


Documentation comments are usually used to write large programs for a project or
software application as it helps to create documentation API. These APIs are needed
for reference, i.e., which classes, methods, arguments, etc., are used in the code.

To create documentation API, we need to use the javadoc tool. The documentation


comments are placed between /** and */.

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. */    

Data Types in Java


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.

Java Primitive Data Types


In Java language, primitive data types are the building blocks of data manipulation.
These are the most basic data types available in Java language.

There are 8 types of primitive data types:


o boolean data type
o byte data type
o char data type
o short data type
o int data type
o long data type
o float data type
o double data type

Data Type Default Value Default size

boolean false 1 bit

char '\u0000' 2 byte

byte 0 1 byte

short 0 2 byte

int 0 4 byte
long 0L 8 byte

float 0.0f 4 byte

double 0.0d 8 byte

Boolean Data Type


The Boolean data type is used to store only two possible values: true and false. This
data type is used for simple flags that track true/false conditions.

The Boolean data type specifies one bit of information, but its "size" can't be defined
precisely.

Example:

1. Boolean one = false  

Byte Data Type


The byte data type is an example of primitive data type. It isan 8-bit signed two's
complement integer. Its value-range lies between -128 to 127 (inclusive). Its
minimum value is -128 and maximum value is 127. Its default value is 0.

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  

Short Data Type


The short data type is a 16-bit signed two's complement integer. Its value-range lies
between -32,768 to 32,767 (inclusive). Its minimum value is -32,768 and maximum
value is 32,767. Its default value is 0.

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  

Long Data Type


The long data type is a 64-bit two's complement integer. Its value-range lies between
-9,223,372,036,854,775,808(-2^63) to 9,223,372,036,854,775,807(2^63 -1)(inclusive).
Its minimum value is - 9,223,372,036,854,775,808and maximum value is
9,223,372,036,854,775,807. Its default value is 0. The long data type is used when you
need a range of values more than those provided by int.

Example:

1. long a = 100000L, long b = -200000L  

Float Data Type


The float data type is a single-precision 32-bit IEEE 754 floating point.Its value range
is unlimited. It is recommended to use a float (instead of double) if you need to save
memory in large arrays of floating point numbers. The float data type should never
be used for precise values, such as currency. Its default value is 0.0F.

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  

Char Data Type


The char data type is a single 16-bit Unicode character. Its value-range lies between
'\u0000' (or 0) to '\uffff' (or 65,535 inclusive).The char data type is used to store
characters.

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 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 in java


1. public class A  
2. {  
3.     static int m=100;//static variable  
4.     void method()  
5.     {    
6.         int n=90;//local variable    
7.     }  
8.     public static void main(String args[])  
9.     {  
10.         int data=50;//instance variable    
11.     }  
12. }//end of class   

Java Variable Example: Add Two Numbers


1. public class Simple{    
2. public static void main(String[] args){    
3. int a=10;    
4. int b=10;    
5. int c=a+b;    
6. System.out.println(c);    
7. }  
8. }    

Output:
20

Java Variable Example: Widening


1. public class Simple{  
2. public static void main(String[] args){  
3. int a=10;  
4. float f=a;  
5. System.out.println(a);  
6. System.out.println(f);  
7. }}  

Output:

10
10.0

Java Variable Example: Narrowing (Typecasting)


1. public class Simple{  
2. public static void main(String[] args){  
3. float f=10.5f;  
4. //int a=f;//Compile time error  
5. int a=(int)f;  
6. System.out.println(f);  
7. System.out.println(a);  
8. }}  

Output:

10.5
10

Java Variable Example: Overflow


1. class Simple{  
2. public static void main(String[] args){  
3. //Overflow  
4. int a=130;  
5. byte b=(byte)a;  
6. System.out.println(a);  
7. System.out.println(b);  
8. }}  

Output:
130
-126

Java Variable Example: Adding Lower Type


1. class Simple{  
2. public static void main(String[] args){  
3. byte a=10;  
4. byte b=10;  
5. //byte c=a+b;//Compile Time Error: because a+b=20 will be int  
6. byte c=(byte)(a+b);  
7. System.out.println(c);  
8. }}  

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.

Java Operator Precedence


Operator Type Category Precedence

Unary postfix expr++ expr--


prefix ++expr --expr +expr -expr ~ !

Arithmetic multiplicative * / %

additive + -

Shift shift << >> >>>

Relational comparison < > <= >= instanceof

equality == !=

Bitwise bitwise AND &

bitwise exclusive OR ^

bitwise inclusive OR |

Logical logical AND &&

logical OR ||

Ternary ternary ? :

Assignment assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=

Java Unary Operator


The Java 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

Java Unary Operator Example: ++ and --


1. public class OperatorExample{  
2. public static void main(String args[]){  
3. int x=10;  
4. System.out.println(x++);//10 (11)  
5. System.out.println(++x);//12  
6. System.out.println(x--);//12 (11)  
7. System.out.println(--x);//10  
8. }}  

Output:

10
12
12
10

Java Unary Operator Example 2: ++ and --


1. public class OperatorExample{  
2. public static void main(String args[]){  
3. int a=10;  
4. int b=10;  
5. System.out.println(a++ + ++a);//10+12=22  
6. System.out.println(b++ + b++);//10+11=21  
7.   
8. }}  

Output:

22
21

Java Unary Operator Example: ~ and !


1. public class OperatorExample{  
2. public static void main(String args[]){  
3. int a=10;  
4. int b=-10;  
5. boolean c=true;  
6. boolean d=false;  
7. System.out.println(~a);//-11 (minus of total positive value which starts from 0)  
8. System.out.println(~b);//9 (positive of total minus, positive starts from 0)  
9. System.out.println(!c);//false (opposite of boolean value)  
10. System.out.println(!d);//true  
11. }}  

Output:
-11
9
false
true

Java Arithmetic Operators


Java arithmetic operators are used to perform addition, subtraction, multiplication,
and division. They act as basic mathematical operations.

Java Arithmetic Operator Example


1. public class OperatorExample{  
2. public static void main(String args[]){  
3. int a=10;  
4. int b=5;  
5. System.out.println(a+b);//15  
6. System.out.println(a-b);//5  
7. System.out.println(a*b);//50  
8. System.out.println(a/b);//2  
9. System.out.println(a%b);//0  
10. }}  

Output:

15
5
50
2
0

Java Arithmetic Operator Example: Expression


1. public class OperatorExample{  
2. public static void main(String args[]){  
3. System.out.println(10*10/5+3-1*4/2);  
4. }}  

Output:

21

Java Left Shift Operator


The Java left shift operator << is used to shift all of the bits in a value to the left side
of a specified number of times.
Java Left Shift Operator Example
1. public class OperatorExample{  
2. public static void main(String args[]){  
3. System.out.println(10<<2);//10*2^2=10*4=40  
4. System.out.println(10<<3);//10*2^3=10*8=80  
5. System.out.println(20<<2);//20*2^2=20*4=80  
6. System.out.println(15<<4);//15*2^4=15*16=240  
7. }}  

Output:

40
80
80
240

Java Right Shift Operator


The Java 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.

Java Right Shift Operator Example


1. public OperatorExample{  
2. public static void main(String args[]){  
3. System.out.println(10>>2);//10/2^2=10/4=2  
4. System.out.println(20>>2);//20/2^2=20/4=5  
5. System.out.println(20>>3);//20/2^3=20/8=2  
6. }}  

Output:

2
5
2

Java Shift Operator Example: >> vs >>>


1. public class OperatorExample{  
2. public static void main(String args[]){  
3.     //For positive number, >> and >>> works same  
4.     System.out.println(20>>2);  
5.     System.out.println(20>>>2);  
6.     //For negative number, >>> changes parity bit (MSB) to 0  
7.     System.out.println(-20>>2);  
8.     System.out.println(-20>>>2);  
9. }}  

Output:

5
5
-5
1073741819

Java 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.

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

Java AND Operator Example: Logical && vs Bitwise &


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);//10 because second condition is not checked  
8. System.out.println(a<b&a++<c);//false && true = false  
9. System.out.println(a);//11 because second condition is checked  
10. }}  
Output:

false
10
false
11

Java OR Operator Example: Logical || and Bitwise |


The logical || operator doesn't check the second condition if the first condition is
true. It checks the second condition only if the first one is false.

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

Java Ternary Operator


Java 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.

Java Ternary Operator Example


1. public class OperatorExample{  
2. public static void main(String args[]){  
3. int a=2;  
4. int b=5;  
5. int min=(a<b)?a:b;  
6. System.out.println(min);  
7. }}  

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:

Java Assignment Operator


Java 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.

Java Assignment Operator Example


1. public class OperatorExample{  
2. public static void main(String args[]){  
3. int a=10;  
4. int b=20;  
5. a+=4;//a=a+4 (a=10+4)  
6. b-=4;//b=b-4 (b=20-4)  
7. System.out.println(a);  
8. System.out.println(b);  
9. }}  

Output:
14
16

Java Assignment Operator Example


1. public class OperatorExample{  
2. public static void main(String[] args){  
3. int a=10;  
4. a+=3;//10+3  
5. System.out.println(a);  
6. a-=4;//13-4  
7. System.out.println(a);  
8. a*=2;//9*2  
9. System.out.println(a);  
10. a/=2;//18/2  
11. System.out.println(a);  
12. }}  

Output:

13
9
18
9

Java Assignment Operator Example: Adding short


1. public class OperatorExample{  
2. public static void main(String args[]){  
3. short a=10;  
4. short b=10;  
5. //a+=b;//a=a+b internally so fine  
6. a=a+b;//Compile time error because 10+10=20 now int  
7. System.out.println(a);  
8. }}  

Output:

Compile time error

After type cast:

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

Type Casting and Type Conversion:

The two terms type casting and the type conversion are used in a program to


convert one data type to another data type. The conversion of data type is possible
only by the compiler when they are compatible with each other. Let's discuss the
difference between type casting and type conversion in any programming language.

What is a type casting?


When a data type is converted into another data type by a programmer or user while
writing a program code of any programming language, the mechanism is known
as type casting. The programmer manually uses it to convert one data type into
another. It is used if we want to change the target data type to another data type.
Remember that the destination data type must be smaller than the source data type.
Hence it is also called a narrowing conversion.

Syntax:

1. Destination_datatype = (target_datatype) variable;  
2. (data_type) it is known as casting operator  

Target_datatype: It is the data type in which we want to convert the destination


data type. The variable defines a value that is to be converted in the target_data type.
Let's understand the concept of type casting with an example.
Suppose, we want to convert the float data type into int data type. Here, the target
data type is smaller than the source data because the size of int is 2 bytes, and the
size of the float data type is 4 bytes. And when we change it, the value of the float
variable is truncated and convert into an integer variable. Casting can be done with a
compatible and non-compatible data type.

1. float b = 3.0;  
2. int a = (int) b; // converting a float value into integer  

Let's understand the type casting through a C program.

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:

What is type conversion?


If a data type is automatically converted into another data type at compile time is
known as type conversion. The conversion is performed by the compiler if both data
types are compatible with each other. Remember that the destination data type
should not be smaller than the source type. It is also known as widening conversion
of the data type.

Let's understand the type conversion with an example.

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.

Let's understand type conversion through a C program.

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:

Difference Between Type Casting and Type Conversion


S.N. Type Casting Type Conversion

1 Type casting is a mechanism in which Type conversion allows a compiler to convert


one data type is converted to another one data type to another data type at the
data type using a casting () operator by a compile time of a program or code.
programmer.

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.

3 It requires a programmer to manually It does not require any programmer intervention


casting one data into another type. to convert one data type to another because the
compiler automatically compiles it at the run
time of a program.

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.

6 It is also known as narrowing conversion It is also known as widening conversion because


because one larger data type converts to one smaller data type converts to a larger data
a smaller data type. type.

7 It is more reliable and efficient. It is less efficient and less reliable.

8 There is a possibility of data or In type conversion, data is unlikely to be lost


information being lost in type casting. when converting from a small to a large data
type.

9 float b = 3.0; int x = 5, y = 2, c;


int a = (int) b float q = 12.5, p;
p = q/x;

Java Control Statements | Control Flow in


Java
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.

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

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:

1. if(condition) {    
2. statement 1; //executes when condition is true   
3. }  
4. else{  
5. statement 2; //executes when condition is false   
6. }  

Consider the following example.

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:

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.

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. }  

Consider the following example.

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

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.

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. }  

Consider the following example.

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.

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.

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

Let's understand the loop statements one by one.

Java 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.

1. for(initialization, condition, increment/decrement) {    
2. //block of statements    
3. }    

The flow chart for the for-loop is given below.

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:

The sum of first 10 natural numbers is 55


Java 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.

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:

Printing the content of the array names:

Java
C
C++
Python
JavaScript

Java 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.

1. while(condition){    
2. //looping statements    
3. }    

The flow chart for the while loop is given in the following image.

Consider the following example.

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:

Printing the list of first 10 even numbers

0
2
4
6
8
10

Java 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.

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:

Printing the list of first 10 even numbers


0
2
4
6
8
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.

Java 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

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

break statement example with labeled for loop

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.

Consider the following example to understand the functioning of the continue


statement in Java.

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.

Types of Array in java


There are two types of array.
o Single Dimensional Array
o Multidimensional Array

Single Dimensional Array in Java


Syntax to Declare an Array in Java

1. dataType[] arr; (or)  
2. dataType []arr; (or)  
3. dataType arr[];  

Instantiation of an Array in Java

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

Declaration, Instantiation and Initialization of


Java Array
We can declare, instantiate and initialize the java array together by:

1. int a[]={33,3,4,5};//declaration, instantiation and initialization  

Let's see the simple example to print this array.

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

For-each Loop for Java 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:

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

Passing Array to a Method in Java


We can pass the java array to method so that we can reuse the same logic on any
array.

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:

Multidimensional Array in Java


In such case, data is stored in row and column based index (also known as matrix
form).

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

1. int[][] arr=new int[3][3];//3 row and 3 column  

Example to initialize Multidimensional Array in Java

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

You might also like