You are on page 1of 106

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.
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:
•Java syntax is based on C++ (so easier for programmers to learn it after C++).
•Java has removed many complicated and rarely-used features, for example, explicit pointers, operator
overloading, etc.
•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:
Object
Class
Inheritance
Polymorphism
Abstraction
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)
Secured
Java is best known for its security. With Java, we can develop virus-free systems. Java is secured because:
•No explicit pointer
•Java Programs run inside a virtual machine sandbox

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).
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.
Bytecode Verifier: It checks the code fragments for illegal code that can violate access rights to
objects.
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:
•It uses strong memory management.
•There is a lack of pointers that avoids security problems.
•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.
•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++.
Importance and features of Java

Java is one of the most popular programming languages used to create Web applications and
platforms. It was designed for flexibility, allowing developers to write code that would run on
any machine, regardless of architecture or platform. According to the Java home page, more
than 1 billion computers and 3 billion mobile phones worldwide run Java.
The importance of Java that highlights it among other programming languages
Mobile Applications
For the development of mobile apps, Java is the preferred programming language. It works with
Kotlin and Android Studio, among other software. You’re probably thinking why only Java
programming language.
The reason for this is that it can operate on the Java Virtual Machine, but Android executes class
files using the Dalvik Virtual Machine. These files are then packaged together as an Android
application package commonly known as apk. With Java and its OOPs principles, Android has a
higher level of security and accessibility.
● Web-based Applications
It’s also used to create web-based applications. And because of the wide support for web
development via Struts, JSP, and Servlet. Java considers as a server-side computer language for
this reason.
We can create a wide range of apps using these features. Hibernate, Spring, and Spring Boot are
the most common frameworks for constructing web-based apps. Popular websites that use Java
are IRCTC, LinkedIn, AliExpress, and others.

Scientific Applications
When it comes to scientific computations and mathematical processes, software engineers
consider Java programming language as the weapon of choice. These programs are intended to
be extremely safe and quick.
They have a higher degree of mobility and require less maintenance. Java can combine with
some of the most capable software, such as MATLAB, for both the engaging user interface and
the core system.
Game development
Because it is supported by the open-source most compelling 3D technology, Java is commonly
applied by game production companies. When it comes to building 3D games, the engine has
unmatched capabilities.
Minecraft, MI III, and other Java-based games are among the most popular. For developing
games, various well-known frameworks and libraries are present. And these are such as OpenGL
and LibGDX.
How JVM Works – JVM Architecture?

The JVM consists of three distinct components: Class Loader. Runtime Memory/Data Area.
Execution Engine.
What is the use of JVM in Java?

Java Virtual Machine, or JVM, loads, verifies and executes Java byte code. It is known as the
interpreter or the core of Java programming language because it executes Java programming.

JVM(Java Virtual Machine) acts as a run-time engine to run Java applications. JVM is the one
that actually calls the main method present in a java code. JVM is a part of JRE(Java
Runtime Environment).

Java applications are called WORA (Write Once Run Anywhere). This means a programmer can
develop Java code on one system and can expect it to run on any other Java-enabled system
without any adjustment. This is all possible because of JVM.

When we compile a .java file, .class files(contains byte-code) with the same class names present
in .java file are generated by the Java compiler. This .class file goes into various steps when we
run it. These steps together describe the whole JVM.
What is JVM

A specification where working of Java Virtual Machine is specified. But implementation provider
is independent to choose the algorithm. Its implementation has been provided by Oracle and
other companies.
An implementation Its implementation is known as JRE (Java Runtime Environment).
Runtime Instance Whenever you write java command on the command prompt to run the java
class, an instance of JVM is created.
What it does
The JVM performs following operation:
Loads code
Verifies code
Executes code
Provides runtime environment
JVM provides definitions for the:
Memory area
Class file format
Register set
Garbage-collected heap
Fatal error reporting etc.
1) Classloader
Class Loader Subsystem
Classloader is a subsystem of JVM which is used to load class files. Whenever we run the java
program, it is loaded first by the classloader. There are three built-in classloaders in Java.
Bootstrap ClassLoader: This is the first classloader which is the super class of Extension
classloader. It loads the rt.jar file which contains all class files of Java Standard Edition like
java.lang package classes, java.net package classes, java.util package classes, java.io package
classes, java.sql package classes etc.
Extension ClassLoader: This is the child classloader of Bootstrap and parent classloader of
System classloader. It loades the jar files located inside $JAVA_HOME/jre/lib/ext directory.
System/Application ClassLoader: This is the child classloader of Extension classloader. It loads
the classfiles from classpath. By default, classpath is set to current directory. You can change the
classpath using "-cp" or "-classpath" switch. It is also known as Application classloader.

It is mainly responsible for three activities.


Loading
Linking
Initialization
Loading: The Class loader reads the “.class” file, generate the corresponding binary data and
save it in the method area. For each “.class” file, JVM stores the following information in the
method area.
The fully qualified name of the loaded class and its immediate parent class.
Whether the “.class” file is related to Class or Interface or Enum.
Modifier, Variables and Method information etc.
After loading the “.class” file, JVM creates an object of type Class to represent this file in the
heap memory. Please note that this object is of type Class predefined in java.lang package.
These Class object can be used by the programmer for getting class level information like the
name of the class, parent name, methods and variable information etc. To get this object
reference we can use getClass() method of Object class.
Linking: Performs verification, preparation, and (optionally) resolution.

Verification: It ensures the correctness of the .class file i.e. it checks whether this file is properly
formatted and generated by a valid compiler or not. If verification fails, we get run-time
exception java.lang.VerifyError. This activity is done by the component ByteCodeVerifier. Once
this activity is completed then the class file is ready for compilation.
Preparation: JVM allocates memory for class variables and initializing the memory to default
values.
Resolution: It is the process of replacing symbolic references from the type with direct
references. It is done by searching into the method area to locate the referenced entity.
Initialization: In this phase, all static variables are assigned with their values defined in the code
and static block(if any). This is executed from top to bottom in a class and from parent to child in
the class hierarchy.
In general, there are three class loaders :
Bootstrap class loader: Every JVM implementation must have a bootstrap class loader, capable
of loading trusted classes. It loads core java API classes present in the “JAVA_HOME/jre/lib”
directory. This path is popularly known as the bootstrap path. It is implemented in native
languages like C, C++.
Extension class loader: It is a child of the bootstrap class loader. It loads the classes present in
the extensions directories
“JAVA_HOME/jre/lib/ext”(Extension path) or any other directory specified by the java.ext.dirs
system property. It is implemented in java by the sun.misc.Launcher$ExtClassLoader class.
System/Application class loader: It is a child of the extension class loader. It is responsible to load
classes from the application classpath. It internally uses Environment Variable which mapped to
java.class.path. It is also implemented in Java by the sun.misc.Launcher$AppClassLoader class.
Java Language Keywords

A Java keyword is one of 50 reserved terms that have a special function and a set definition
in the Java programming language. The fact that the terms are reserved means that they
cannot be used as identifiers for any other program elements, including classes,
subclasses, variables, methods and objects.

Here is a list of keywords in the Java programming language. You cannot use any of the following as
identifiers in your programs. The keywords const and goto are reserved, even though they are not
currently used. true, false, and null might seem like keywords, but they are actually literals; you cannot
use them as identifiers in your programs.
Keyword Description
A non-access modifier. Used for classes and methods: An
abstract class cannot be used to create objects (to access it,
it must be inherited from another class). An abstract
abstract
method can only be used in an abstract class, and it does
not have a body. The body is provided by the subclass
(inherited from)
assert For debugging
boolean A data type that can only store true and false values
break Breaks out of a loop or a switch block
A data type that can store whole numbers from -128 and
byte
127
case Marks a block of code in switch statements

catch Catches exceptions generated by try statements

char A data type that is used to store a single character

class Defines a class

continue Continues to the next iteration of a loop

const Defines a constant. Not in use - use final instead

default Specifies the default block of code in a switch statement

do Used together with while to create a do-while loop

A data type that can store whole numbers from 1.7e−308


double to 1.7e+308

else Used in conditional statements

enum Declares an enumerated (unchangeable) type

exports Exports a package with a module. New in Java 9


extends Extends a class (indicates that a class is inherited from another class)

A non-access modifier used for classes, attributes and methods,


final which makes them non-changeable (impossible to inherit or
override)

Used with exceptions, a block of code that will be executed no matter


finally if there is an exception or not

float A data type that can store whole numbers from 3.4e−038 to 3.4e+038
for Create a for loop
goto Not in use, and has no function
if Makes a conditional statement
implements Implements an interface
import Used to import a package, class or interface
Checks whether an object is an instance of a specific class or an
instanceof interface
A data type that can store whole numbers from -2147483648 to
int 2147483647
Used to declare a special type of class that only contains abstract
interface methods
A data type that can store whole numbers from -
long 9223372036854775808 to 9223372036854775808
module Declares a module. New in Java 9
Specifies that a method is not implemented in the same Java source
native file (but in another language)
new Creates new objects
package Declares a package

An access modifier used for attributes, methods and constructors,


private making them only accessible within the declared class

An access modifier used for attributes, methods and constructors,


protected making them accessible in the same package and subclasses
An access modifier used for classes, attributes, methods
public and constructors, making them accessible by any other
class
requires Specifies required libraries inside a module. New in Java 9
Finished the execution of a method, and can be used to
return
return a value from a method
A data type that can store whole numbers from -32768 to
short
32767
A non-access modifier used for methods and attributes.
static Static methods/attributes can be accessed without creating
an object of a class
Restrict the precision and rounding of floating point
strictfp calculations
super Refers to superclass (parent) objects
switch Selects one of many code blocks to be executed
synchronized A non-access modifier, which specifies that methods can
only be accessed by one thread at a time
this Refers to the current object in a method or constructor
throw Creates a custom error
throws Indicates what exceptions may be thrown by a method
A non-accesss modifier, which specifies that an attribute is
transient
not part of an object's persistent state
try Creates a try...catch statement
var Declares a variable. New in Java 10
void Specifies that a method should not have a return value
Indicates that an attribute is not cached thread-locally, and
volatile
is always read from the "main memory"
while Creates a while loop
Note: true, false, and null are not keywords, but they are literals and reserved words that cannot be
used as identifiers.

abstract continue for new switch


assert*** default goto* package synchronized
boolean do if private this
break double implements protected throw
byte else import public throws
case enum**** instanceof return transient
catch extends int short try
char final interface static void
class finally long strictfp** volatile
const* float native super while
*
not used
**
added in 1.2
***
added in 1.4
****
added in 5.0
Java Constant

As the name suggests, a constant is an entity in programming that is immutable. In other


words, the value that cannot be changed. In this section, we will learn about Java constant
and how to declare a constant in Java.
What is constant?
Constant is a value that cannot be changed after assigning it. Java does not directly support
the constants. There is an alternative way to define the constants in Java by using the non-
access modifiers static and final.
How to declare constant in Java?
In Java, to declare any variable as constant, we use static and final modifiers. It is also
known as non-access modifiers. According to the Java naming convention the identifier
name must be in capital letters.
Static and Final Modifiers
The purpose to use the static modifier is to manage the memory.
It also allows the variable to be available without loading any instance of the class in which
it is defined.
The final modifier represents that the value of the variable cannot be changed. It also makes
the primitive data type immutable or unchangeable.
The syntax to declare a constant is as follows:

static final datatype identifier_name=value;


For example, price is a variable that we want to make constant.

static final double PRICE=432.78;


Where static and final are the non-access modifiers. The double is the data type and PRICE is the
identifier name in which the value 432.78 is assigned.
In the above statement, the static modifier causes the variable to be available without an
instance of its defining class being loaded and the final modifier makes the variable fixed.
Here a question arises that why we use both static and final modifiers to declare a constant?
If we declare a variable as static, all the objects of the class (in which constant is defined) will be
able to access the variable and can be changed its value. To overcome this problem, we use the
final modifier with a static modifier.
When the variable defined as final, the multiple instances of the same constant value will be
created for every different object which is not desirable.
When we use static and final modifiers together, the variable remains static and can be
initialized once. Therefore, to declare a variable as constant, we use both static and final
modifiers. It shares a common memory location for all objects of its containing class.
Why we use constants?
The use of constants in programming makes the program easy and understandable which can be
easily understood by others. It also affects the performance because a constant variable is
cached by both JVM and the application.
Example 1: Declaring Constant as Private
ConstantExample1.java
import java.util.Scanner;
public class ConstantExample1
{
//declaring constant
private static final double PRICE=234.90;
public static void main(String[] args)
{
int unit;
double total_bill;
System.out.print("Enter the number of units you have used: ");
Scanner sc=new Scanner(System.in);
unit=sc.nextInt();
total_bill=PRICE*unit;
System.out.println("The total amount you have to deposit is: "+total_bill);
}
}
Declaring Constant as Public
In the following example, we have declared constant PI as public. Inside the main() method, we
have assigned 3.15 in the constant PI. After that, we have invoked the printValue() method.
When we execute the program, it shows an error cannot assign a value to the final variable PI.
ConstantExample3.java
public class ConstantExample3
{
//declaring PI as constant
public static final double PI= 3.14;
public static void main(String[] args)
{
printValue();
//trying to assign 3.15 in the constant PI
PI = 3.15;
printValue();
}
void printValue()
{
System.out.print("The value of PI cannot be changed to " + PI);
}
}
Java Variables and Data Types with EXAMPLE

What is a Variable in Java?


Variable in Java is a data container that stores the data values during Java program execution.
Every variable is assigned data type which designates the type and quantity of value it can hold.
Variable is a memory location name of the data. The Java variables have mainly three types :
Local, Instance and Static.
In order to use a variable in a program you to need to perform 2 steps
Variable Declaration
Variable Initialization
Variable Declaration:
To declare a variable, you must specify the data type & give the variable a unique name.
Examples of other Valid Declarations are
int a,b,c; float pi; double d; char a;
Variable Initialization:
To initialize a variable, you must assign it a valid value.
Types of variables
In Java, there are three types of variables:
Local Variables
Instance Variables
Static Variables
1) Local Variables
Local Variables are a variable that are declared inside the body of a method. 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 Variables
Instance variables are defined without the STATIC keyword .They are defined Outside a
method declaration. They are Object specific and are known as instance variables.
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 Variables
Static variables are initialized only once, at the start of the program execution. These
variables should be initialized first, before the initialization of any instance variables.
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

public class A
{
static int m=100;//static variable
void method()
{
int n=90;//local variable
}
public static void main(String args[])
{
int data=50;//instance variable
}
}//end of class
Java Variable Example: Add Two Numbers

public class Simple{


public static void main(String[] args){
int a=10;
int b=10;
int c=a+b;
System.out.println(c);
}
}
What is Data Types in Java?
Data Types in Java are defined as specifiers that allocate different sizes and types of values that
can be stored in the variable or an identifier. Java has a rich set of data types. Data types in Java
can be divided into two parts :
Primitive Data Types :- which include integer, character, boolean, and float
Non-primitive Data Types :- which include classes, arrays and interfaces.
Primitive Data Types
Primitive Data Types are predefined and available within the Java language. Primitive values do not share state with
other primitive values.
There are 8 primitive types: byte, short, int, long, char, float, double, and boolean
Integer data types
byte (1 byte) short (2 bytes) int (4 bytes) long (8 bytes)

Floating Data Type


float (4 bytes) double (8 bytes)
Textual Data Type
char (2 bytes)
Logical
boolean (1 byte) (true/false)
Java Data Types
Data Type Default Value Default size
byte 0 1 byte
short 0 2 bytes
int 0 4 bytes
long 0L 8 bytes
float 0.0f 4 bytes
double 0.0d 8 bytes
boolean false 1 bit
char ‘\u0000’ 2 bytes
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:
Unary Operator,
Arithmetic Operator,
Shift Operator,
Relational Operator,
Bitwise Operator,
Logical Operator, Operator Type Category Precedence
Ternary Operator and postfix expr++ expr--
Unary
Assignment Operator. prefix ++expr --expr +expr -expr ~ !

multiplicative */%
Java Operator Precedence Arithmetic
additive +-
Shift shift << >> >>>

comparison < > <= >= instanceof


Relational
equality == !=
bitwise AND &

Bitwise bitwise exclusive OR ^

bitwise inclusive OR |
logical AND &&
Logical
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.:

incrementing/decrementing a value by one


negating an expression
inverting the value of a boolean

Java Unary Operator Example: ++ and --


public class OperatorExample{
public static void main(String args[]){
int x=10;
System.out.println(x++);//10 (11)
System.out.println(++x);//12
System.out.println(x--);//12 (11)
System.out.println(--x);//10
}}

Output:
10 12 12 10
1. Arithmetic Operators: They are used to perform simple arithmetic operations on primitive
data types.
* : Multiplication
/ : Division
% : Modulo
+ : Addition
– : Subtraction
2. Unary Operators: Unary operators need only one operand. They are used to increment,
decrement or negate a value.
– : Unary minus, used for negating the values.
+ : Unary plus indicates the positive value (numbers are positive without this, however). It
performs an automatic conversion to int when the type of its operand is the byte, char, or short.
This is called unary numeric promotion.
++ : Increment operator, used for incrementing the value by 1. There are two varieties of
increment operators.
Post-Increment: Value is first used for computing the result and then incremented.
Pre-Increment: Value is incremented first, and then the result is computed.
— : Decrement operator, used for decrementing the value by 1. There are two varieties of
decrement operators.
Post-decrement: Value is first used for computing the result and then decremented.
Pre-Decrement: Value is decremented first, and then the result is computed.
! : Logical not operator, used for inverting a boolean value.
3. Assignment Operator: ‘=’ Assignment operator is used to assigning a value to any
variable. It has a right to left associativity, i.e. value given on the right-hand side of the
operator is assigned to the variable on the left, and therefore right-hand side value must
be declared before using it or should be a constant.
The general format of the assignment operator is:
variable = value;
In many cases, the assignment operator can be combined with other operators to build a
shorter version of the statement called a Compound Statement. For example, instead
of a = a+5, we can write a += 5.
•+=, for adding left operand with right operand and then assigning it to the variable on
the left.
•-=, for subtracting right operand from left operand and then assigning it to the variable
on the left.
•*=, for multiplying left operand with right operand and then assigning it to the variable on
the left.
•/=, for dividing left operand by right operand and then assigning it to the variable on the
left.
•%=, for assigning modulo of left operand by right operand and then assigning it to the
variable on the left.
4. Relational Operators: These operators are used to check for relations like equality,
greater than, and less than. They return boolean results after the comparison and are
extensively used in looping statements as well as conditional if-else statements. The
general format is,
variable relation_operator value
•Some of the relational operators are-
•==, Equal to returns true if the left-hand side is equal to the right-hand side.
•!=, Not Equal to returns true if the left-hand side is not equal to the right-hand side.
•<, less than: returns true if the left-hand side is less than the right-hand side.
•<=, less than or equal to returns true if the left-hand side is less than or equal to
the right-hand side.
•>, Greater than: returns true if the left-hand side is greater than the right-hand
side.
•>=, Greater than or equal to returns true if the left-hand side is greater than or
equal to the right-hand side.
5. Logical Operators: These operators are used to perform “logical AND” and “logical
OR” operations, i.e., a function similar to AND gate and OR gate in digital electronics.
One thing to keep in mind is the second condition is not evaluated if the first one is false,
i.e., it has a short-circuiting effect. Used extensively to test for several conditions for
making a decision. Java also has “Logical NOT”, which returns true when the condition
is false and vice-versa
Conditional operators are:
•&&, Logical AND: returns true when both conditions are true.
•||, Logical OR: returns true if at least one condition is true.
•!, Logical NOT: returns true when a condition is false and vice-versa

6. Ternary operator: Ternary operator is a shorthand version of the if-else statement. It


has three operands and hence the name ternary.
The general format is:
condition ? if true : if false
The above statement means that if the condition evaluates to true, then execute the
statements after the ‘?’ else execute the statements after the ‘:’.
7. Bitwise Operators: These operators are used to perform the manipulation of
individual bits of a number. They can be used with any of the integer types. They are
used when performing update and query operations of the Binary indexed trees.
•&, Bitwise AND operator: returns bit by bit AND of input values.
•|, Bitwise OR operator: returns bit by bit OR of input values.
•^, Bitwise XOR operator: returns bit-by-bit XOR of input values.
•~, Bitwise Complement Operator: This is a unary operator which returns the one’s
complement representation of the input value, i.e., with all bits inverted.

8. Shift Operators: These operators are used to shift the bits of a number left or right,
thereby multiplying or dividing the number by two, respectively. They can be used when
we have to multiply or divide a number by two. General format-
number shift_op number_of_places_to_shift;
•<<, Left shift operator: shifts the bits of the number to the left and fills 0 on voids left
as a result. Similar effect as multiplying the number with some power of two.
•>>, Signed Right shift operator: shifts the bits of the number to the right and fills 0 on
voids left as a result. The leftmost bit depends on the sign of the initial number. Similar
effect as dividing the number with some power of two.
•>>>, Unsigned Right shift operator: shifts the bits of the number to the right and fills 0
on voids left as a result. The leftmost bit is set to 0.
9. instanceof operator: The instance of the operator is used for type checking. It can be
used to test if an object is an instance of a class, a subclass, or an interface. General format-
object instance of class/subclass/interface
Control Statements:
Control Statements are used to control the execution flow of the program.
There are three types of control statements:
Conditional Control Statements
Looping Control Statements
Unconditional Control Statements/Jump Statements
Conditional Control Statements
Conditional Control Statements allows the program to select between the alternatives during
the program execution.
They are also called as decision-making statements or selection statements.
1. If statement
It will go inside the block only if the condition is true otherwise, it will not execute the block.
if(condition){
// statements (if Block)
}
//other statements
• Below flow chart shows the condition of if block execution.
Execution Flow Chart of If Statement
2. If-Else Statement
If the condition is true then, it will execute the If block. Otherwise, it will execute the Else block.
if(condition){
// statements (if Block)
}
else{
// statements (Else block)
}
3. If Else-If statement
If the condition is true, then it will execute the If block. Otherwise, it will execute the Else-If
block. Again, if the condition is not met, then it will move to the else block.
if(condition){
// statements (if Block)
}
else if{
// statements (Else-If block)
}
else{
//statements(Else Block)
}//other statements
Execution flow chart of If Else-If Statement
Program to understand If statements
class WriteExample{
public static void main(String []args){
int a=2; int b=3; int c=4;
if(a>b){
System.out.print(“Institute1”);
}
else if(a>c){
System.out.print(“Institute2”);
}
else{
System.out.print(“Intellipaat”);
}
}
}
Output:
Intellipaat
4. Switch Statement
Switch statement allows program to select one action among multiple actions during the
program execution.
Syntax:
Switch(variable/value/expression){
Case :
// statements [];
Case : Program to understand switch statement:
// statements []; class WriteExample{
… public static void main(String []args){
default: int choice=2; int a=1;
// statements []; switch(choice){
} case a:
System.out.print(“For Right Study”); break;
case choice:
System.out.print(“Intellipaat Trainings”); break;
default:
System.out.print(“No choice found”); break;
}
}}
}
Output: Intellipaat Trainings
Looping Control Statements
These are used to execute a block of statements multiple times. It means it executes the same
code multiple times so it saves code. These are also called Iteration statements.
There are three types of looping control statements:
For loop
While loop Program to understand for loop
Do-while loop public class Main {
public static void main(String[] args) {
1. For loop for (int i = 0; i < 5; i++) {
It executes the code until condition is false. System.out.println(i);
It is used when number of iterations are known. }
Syntax: }
for(initialization; condition; increment/decrement) }
{
//statements (For Body) O/P
} 0
1
2
3
4
2. While loop
While loop executes till the condition becomes false.
Syntax:
while(condition){
// statements
}
Program to understand while loop
class Intellipaat {public static void main(String args[]) {
int i = 2;
while( i <=2 )
{
System.out.println(“Intellipaat” );
i++;
}
}
}
Output: Intellipaat
3. Do-while loop
When you are using for or while, then it will execute the loop body only if the condition if true.
In do-while loop, it will execute the loop first, then it checks the condition. So, it will execute the
loop atleast once.
It is called exit controlled loop while for & while loop are called entry controlled loop.
Syntax:
do{
// statements
}while(condition);
Program to understand do-while loop
public class DoWhileExample {
public static void main(String[] args) {
int i=1;
do{
System.out.println(i);
i++;
}while(i<=10);
}
}
Unconditional Control Statements/Jump Statements

What is a break statement in Java?


The break statement in Java terminates the loop immediately, and the control of the program moves to the
next statement following the loop. It is almost always used with decision-making statements (Java if...else
Statement).
•Syntax: break; or break <label>;
class Intellipaat{ // break without label
class Test {
public static void main(String args[]){
for(int i=1;i<=4;i++){ public static void main(String[] args)
if(i==3) break; { // for loop
System.out.println(“Intellipaat.com”);} for (int i = 1; i <= 10; ++i)
}} { // if the value of i is 5 the loop terminates
Output: if (i == 5)
Intellipaat.com { break; }
Intellipaat.com System.out.println(i);
}}}

Output:
1234
In the above program, we are using the for loop to print the value of i in each iteration. To know how for
loop works, visit the Java for loop. Here, notice the statement,
if (i == 5) { break; }
This means when the value of i is equal to 5, the loop terminates. Hence we get the output with values
less than 5 only.
What is a Continue statement in Java?
The continue statement breaks one iteration (in the loop), if a specified condition occurs, and
continues with the next iteration in the loop.
Syntax: continue; or continue<label>; public class Main {
class Intellipaat{ //continue without label public static void main(String[] args) {
public static void main(String args[]){ int i = 0;
for(int i=1;i<=4;i++){ while (i < 10) {
System.out.print(“ “+i+” “); if (i == 4) {
if(i==3) continue; i++;
System.out.println(“Intellipaat.com”);} continue;
}
}}
System.out.println(i);
i++;
}
}
}
O/P
0
1
2
3
5
6
7
8
9
class Main { public static void main(String[] args) { // for loop for (int i = 1; i <= 10; ++i) { // if value of i is between 4
and 9 // continue is executed if (i > 4 && i < 9) { continue; } System.out.println(i); } } }

Output:
1 2 3 4 9 10
In the above program, we are using the for loop to print the value of i in each iteration. To
know how for loop works, visit Java for loop. Notice the statement,
if (i > 4 && i < 9) { continue; }
Here, the continue statement is executed when the value of i becomes more than 4 and less
than 9.
It then skips the print statement for those values. Hence, the output skips the values 5, 6, 7,
and 8.
Conditional Statements

Conditional Statements come under Control Structures in Java. As the same suggests, it
controls the flow of the execution of the program. Controlling here means branching,
decision-making, and iterating.
Generally, there are 3 types of Control Structures in Java:
Conditional Statements or Decisional Statements (if, if-else, switch)
Iteration Statements or Loops (for, while, do-while, for-each)
Jump Statements (break, continue, return)
In this article, we aim to explain conditional statements in Java and their working with
examples.
Conditional Statements in Java
Conditional statements in Java are the executable block of code (or branch to a specific
code) dependent on certain conditions. These statements are also known as decision
statements or selection statements in Java.
Following are the statements covered under conditional statements in Java:
If statement
If else statement
Switch Statement
If Statement
If a statement executes a set of statements based upon certain conditions. The condition
statement follows the if keyword.
Syntax:
if (condition) { //Statements to be executed }
Working of if statement:
The if clause accepts a condition and executes the set of statements falling under it
only when the condition evaluated is true.
Instance: displaying a number as positive (statement) if the number is greater
than zero (condition).
class if_condition {
public static void main(String[] args) {
double a = 0.5;
if (a>0)
{
System.out.println(a + " is a Positive Number!");
}
}
}

Output:

If-Else Statement
If-Else statement is a control structure that selects or chooses a set of statements depending
upon certain conditions.
If statements are like a subset of if-else statements.
Syntax:
if (condition) { //Statements to be executed if condition satisfies } else { //Statements to be
executed if the condition is not satisfied }
Working of if-else statements:
Here, the if clause evaluates the expression. If it comes out as true, statements under if block
gets executed. Else, statements under the else block get executed. As you can observe here,
depending upon the condition some sets of statements are executed and some are
bypassed.

class if_else_condition {
public static void main(String[] args) {
double a = -0.5;
if (a>0)
{
System.out.println(a + " is a Positive Number!");
}
else
{
System.out.println(a + " is a Negative Number!");
}
}
}

Output:
Nested If-Else Statements
The nested if-else statements are statements that incorporate more than one if-else clause.
Syntax:
if (condition) { //Statements set 1 } else if (condition 2) { //Statements set 2 } . . . else
{ //Statements to be executed if no condition is satisfied. }
class nested_if_else_condition {
public static void main(String[] args) {
double total_marks = 382;
char grade;
double perc = (total_marks/500)*100;
if (perc >= 80)
{
grade = 'A';
}
else if ((perc >=70) && (perc <80))
{
grade = 'B';
}
else if ((perc >=60) && (perc <70))
{
grade = 'c';
}
else
{
grade = 'D';
}
System.out.println("The percentage of the student is: " +perc);
System.out.println("\n The grade of the student is: " +grade);
}
}

Output:
Switch Statement
Unlike the if-else statement, the switch has multiple paths of execution. Moreover, it
evaluates the expression based on some of the primitive types or class types and matches
their value with its cases.
A switch can work well with a byte, char, short, and int primitive data types.
Syntax:
switch (Expression) { case value 1: Statement 1; case value 2: Statement 2; case value 3:
Statement 3; . . . case value n: Statement n; Default: default statement; }
class Switch_Case {
public static void main(String[] args) {
char a = 'C';
switch (a)
{
case 'A':
System.out.println("Letter A");
break;
case 'C':
System.out.println("Letter C");
break;
default:
System.out.println("Default case: NO Letter Matched!");
}
}
}

Output:
Class Definition in Java
In object-oriented programming, a class is a basic building block. It can be defined as
template that describes the data and behaviour associated with the class. class is to create
an object (variable) of that class that can be used to access the member variables and
methods of the class.
A class can also be called a logical template to create the objects that share common
properties and methods.
For example, an Employee class may contain all the employee details in the form of
variables and methods. If the class is instantiated i.e. if an object of the class is created (say
e1), we can access all the methods or properties of the class.
Defining a Class in Java
Java provides a reserved keyword class to define a class. The keyword must be followed by
the class name. Inside the class, we declare methods and variables.

In general, class declaration includes the following in the order as it appears:


Modifiers: A class can be public or has default access.
class keyword: The class keyword is used to create a class.
Class name: The name must begin with an initial letter (capitalized by convention).

Superclass (if any): The name of the class's parent (superclass), if any, preceded by the keyword
extends. A class can only extend (subclass) one parent.
Interfaces (if any): A comma-separated list of interfaces implemented by the class, if any,
preceded by the keyword implements. A class can implement more than one interface.
Java Class Example
Body: The class body surrounded by braces, { }. Example 1:
Syntax: Let's consider the following example to understand how
to define a class in Java and implement it with the object
<access specifier> class class_name of class.
{ Calculate.java
// class definition
// member variables public class Calculate
// class methods {
// instance variables
} int a;
int b;

// constructor to instantiate
public Calculate (int x, int y) {
this.a = x;
this.b = y;
}

// method to add numbers


public int add () {
int res = a + b;
return res;
}

// method to subtract numbers


public int subtract () {
int res = a - b;
return res;
}

// method to multiply numbers


public int multiply () {
int res = a * b;
return res;
}
// method to divide numbers
public int divide () {
int res = a / b;
return res;
}
// main method
public static void main(String[] args) {
// creating object of Class
Calculate c1 = new Calculate(45, 4);

// calling the methods of Calculate class


System.out.println("Addition is :" + c1.add());
System.out.println("Subtraction is :" + c1.subtract());
System.out.println("Multiplication is :" + c1.multiply());
System.out.println("Division is :" + c1.divide());
}

Output:
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.
Types of Variables
There are three types of variables in Java:
1. local variable
2. instance variable
3. 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
public class A
{
static int m=100;//static variable
void method()
{
int n=90;//local variable
}
public static void main(String args[])
{
int data=50;//instance variable
}
}//end of class

Java Variable Example: Add Two Numbers


public class Simple{
public static void main(String[] args){
int a=10;
int b=10; Output:
int c=a+b; 20
System.out.println(c);
}
}
Java Methods

A method is a block of code which only runs when it is called.


You can pass data, known as parameters, into a method.
Methods are used to perform certain actions, and they are also known as functions.
Why use methods?
To reuse code: define the code once, and use it many times.
Example
Create a method inside Main:
public class Main { static void myMethod() { // code to be executed } }

Example Explained
•myMethod() is the name of the method
•static means that the method belongs to the Main class and not an object of the Main class. You will
learn more about objects and how to access methods through objects later in this tutorial.
•void means that this method does not have a return value. You will learn more about return values
later in this chapter

Call a Method
To call a method in Java, write the method's name followed by two parentheses () and a semicolon;
In the following example, myMethod() is used to print a text (the action), when it is called:
Example: Inside main, call the myMethod() method:
public class Main
{
static void myMethod()
{
System.out.println("I just got executed!");
}
public static void main(String[] args)
{
myMethod();
}}
// Outputs "I just got executed!“
A method can also be called multiple times:
Example
public class Main
{
static void myMethod()
{
System.out.println("I just got executed!");
}
public static void main(String[] args)
{
myMethod();
myMethod();
myMethod();
}
}
OutPut
// I just got executed!
// I just got executed!
// I just got executed!
Java Classes and Objects
Java Classes/Objects
Java is an object-oriented programming language.
Everything in Java is associated with classes and objects, along with its attributes and methods. For
example: in real life, a car is an object. The car has attributes, such as weight and color, and methods,
such as drive and brake.
A Class is like an object constructor, or a "blueprint" for creating objects.
Create a Class
To create a class, use the keyword class:
Main.java
Create a class named "Main" with a variable x:
public class Main
{
int x = 5;
}
Create an Object
In Java, an object is created from a class. We have already created the class named Main, so now we can use this to
create objects.
To create an object of Main, specify the class name, followed by the object name, and use the keyword new:
Example
Create an object called "myObj" and print the value of x:
public class Main
{ int x = 5;
public static void main(String[] args)
{ Main myObj = new Main(); //new=memory allocation & Main() =constructor(they assign the default
values)
System.out.println(myObj.x);
}
} Output: 5
Multiple Objects
You can create multiple objects of one class:

Example
Create two objects of Main:
public class Main
{
int x = 5;
public static void main(String[] args)
{
Main myObj1 = new Main();
// Object 1
Main myObj2 = new Main();
// Object 2
System.out.println(myObj1.x);
System.out.println(myObj2.x);
}
}
Output:
5
5
Java Constructors
Java Constructors
A constructor in Java is a special method that is used to initialize objects. The constructor is called when an object of
a class is created. It can be used to set initial values for object attributes. A constructor in Java is a special method
that is used to initialize objects. The constructor is called when an object of a class is created.
Example
Create a constructor:
// Create a Main class
public class Main
{ int x; // Create a class attribute
// Create a class constructor for the Main class
public Main() { x = 5; // Set the initial value for the class attribute x
}
public static void main(String[] args)
{
Main myObj = new Main(); // Create an object of class Main (This will call the constructor)
System.out.println(myObj.x); // Print the value of x } }

// Outputs 5

Note that the constructor name must match the class name, and it cannot have a return type (like
void).
Also note that the constructor is called when the object is created.
All classes have constructors by default: if you do not create a class constructor yourself, Java creates
one for you. However, then you are not able to set initial values for object attributes.
Constructor Parameters
Constructors can also take parameters, which is used to initialize attributes.
The following example adds an int y parameter to the constructor. Inside the constructor we set x to y (x=y). When we
call the constructor, we pass a parameter to the constructor (5), which will set the value of x to 5:

Example
public class Main
{
int x;
public Main(int y)
{
x = y;
}
public static void main(String[] args)
{
Main myObj = new Main(5);
System.out.println(myObj.x);
}
}
// Outputs 5
public class Main
{
int modelYear;
String modelName;
public Main(int year, String name)
{
modelYear = year;
modelName = name;
}
public static void main(String[] args)
{
Main myCar = new Main(1969, "Mustang");
System.out.println(myCar.modelYear + " " + myCar.modelName);
}
}
// Outputs 1969 Mustang
Method in Java
In java Method called the function becoz we can create method within the class
In general, a method is a way to perform some task. Similarly, the method in Java is a
collection of instructions that performs a specific task. It provides the reusability of code.
We can also easily modify code using methods. In this section, we will learn what is a
method in Java, types of methods, method declaration, and how to call a method in
Java.
What is a method in Java?
A method is a block of code or collection of statements or a set of code grouped together to
perform a certain task or operation. It is used to achieve the reusability of code. We write a
method once and use it many times. We do not require to write code again and again. It also
provides the easy modification and readability of code, just by adding or removing a
chunk of code. The method is executed only when we call or invoke it.
The most important method in Java is the main() method. If you want to read more about
the main() method, go through the link https://www.javatpoint.com/java-main-method.
Method Declaration
The method declaration provides information about method attributes, such as visibility,
return-type, name, and arguments. It has six components that are known as method
header, as we have shown in the following figure.
Method Signature: Every method has a method signature. It is a part of the method
declaration. It includes the method name and parameter list.
Access Specifier: Access specifier or modifier is the access type of the method. It specifies
the visibility of the method. Java provides four types of access specifier:
Public: The method is accessible by all classes when we use public specifier in our
application.
Private: When we use a private access specifier, the method is accessible only in the classes
in which it is defined.
Protected: When we use protected access specifier, the method is accessible within the
same package or subclasses in a different package.
Default: When we do not use any access specifier in the method declaration, Java uses
default access specifier by default. It is visible only from the same package only.
Return Type: Return type is a data type that the method returns. It may have a primitive
data type, object, collection, void, etc. If the method does not return anything, we use void
keyword.
Method Name: It is a unique name that is used to define the name of a method. It must be
corresponding to the functionality of the method. Suppose, if we are creating a method for
subtraction of two numbers, the method name must be subtraction(). A method is invoked
by its name.
Parameter List: It is the list of parameters separated by a comma and enclosed in the pair
of parentheses. It contains the data type and variable name. If the method has no parameter,
left the parentheses blank.
Method Body: It is a part of the method declaration. It contains all the actions to be
performed. It is enclosed within the pair of curly braces.
Naming a Method
While defining a method, remember that the method name must be a verb and start with a
lowercase letter. If the method name has more than two words, the first name must be a
verb followed by adjective or noun. In the multi-word method name, the first letter of each
word must be in uppercase except the first word. For example:
Single-word method name: sum(), area()

Multi-word method name: areaOfCircle(), stringComparision()


It is also possible that a method has the same name as another method name in the same
class, it is known as method overloading.
Types of Method
There are two types of methods in Java:
Predefined Method
User-defined Method
1. Predefined Method:
In Java, predefined methods are the method that is already defined in the Java class libraries is
known as predefined methods. It is also known as the standard library method or built-in
method. We can directly use these methods just by calling them in the program at any point.
Some pre-defined methods are length(), equals(), compareTo(), sqrt(), etc. When we call any of
the predefined methods in our program, a series of codes related to the corresponding method
runs in the background that is already stored in the library.
Each and every predefined method is defined inside a class. Such as print() method is defined in
the java.io.PrintStream class. It prints the statement that we write inside the method. For
example, print("Java"), it prints Java on the console.

Examples:
1. print(); //
2. Sort(); //use with array class
3. Sqrt(); // use with math class
4. Nextint(); // use with scanner class
Let's see an example of the predefined method.
Demo.java
public class Demo
{
public static void main(String[] args)
{
// using the max() method of Math class
System.out.print("The maximum number is: " + Math.max(9,7));
}
}
Output: The maximum number is: 9

In the above example, we have used three predefined methods main(), print(), and max().
We have used these methods directly without declaration because they are predefined. The
print() method is a method of PrintStream class that prints the result on the console. The
max() method is a method of the Math class that returns the greater of two numbers.
2. User-defined Method:
Examples:
1. add()
2. sub()
3. show()
4. display()
Syntax: return type function name(parameters)
{
// statements
}
The method written by the user or programmer is known as a user-defined method. These
methods are modified according to the requirement.
How to Create a User-defined Method
Let's create a user defined method that checks the number is even or odd. First, we will
define the method.
//user defined method
public static void findEvenOdd(int num)
{
//method body
if(num%2==0)
System.out.println(num+" is even");
else
System.out.println(num+" is odd");
}
We have defined the above method named findevenodd(). It has a parameter num of type
int. The method does not return any value that's why we have used void. The method body
contains the steps to check the number is even or odd. If the number is even, it prints the
number is even, else prints the number is odd.

Why we need method?


1. Decrease line of code.
2. Readability
3. Repeat(we can use block of code multiple times)

Rules of method declaration?


4. Definition/method{ block of code}
5. Calling(execute the method)
example:
Class A
{
public static void main(string[]args)
{
Disp(); //method name
}
Void Disp() //void(return type),Disp(function name)
{
System.out.println();
}
}
Method Overloading in Java

If a class has multiple methods having same name but different in parameters, it is known as
Method Overloading.
If we have to perform only one operation, having same name of the methods increases the
readability of the program.
Suppose you have to perform addition of the given numbers but there can be any number of
arguments, if you write the method such as a(int,int) for two parameters, and b(int,int,int)
for three parameters then it may be difficult for you as well as other programmers to
understand the behavior of the method because its name differs.
So, we perform method overloading to figure out the program quickly.

Advantage of method overloading


Method overloading increases the readability of the program.
Different ways to overload the method
There are two ways to overload the method in java
By changing number of arguments
By changing the data type
1) Method Overloading: changing no. of arguments
In this example, we have created two methods, first add() method performs addition of two
numbers and second add method performs addition of three numbers.
In this example, we are creating static methods so that we don't need to create instance for
calling methods.
class Adder
{
static int add(int a,int b)
{return a+b;
}
static int add(int a,int b,int c)
{return a+b+c;
}
}
class TestOverloading1
{
public static void main(String[] args)
{
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}
Output: 22 33
2) Method Overloading: changing data type of arguments
In this example, we have created two methods that differs in data type. The first add method
receives two integer arguments and second add method receives two double arguments.

class Adder{
static int add(int a, int b){return a+b;}
static double add(double a, double b){return a+b;}
}
class TestOverloading2{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}}

Output:
22 24.9
Arrays in Java

Java Arrays
Normally, an array is a collection of similar type of elements which has contiguous memory
location.
Java array is an object which contains elements of a similar data type. Additionally, The
elements of an array are stored in a contiguous memory location. It is a data structure where we
store similar elements. We can store only a fixed set of elements in a Java array.
Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element
is stored on 1st index and so on.
Unlike C/C++, we can get the length of the array using the length member. In 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 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
Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.
Random access: We can get any data located at an index position.
Disadvantages
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.
•Single Dimensional Array
•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


arrayRefVar=new datatype[size];
Example of Java Array
Let's see the simple example of java array, where we are going to declare, instantiate,
initialize and traverse an array.

//Java Program to illustrate how to declare, instantiate, initialize


//and traverse the Java array.

class Testarray{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<a.length;i++) //length is the property of array
System.out.println(a[i]);
}}
Output:
10 20 70 40 50
//Java Program to illustrate the use of declaration, instantiation
//and initialization of Java array in a single line

class Testarray1{
public static void main(String args[]){
int a[]={33,3,4,5}; //declaration, instantiation and initialization
//printing array
for(int i=0;i<a.length;i++) //length is the property of array
System.out.println(a[i]);
}}

Output:
33 3 4 5
//Java Program to print the array elements using for-each loop

class Testarray1{
public static void main(String args[]){ Output:
int arr[]={33,3,4,5}; 33
//printing array using for-each loop 3
for(int i:arr) 4
System.out.println(i); 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.
//
Java Program to demonstrate the way of passing a System.out.println(min);
n array }
//to method.
class Testarray2{ public static void main(String args[]){
// int a[]={33,3,4,5};//
creating a method which receives an array as a par declaring and initializing an array
ameter min(a);//passing array to method
static void min(int arr[]){ }}
int min=arr[0];
for(int i=1;i<arr.length;i++)
if(min>arr[i])
Output:
min=arr[i]; 3
One Dimensional Array In Java – Tutorial & Example
in Java Programs Comments Off on One Dimensional Array In Java – Tutorial & Example
One Dimensional Array Program in Java – In this article, we will detail in on all the different
methods to describe the one-dimensional array program in Java with suitable examples &
sample outputs.
The methods used in this article are as follows:
Using Standard Method
Using Scanner
Using String
An array is a collection of elements of one specific type in a horizontal fashion. The array in
contention here is that of the one-dimensional array in Java programming.
Anything having one-dimension means that there is only one parameter to deal with. In regular
terms, it is the length of something. Similarly, as far as an array is concerned, one dimension
means it has only one value per location or index.
One-dimensional array in Java programming is an array with a bunch of values having been
declared with a single index.
As you can see in the example given above, firstly, you need to declare the elements that you
want to be in the specified array.
Secondly, the location of each element needs to particularized as well, since that is where the
elements will be stored respectively.
Thirdly, you need to declare the array accordingly.
As it is visible, the three elements that have been listed simultaneously are as follows:
10
20
30
Hence, the result is printed as 10 20 30 respectively in single lines, since it is a one-dimensional
array.
Thus, the methods used to do so in Java are as follows:
One Dimensional Array – Using Standard
Method elements are");
class OnedimensionalStandard System.out.println(a[0]);
{ System.out.println(a[1]);
public static void main(String args[]) System.out.println(a[2]);
{ }}
int[] a=new int[3];//declaration
Output:
a[0]=10;//initialization Output
a[1]=20; Java
a[2]=30; One dimensional array elements are
10
//printing array 20
System.out.println("One dimensional array 30
One-Dimensional Array Examples
Example 1: standard method
The standard method includes declaring a variable and initializing it using new or with a
specialized set of values using array initializer.
General Syntax:

data_type[] var_name = new data_type[]; OR


data_type var_name[] = {}; // curly braces encloses specialized set of values

For Example:
public class example{
public static void main{String args[])
{ int arr[] = {1,5,10,15,20}; // initializing array
for(int i=0;i<arr.length;i++)
{ System.out.println(arr[i]+" "); // printing array elements } } }
Output :
1 5 10 15 20
In the above example, we created a one-dimensional array of type int and stored 5 elements
1, 5, 10, 15,20 and set the arr variable to refer to the new array. Each element of the array is
accessed through its index value.
Using Scanner
What is Scanner method in Java?
Scanner is a class in java. util package used for obtaining the input of the primitive types like int,
double, etc. and strings. It is the easiest way to read input in a Java program, though not very efficient
if you want an input method for scenarios where time is a constraint like in competitive programming.
What is Scanner method in Java?
Scanner is a class in java. util package used for obtaining the input of the primitive types like int,
double, etc. and strings. It is the easiest way to read input in a Java program, though not very efficient
if you want an input method for scenarios where time is a constraint like in competitive programming.

Scanner Class Methods Method Description


There are various methods of Scanner class which can Reads
nextBoolean() a boolean value
be used for various data types. Take a look at the from the user
below table to know about these methods. Reads a byte value
nextByte() from the user
Reads
nextDouble() a double value
from the user
Reads a float value
nextFloat() from the user
Reads an int value
nextInt() from the user
Reads
nextLine() a String value from
the user
Reads a long value
nextLong() from the user
Now let’s take an example to
demonstrate the above methods. nextShort()
Reads a short value
from the user
Read the array length as sc.nextInt() and store it in the variable len and declare an array
int[len].
2) To store elements in to the array for i=0 to i<length of an array read the element using
sc.nextInt() and store the element at the index a[i].
3) Display the elements of an array for loop iterates from i=0 to i<length of an array print
the array element a[i].
What is the Java util package?
Package java. util. Contains the collections framework, some internationalization support
classes, a service loader, properties, random number generation, string parsing and
scanning classes, base64 encoding and decoding, a bit array, and several miscellaneous
utility classes.

import java.util.*;
class OnedimensionalScanner
{
public static void main(String args[])
{
int len;
Scanner sc=new Scanner(System.in);
System.out.println("Enter Array length : ");
len=sc.nextInt(); // The nextInt() method of Java Scanner class is used to scan the next token
of the input as an int.
int a[]=new int[len]; //declaration
System.out.print("Enter " + len + " Element to Store in Array :\n");
for(int i=0; i<len; i++)
{
a[i] = sc.nextInt();
}
System.out.print("Elements in Array are :\n");
for(int i=0; i<len; i++)
{
System.out.print(a[i] + " ");
}
}
}

Output:
Output
Java
Enter Array length :
4
Enter 4 Element to Store in Array :
1
2
3
4
Elements in Array are :
1 2 3 4
Using For Loop – One Dimensional Array
One Dimensional Array using Standard Method
Java
class OnedimensionalLoop
{
public static void main(String args[])
{
int a[]={10,20,30,40,50};//declaration and initialization
System.out.println("One dimensional array elements are :\n");
for(int i=0;i<a.length;i++)
{
System.out.println("a["+i+"]:"+a[i]);
}
}
}

Using For Loop – One Dimensional Array


Output:
One dimensional array elements are :

a[0]:10
a[1]:20
a[2]:30
a[3]:40
a[4]:50
class OneDimensionString
{
public static void main(String[] args)
{
//declare and initialize one dimension array
String[] str = new String[]{"one", "two", "three", "four"};
System.out.println("These are elements of one Dimensional array.");
for (int i = 0; i < str.length; i++)
{
System.err.println(str[i] + " ");
}
}
}

Using String
1.We declared one-dimensional string array with the elements strings.
2) To print strings from the string array. for i=0 to i<length of the string print string which is at the
index str[i].
Output:
Output
Java
These are elements of one Dimensional array.
one
two
three
four
Let’s implement a program that shows a String Array declaration.

public class Main


{
public static void main(String[] args) {

String[] myarray; //declaration of string array without size


String[] strArray = new String[5]; //declaration with size

//System.out.println(myarray[0]); //variable myarray might not have been initialized


//display elements of second array
System.out.print(strArray[0] + " " +strArray[1]+ " " + strArray[2]+ " " +
strArray[3]+ " " +strArray[4]);
}
}

Output:
Using A New Array
In this method, you create a new array having a size that is greater than the original array so that you
can accommodate the new element. After creating the new array, all the elements of the original array
are copied to this array and then the new element is added to the end of the array.
An example program to add an element using the new array is shown below.

importjava.util.*;
public class Main
{
public static void main(String[] args) {
//original array
String[] colorsArray = {"Red", "Green", "Blue" };
System.out.println("Original Array: " + Arrays.toString(colorsArray));
//length of original array
int orig_length = colorsArray.length;
//new element to be added to string array
String newElement = "Orange";
//define new array with length more than the original array
String[] newArray = new String[ orig_length + 1 ];
//add all elements of original array to new array
for (int i=0; i <colorsArray.length; i++)
{
newArray[i] = colorsArray [i];
}
//add new element to the end of new array
newArray[newArray.length- 1] = newElement;
//make new array as original array and print it
colorsArray = newArray;
System.out.println("Array after adding new item: " + Arrays.toString(colorsArray));
}
}
Output:

This approach clearly results in memory and performance overhead as you have to maintain
two arrays in the program.
Using ArrayList
You can also add an element to String array by using ArrayList as an intermediate data
structure. import java.io.*;
import java.lang.*;
An example is shown below. import java.util.*;

class Main {

public static void main(String[] args)


{
// define initial array
String numArray[]
= { "one", "two", "three", "four", "five", "six" };

// print the original array


System.out.println("Initial Array:\n"
+ Arrays.toString(numArray));

// new element to be added


String newElement = "seven";

// convert the array to arrayList


List<String>numList
= new ArrayList<String>(
Arrays.asList(numArray));

// Add the new element to the arrayList


numList.add(newElement);

// Convert the Arraylist back to array


numArray = numList.toArray(numArray);

// print the changed array


System.out.println("\nArray with value " + newElement
+ " added:\n"
+ Arrays.toString(numArray));
}
}
Output:

As shown in the above program, the string array is first converted into an ArrayList using
the asList method. Then the new element is added to the ArrayList using the add method.
Once the element is added, the ArrayList is converted back to the array.
This is a more efficient approach when compared to the ones discussed previously.
What is One Dimensional Array (1D Array) in Java?
A One-Dimensional Array in Java programming is a special type of variable that can store
multiple values of only a single data type such as int, float, double, char, structure, pointer,
etc. at a contagious location in computer memory. Here contagious location means at a
fixed gap in computer memory.
A One-Dimensional Array is also known as 1D Array.
Suppose we want to store the age of 10 students. In that case, we have to declare 10
variables in our Java program to store the age of 10 students.
Now here comes the use of a one-dimensional array. With the help of 1D Array, we will
declare a single variable in our Java program that can store the age of 10 students at a time.

Declaration Syntax of a One Dimensional Array in Java


datatype variable_name[] = new datatype[size];
Or
datatype[] variable_name = new datatype[size];
Here, size is the number of elements we want to store in the array.
Store and Access the Numbers in a 1D Array using Loops
We can also store as well as access the numbers in a 1D array using either for, while or do while loop.
Let's see a few examples.

Example 1
Program to input 10 numbers in an array and display only the even numbers if present in the array.
import java.util.Scanner;
public class Example
{
public static void main(String args[])
{
int a[]=new int[10], i;
Output
Scanner sc=new Scanner(System.in); Enter 10 numbers
System.out.println("Enter 10 numbers"); 11
for(i=0; i<10; i++) 15
{ 28
a[i]=sc.nextInt(); 31
} 49
System.out.println("List of even numbers");
54
for(i=0; i<10; i++)
{ 72
if(a[i]%2==0) 81
{ 93
System.out.print(a[i]+" "); 14
}}}} List of even numbers 28 54 72 14

Here, you can see that we have run a for loop 10 times to store the user's input in the array.
After that we have run another for loop 10 times to access each number from the array and
print only the even numbers from it.
Example 2
Program to input 5 numbers in an array and print all the numbers from the backside of the array. Example: 12 18 16
Output: 16 18 12

import java.util.Scanner;
public class Example Output
{ Enter 5 numbers
public static void main(String args[]) 48
{
21
int a[]=new int[5], i;
Scanner sc=new Scanner(System.in); 97
System.out.println("Enter 5 numbers"); 64
for(i=0; i<5; i++) 53
{ 53 64 97 21 48
a[i]=sc.nextInt();
}
for(i=4; i>=0; i--)
{
System.out.print(a[i]+" ");
}}}

Here, you can see that we have run a for loop 5 times to store the user's input in the array.
After that we have run another for loop in reverse order to print all the numbers from the
back side of the array.
What is Two Dimensional Array (2D Array) in Java
A Two Dimensional Array in Java is a collection of 1D Array. It consists of rows and columns and
looks like a table. A 2D array is also known as Matrix.
Declaration Syntax of a Two Dimensional Array in Java
datatype variable_name[][] = new datatype[row_size][column_size];
Or
datatype[][] variable_name = new datatype[row_size][column_size];
Here row_size is the number of rows we want to create in a 2D array and, column_size is the number of
columns in each row.

Example
int a[][]=new int[3][3];
Or
int[][] a=new int[3][3];
Store and Access the Numbers in a 2D Array using Loops
We can also store as well as access the numbers in a 2D array using either for, while or do while loop. Let's see a few
examples.

Example 1
Program to input numbers in a 3x3 Matrix and display the numbers in a table format.
import java.util.Scanner;
public class Example
{
public static void main(String args[])
{
int a[][]=new int[3][3];
Scanner sc=new Scanner(System.in);
int r,c;
System.out.println("Enter 9 numbers");
for(r=0; r<3; r++)
{
for(c=0; c<3; c++)
{
a[r][c]=sc.nextInt();
}}
System.out.println("\nOutput");
for(r=0; r<3; r++) // this loop is for row
{
for(c=0; c<3; c++) // this loop will print 3 numbers in each row
{
System.out.print(a[r][c]+" ");
}
System.out.println(); // break the line after printing the numbers in a row } } }
Output
Enter 9 numbers
84
36
41
98
34
57
20
31
24
Output 84 36 41 98 34 57 20 31 24
Here, you can see that we have run a nested for loop to store the user's input in a 3x3 matrix. After that we have run
another nested for loop to access each number from the 2D array and print on the screen in a table format.
Example 2
Program to input numbers in a 3x3 Matrix and print only even numbers if present in the matrix.
import java.util.Scanner;
public class Example
{
public static void main(String args[])
{ Output
int a[][]=new int[3][3]; Enter 9 numbers
Scanner sc=new Scanner(System.in); 84
int r,c; 36
System.out.println("Enter 9 numbers"); 41
for(r=0; r<3; r++)
98
{
for(c=0; c<3; c++) 34
{ 57
a[r][c]=sc.nextInt(); 20
}} 31
System.out.println("\nEven Numbers"); 24
for(r=0; r<3; r++) Even Numbers 84 36 98 34 20 24
{
for(c=0; c<3; c++)
{
if(a[r][c]%2==0)
{
System.out.print(a[r][c]+" ");
}}}}}

Here, you can see that we have entered numbers in a 3x3 matrix using nested for loop.
After that we have run another nested for loop to fetch the numbers from the 2D array and
print only those numbers which are divisible by 2.

You might also like