UNIT-1 Introduction - NOTES Java
UNIT-1 Introduction - NOTES Java
Structure,
and Compilation. Fundamental,
Programming Structures in Java: Defining Classes in Java, Constructors, Methods, Access
Specifies, Static Members, Final Members, Comments, Data types, Variables, Operators,
Control
Flow, Arrays & String.
Object Oriented Programming: Class, Object, Inheritance Super Class, Sub Class, Overriding,
Overloading, Encapsulation, Polymorphism, Abstraction, Interfaces, and Abstract Class.
Packages: Defining Package, CLASSPATH Setting for Packages, Making JAR Files for Library
Packages, Import and Static Import Naming Convention For Packages processor evolution and
types, microprocessor architecture and operation of its components, addressing modes,
interrupts, data transfer schemes, instruction and data flow, timer and timing diagram,
Interfacing
Introduction To Java
Java is an object-oriented, class-based programming language. The language is
designed to have as few dependencies implementations as possible. The intention of
using this language is to give relief to the developers from writing codes for every
platform. The term WORA, write once and run everywhere is often associated with this
language. It means whenever we compile a Java code, we get the byte code (.class file),
and that can be executed (without compiling it again) on different platforms provided
they support Java. In the year 1995, Java language was developed. It is mainly used to
develop web, desktop, and mobile devices. The Java language is known for its
robustness, security, and simplicity features. That is designed to have as few
implementation dependencies as possible.
History
The Java language has a very interesting history. Patrick Naughton, Mike Sheridan, and
Jame Gosling, known as the Green team, started the development of Java in the year
1991. These people were the engineers at Sun Microsystems. In 1996, the first public
implementation was released as Java 1.0. The compiler of Java 1.0 was rewritten by
Arthur Van Hoff to comply strictly with its specification. With the introduction of Java
2, the new versions have multiple different configurations that have been built for the
various platforms. It is worth noting that James Gosling is also known as the father of
Java.
The ISO standard body was approached by Sun Microsystems in the year 1997 to
formalize Java, but the process was withdrawn soon. At one point in time, Sun
Microsystems provided most of its implementation of Java available without any cost,
despite having the status of proprietary software.
Application Programs
The Implementation of an application program in Java application includes the
following steps.
It is worth noting here that JDK (Java Development Kit) should be installed properly on
the system, and the path should also be set.
FileName: TestClass.java
Write the above code and save the file with the name TestClass. The file should have
the .java extension.
Open the command prompt, and type javac TestClass.java. javac is the command that
makes the Java compiler come to action to compile the Java program. After the
command, we must put the name of the file that needs to be compiled. In our case, it
is TestClass.java. After typing, press the enter button. If everything goes well, a
TestClass.class file will be generated that contains the byte code. If there is some error
in the program, the compiler will point it out, and TestClass.class will not be created.
The Terminologies in Java
JVM (Java Virtual Machine): JVM is the specification that facilitates the runtime
environment in which the execution of the Java bytecode takes place. Whenever one
uses the command java, an instance of the JVM is created. JVM facilitates the
definition of the memory area, register set, class file format, and fatal error reporting.
Note that the JVM is platform dependent.
Byte Code: It has already been discussed in the introductory part that the Java
compiler compiles the Java code to generate the .class file or the byte code. One has
to use the javac command to invoke the Java compiler.
Java Development Kit (JDK): It is the complete Java Development Kit that
encompasses everything, including JRE(Java Runtime Environment), compiler, java
docs, debuggers, etc. JDK must be installed on the computer for the creation,
compilation, and execution of a Java program.
Java Runtime Environment (JRE): JRE is part of the JDK. If a system has only JRE
installed, then the user can only run the program. In other words, only
the java command works. The compilation of a Java program will not be possible
(the javac command will not work).
Garbage Collector: Programmers are not able to delete objects in Java. In order to do
so, JVM has a program known as Garbage Collector. Garbage Collectors recollect or
delete unreferenced objects. Garbage Collector makes the life of a developer/
programmer easy as they do not have to worry about memory management.
o Abstraction
o Inheritance
o Polymorphism
o Encapsulation
The Java language also extensively uses the concepts of classes and objects. Also, all
these features mentioned above are there in Java, which makes Java an object-oriented
programming language. Note that Java is an object-oriented programming language
but not 100% object-oriented.
Simple: Java is considered a simple language because it does not have the concept of
pointers, multiple inheritances, explicit memory allocation, or operator overloading.
Robust:
Java language is very much robust. The meaning of robust is reliable. The Java
language is developed in such a fashion that a lot of error checking is done as early as
possible. It is because of this reason that this language can identify those errors that
are difficult to identify in other programming languages. Exception Handling, garbage
collections, and memory allocation are the features that make Java robust.
Secure: There are several errors like buffer overflow or stack corruption that are not
possible to exploit in the Java language. We know that the Java language does not
have pointers. Therefore, it is not possible to have access to out-of-bound arrays. If
someone tries to do so, ArrayIndexOutofBound Exception is raised. Also, the execution
of the Java programs happens in an environment that is completely independent of
the Operating System, which makes this language even more secure.
Distributed: Distributed applications can be created with the help of the Java
language. Enterprise Java beans and Remote Method Invocation are used for creating
distributed applications. The distribution of Java programs can happen easily between
one or more systems that are connected to each other using the internet.
SandBox Execution: It is a known fact that Java programs are executed in different
environment, which gives liberty to users to execute their own applications without
impacting the underlying system using the bytecode verifier. The Bytecode verifier also
gives extra security as it checks the code for the violation of access.
Write Once Run Anywhere: The Java code is compiled by the compiler to get
the .class file or the byte code, which is completely independent of any machine
architecture.
Programs on Java
A few basic Java programs are mentioned below.
Program - 1
FileName: DemoClass.java
// Importing different classes
import java.io.*;
// Main class
public class DemoClass
{
// main method
public static void main(String argvs[])
{
System.out.println("Welcome to javaTpoint.");
}
}
Java Classes
A class in Java is a set of objects which shares common characteristics/ behavior and
common properties/ attributes. It is a user-defined blueprint or prototype from which
objects are created. For example, Student is a class while a particular student named
Ravi is an object.
Data member
Method
Constructor
Nested Class
Interface
Abstraction
Abstraction is one of the key concepts of object-oriented programming (OOP)
languages. Its main goal is to handle complexity by hiding unnecessary details from the
user. This enables the user to implement more complex logic on top of the provided
abstraction without understanding about all the hidden complexity. For example,
people do not think of a car as a set of tens of thousands of individual parts. They think
of it as a well-defined object with its own unique behavior. This abstraction allows
people to use a car to drive to the desired location without worrying about the
complexity of the parts that form the car. They can ignore the details of how the engine,
transmission, and braking systems work. Instead, they are free to utilize the object as a
whole.
Abstract class:
Abstract class in Java contains the ‘abstract’ keyword. If a class is declared
abstract, it cannot be instantiated. So we cannot create an object of an abstract class.
Also, an abstract class can contain abstract as well as concrete methods.
To use an abstract class, we have to inherit it from another class where we have to
provide implementations for the abstract methods there itself, else it will also become
an abstract class.
Interface:
Interface in Java is a collection of abstract methods and static constants. In an
interface, each method is public and abstract but it does not contain any constructor.
Along with abstraction, interface also helps to achieve multiple inheritance in Java.
Encapsulation
Binding (or wrapping) code and data together into a single unit is known as encapsulation. It
means to hide our data in order to make it safe from any modification.
The best way to understand encapsulation is to look at the example of a medical capsule,
where the drug is always safe inside the capsule. Similarly, through encapsulation the methods
and variables of a class are well hidden and safe.
Providing public setter and getter methods to modify and view the variables values.
Inheritance
This is a special feature of Object-Oriented Programming in Java. It lets programmers create
new classes that share some of the attributes of existing classes.
For e.g., a child inherits the properties from his father.
Similarly, in Java, there are two classes:
1. Parent class (Super or Base class)
2. Child class (Subclass or Derived Class)
A class which inherits the properties is known as ‘Child class’ whereas a class
properties
whose are inherited is known as ‘Parent
class’.
Inheritance is classified into 4
types:
Single inheritance
It enables a derived class to inherit the properties and behavior from a single parent class.
Here, Class A is a parent class and Class B is a child class which inherits the properties and
behavior of the parent class.
Multilevel inheritance
When a class is derived from a class which is also derived from another class, i.e. a class
having more than one parent class but at different levels, such type of inheritance is called
Multilevel Inheritance. as hierarchical inheritance.
Here, class B inherits the properties and behavior of class A and class C inherits the prop -
erties of class B. Class A is the parent class for B and class B is the parent class for C. So, class
C implicitly inherits the properties and methods of class A along with Class B.
Hierarchical i
When a class has more than one child class (sub class), then such kind of inheritance is known
Here, class A is a parent class for classes B and C, whereas classes B and C are the parent
classes of D which is the only child class of B and C.
Polymorphism
Polymorphism means taking many forms, where ‘poly’ means many and ‘morph’ means
forms. It is the abilIn Java, compile time polymorphism refers to a process in which a call to an
overloaded method is resolved at compile time rather than at run time. Method overloading is
For eg, Bank is a base class that provides a method rate of interest. But, rate of interest
may differ according to banks. For example, SBI, ICICI and AXIS are the child classes that
provide different rates of interest.
Polymorphism in Java is of two types:
Run time polymorphism.
Compile time polymorphism.
Variables
A variable is the holder that can hold the value while the java program is executed. A variable is
assigned with a datatype. It is the name of reserved area allocated in memory. In other words, it
is a name of memory location. There are three types of variables in java: local, instance and
static.
A variable provides us with named storage that our programs can manipulate. Each variable in
Java has a specific type, which determines the size and layout of the variable’s memory; the
range of values that can be stored within that memory; and the set of operations that can be
applied to the variable.
Before using any variable, it must be declared. The following statement expresses the basic
form of a variable declaration – datatype variable [ = value] [, variable [ = value] ...] ;
Here the data type is one of Java’s data types and variable is the name of the variable. To
declare more than one variable of the specified type, use a comma-separated list.
Example
Types of Variables
Local variable
Local variables are created when the method, constructor or block is entered
Local variable will be destroyed once it exits the method, constructor, or block.
Local variables are visible only within the declared method, constructor, or block.
Local variables are implemented at stack level internally.
There is no default value for local variables, so local variables should be declared and an initial
value should be assigned before the first use.
instance variable
A variable declared inside the class but outside the method, is called instance variable.
Instance variables are declared in a class, but outside a method, constructor or any block.
A slot for each instance variable value is created when a space is allocated for an object in the
heap.
Instance variables are created when an object is created with the use of the keyword ‘new’ and
destroyed when the object is destroyed.
Instance variables hold values that must be referenced by more than one method, constructor
or block, or essential parts of an object’s state that must be present throughout the class.
The instance variables are visible for all methods, constructors and block in the class. It is
recommended to make these variables as private. However, visibility for subclasses can be
given for these variables with the use of access modifiers.
○ Booleans it is false,
Instance variables can be accessed directly by calling the variable name inside the class.
However, within static methods (when instance variables are given accessibility), they should
be called using the fully qualified name. ObjectReference.VariableName.
static variable
Class variables also known as static variables are declared with the static keyword in a class,
but outside a method, constructor, or a block.
Only one copy of each class variable per class is created, regardless of how many objects are
created from it.
Static variables are rarely used other than being declared as constants. Constants are variables
that are declared as public/private, final, and static. Constant variables never change from their
initial value.
Static variables are stored in the static memory. It is rare to use static variables other than
declared final and used as either public or private constants.
Static variables are created when the program starts and destroyed when the program stops.
Visibility is the same as instance variables. However, most static variables are declared public
since they must be available for users of the class.
○ Booleans, it is false.
Values can be assigned during the declaration or within the constructor. Additionally, values
can be assigned in special static initializer blocks.
Static variables can be accessed by calling with the class name Class Name. Variable Name.
When declaring class variables as public static final, then variable names (constants) are all in
upper case. If the static variables are not public and final, the naming syntax is the same as
instance and local variables.
Operators
Operator in java is a symbol that is used to perform operations. Java provides a rich set of
operators to manipulate variables. For example: +, -, *, / etc. All the Java operators can be
divided into the following groups −
Arithmetic Operators : Multiplicative : * / %
Additive :+-
Relational Operators
Comparison : < > <= >= instance of
Equality : == !=
Bitwise Operators
bitwise AND : & bitwise exclusive OR : ^ bitwise inclusive OR : |
Prefix : ++expr --expr +expr -expr
Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations in the same way as they
are used in algebra. The following table lists the arithmetic operators −
Relational
Operators
The following relational operators are supported by Java language.
Example:
int A=10,B=20;
Operator description example Output
boolean re-
checks whether the object is of a particular
type (class type or interface type) sult = name
instance of
(Object reference variable ) instanceof True
Operator instanceof
(class/interface type)
String;
System.out.println(“a == b :” + (a == b));
Java supports several bitwise operators, that can be applied to the integer types, long, int,
short, char, and byte. Bitwise operator works on bits and performs bit-by-bit operation.
System.out.println(“a != b :” + (a != b));
}
}
Bitwise
Operators
Example:
int a = 60,b = 13; binary format of a & b will be
as follows − a = 0011 1100 b = 0000 1101
Bitwise operators follow the truth table:
0 0 0 0 1 1
0 1 0 1 0 1
1 0 0 1 0 0
1 1 1 1 1 0
1100)
>>> (zero fill The left operands value is moved right by A >>>2 will give 15
right the number of bits specified by the right 15 which is 0000 (in binary
operand and shifted values are filled up 1111 form: 0000
shift)
with zeros. 1111)
Logical Operators
The following are the logical operators supported by java.
Example:
A=true;
B=false;
assignment Operators
The following are the assignment operators supported by Java.
Operator description example
-=
(Subtract
C -= A is
It subtracts right operand from the left operand
AND equivalent
and assigns the result to left operand.
to C = C – A
assignment
operator)
*=
(Multiply
C *= A is
It multiplies right operand with the left operand
AND equivalent
and assigns the result to left operand.
to C = C * A
assignment
operator)
/=
(Divide
C /= A is
It divides left operand with the right operand and
AND equivalent
assigns the result to left operand.
to C = C / A
assignment
operator)
%=
(Modulus C %= A is
It takes modulus using two operands and
AND equivalent
assigns the result to left operand.
assignment to C = C % A
operator)
C <<= 2 is
<<= Left shift AND assignment operator. same as
C = C << 2
C >>= 2 is
>>= Right shift AND assignment operator. same as
C = C >> 2
C &= 2 is
&= Bitwise AND assignment operator. same as
C=C&2
bitwise exclusive OR and assignment C ^= 2 is
^= operator. same as
C=C^2
C |= 2 is
|= bitwise inclusive OR and assignment operator. same as C
=C|2
b -= 1; e
*= 2; f /= 2;
System.out.println(“a, b, e, f = “ +
a + “,” + b + “,” + e + “,” + f);
}
Ternary
Operator
Conditional Operator ( ? : )
Since the conditional operator has three operands, it is referred as the ternary operator.
This operator consists of three operands and is used to evaluate Boolean expressions. The goal
of the operator is to decide, which value should be assigned to the variable. The operator is
written as –
variable x = (expression) ? value if true : value if false
{
public static void main(String args[])
int a, b; a =
10;
b = (a == 0) ? 20: 30;
System.out.println( “b : “ + b );
Unary
Operators
Unary operators use only one operand. They are used to increment, decrement or negate a
value.
Operator description
c = b++;
System.out.println(“Value of c (b++) = “ + c);
c = --d;
System.out.println(“Value of c (--d) = “ + c);
c = --e;
}
}
>|
<<= &= ^= |=
Control Flow
Java Control statements control the flow of execution in a java program, based on data
values and conditional logic used. There are three main categories of control flow statements;
Selection statements: if, if-else and switch.
if statement:
The if statement executes a block of code only if the specified expression is true. If the value
is false, then the if block is skipped and execution continues with the rest of the program.
if-else statement
syntax:
if (<conditional expression>)
<statement action>
else
<statement action>
{
int a = 10, b = 20; if (a >
b)
{
} else
{
}
}
the flow of the program falls through to the next case. So, after every case, you must insert a
break statement.
…
case labeln: <statementn>
default: <statement>
} // end switch
Iteration
Iteration statements execute a block of code for several numbers of times until the condi
While statement
while (<loop
condition>{<statements>}
Constructors
Every class has a constructor. If the constructor is not defined in the class, the Java
compiler builds a default constructor for that class. While a new object is created, at least one
constructor will be invoked. The main rule of constructors is that they should have the same
name as the class. A class can have more than one constructor.
• Constructor(s) of a class must have same name as the class name in which it resides.
• A constructor in Java cannot be abstract, final, static and synchronized.
• Access modifiers can be used in constructor declaration to control its access i.e which
other class can call the constructor.
} types of
constructors
There are two type of constructor in Java:
1. no-argument constructor:
A constructor that has no parameter is known as default constructor.
If the constructor is not defined in a class, then compiler creates default constructor (with
no arguments) for the class. If we write a constructor with arguments or no-argument then
compiler does not create default constructor.
Default constructor provides the default values to the object like 0, null etc. depending on the
type.
2. Parameterized constructor
A constructor that has parameters is known as parameterized constructor. If we want to
initialize fields of the class with your own values, then use parameterized constructor.
// Java Program to illustrate calling of parameterized constructor.
import java.io.*; class myclass
{
// data members of the class. String name; int num;
// contructor with arguments. myclass(String name, int n)
// this would invoke parameterized constructor.
myclass m1 = new myclass(“Java”, 2017);
System.out.println(“Name :” + m1.name + “ num :” + m1.num);
this.name = name; this.num = n;
}
}
class myclassmain{
public static void main (String[] args)
{
}
}
There are no “return value” statements in constructor, but constructor returns current class
instance. We can write ‘return’ inside a constructor.
Methods in java
A method is a collection of statement that performs specific task. In Java, each method is a
part of a class and they define the behavior of that class. In Java, method is a jargon used for
method.
advantages of methods
• Program development and debugging are easier
• Increases code sharing and code reusability
• Increases program readability
• It makes program modular and easy to understanding
• It shortens the program length by reducing code redundancy types of methods
There are two types of methods in Java programming:
library methods
The standard library methods are built-in methods in Java programming to handle tasks such
as mathematical computations, I/O processing, graphics, string handling etc. These methods
are already defined and come along with Java class libraries, organized in packages.
Packages Library methods descriptions
java.lang.Math acos() Computes arc cosine of the argument
All maths related exp() Computes the e raised to given power
methods are defined in abs() Computes absolute value of argument
this class
log() Computes natural logarithm
sqrt() Computes square root of the argument
pow() Computes the number raised to given
power
java.lang.String Returns
charAt() the char value at the specified
concat()
All string related methods compareTo()
are defined in this class Concatenates two string
indexOf()
Compares two string
Returns the index of the first occurrence
toUpperCase()
of the given character
converts all of the characters in the String
Example:
Program to compute square root of a given number using built-in method. public class
MathEx {
public static void main(String[] args) {
System.out.print(“Square root of 14 is: “ + Math.sqrt(14));
}
}
Sample Output:
Square root of 14 is: 3.7416573867739413
user-defined methods
The methods created by user are called user defined methods.
Syntax:
return_type method_name(parameter_list);
Here, the return_type specifies the data type of the value returned by method. It will be void
if the method returns nothing. method_name indicates the unique name assigned to the
method. parameter_list specifies the list of values accepted by the method.
method Definition
Method definition provides the actual body of the method. The instructions to complete a
specific task are written in method definition. The syntax of method is as follows:
Syntax:
modifier return_type method_name(parameter_list){
}
Here,
Modifier – Defines the access type of the method i.e accessibility re-
gion of method in the application
Method Overloading
Method overloading is the process of having multiple methods with same name that differs
in parameter list. The number and the data type of parameters must differ in overloaded
methods. It is one of the ways to implement polymorphism in Java. When a method is called,
the overloaded method whose parameters match with the arguments in the call gets invoked.
Note: Overloaded methods are differentiable only based on parameter list and not on their
return type.
Example: Program for addition using Method Overloading class MethodOverload{ void
add(){
System.out.println(“No parameters”);
}
void add(int a,int b){ // overloaded add() for two integer parameter
System.out.println(“Sum:”+(a+b));
}
void add(int a,int b,int c){ // overloaded add() for three integer parameter
System.out.println(“Sum:”+(a+b+c));
}
void add(double a,double b){ // overloaded add() for two double parameter
System.out.println(“Sum:”+(a+b));
}
}
public class Main {
public static void main(String[] args) { MethodOverload obj=new MethodOverload();
obj.add(); // call all versions of add() obj.add(1,2); obj.add(1,2,3);
obj.add(12.3,23.4);
}
}
Sample Output:
No parameters
Sum:3
Sum:6
Sum:35.7
Here, add() is overloaded four times. The first version takes no parameters, second takes
two integers, third takes three integers and fourth accepts two double parameter.
Access specifiers
Access specifiers or access modifiers in java specifies accessibility (scope) of a data
member, method, constructor or class. It determines whether a data or method in a class can
be used or invoked by other class or subclass.
1. Private
2. Default (no speciifer)
3. Protected
4. Public
The details about accessibility level for access specifiers are shown in following table.
access modifiers default Private Protected Public
Accessible inside the class Yes Yes Yes Yes
Accessible within the subclass
Yes No Yes Yes
inside the same package
Accessible outside the package No No No Yes
Accessible within the subclass
No No Yes Yes
outside the package
Example:
Role of private specifier class
PrivateEx{ private int x; public
int y; private
// private data
PrivateEx(){} public
// public data
PrivateEx(int a,int b){ // private constructor
x=a; y=b; // public constructor
}
}
public class Main {
}
}
In this example, we have created two classes PrivateEx and Main. A class contains private
data member, private constructor and public method. We are accessing these private
members from outside the class, so there is compile time error.
Example:
Example:
Role of protected specifier
class Base
{ protected void show(){
System.out.println(“In Base”);
}
} public class Main extends Base
{ public static void main(String[] args)
{ Main obj=new Main();
}
Public access modifier
The public access specifier has highest level of accessibility. Methods, class, and fields
declared as public are accessible by any class in the same package or in other package.
Example:
Role of public specifier
class PublicEx{ public int
no=10;
}
public class Main{ public static void
main(String[] args) {
PublicEx obj=new PublicEx();
System.out.println(obj.no);
}
}
• Static Keyword
class staticex{
} }
} }
10 10
10 11
10 12
Example:
class StaticEx{
static int x; int y=10; static void display(){
System.out.println(“Static Method “+x); // static method accessing static variable
}
public void show(){
System.out.println(“Non static method “+y);
System.out.println(“Non static method “+x); // non-static method can access static
variable
}
}
public class Main
{
public static void main(String[] args) {
StaticEx obj=new StaticEx();
StaticEx.display(); // static method invoked without using object
obj.show();
A static block is a block of code enclosed in braces, preceded by the keyword static.
• The statements within the static block are first executed automatically before main when
the class is loaded into JVM.
• A class can have any number of static blocks.
• JVM combines all the static blocks in a class as single block and executes them.
• Static methods can be invoked from the static block and they will be executed as and
when the static block gets executed.
Syntax:
static{
…………….
}
Example:
class StaticBlockEx{
StaticBlockEx (){
System.out.println(“Constructor”);
static void show(){
} static {
System.out.println(“Inside method”);
} static{
show();
static{
System.out.println(“Static in main”);
}
}
Syntax:
class OuterClass{
……..
static class InnerClass{
static
import
The static import allows the programmer to access any static members of imported class
directly. There is no need to qualify it by its name.
Syntax:
Import static package_name;
Advantage:
• Less coding is required if you have access any static member of a class oftenly.
Disadvantage:
Overuse of static import makes program unreadable and unmaintable.
Arrays
Array is a collection of elements of similar data type stored in contiguous memory location.
The array size is fixed i.e we can’t increase/decrease its size at runtime. It is index based and
the first element is stored at 0th index.
Advantages of Array
• Code Optimization: Multiple values can be stored under common name. Date retrieval or
sorting is an easy process.
• Random access: Data at any location can be retrieved randomly using the index.
Disadvantages of Array
• Inefficient memory usage: Array is static. It is not resizable at runtime based on number
of user’s input. To overcome this limitation, Java introduce collection concept.
types of array
There are two types of array.
• One Dimensional Array
• The syntax for declaring an array variable is
dataType[] arrayName;
Syntax:
an identifier.
Example:
int[] a;
instantiation of an array
Array can be created using the new keyword. To allocate memory for array elements we
must mention the array size. The size of an array must be specified by an int value and not long
or short. The default initial value of elements of an array is 0 for numeric types and false for
boolean.
Syntax:
arrayName=new datatype[size];
Or
dataType[] arrayName=new datatype[size]; //declaration and instantiation
Example:
int[] a=new int[5]; //defining an integer array for 5 elements
Syntax:
dataType[] arrayName=new datatype[]{list of values separated by comma};
Or
dataType[] arrayName={ list of values separated by comma};
Example:
int[] a={12,13,14}; int[]
a=new int[]{12,13,14};
The built-in length property is used to determine length of the array i.e. number of ele -
The array elements can be accessed by using indices. The index starts from 0 and ends at
( array size-1). Each element in an array can be accessed usingfor loop.
Example:
Program to access array elements. class
Main{
//printing array
System.out.println(a[i]);
}
}
Sample Output:
10
20
30
40
the for-each loop
The for-each loop is used to traverse the complete array sequentially without using an index
variable. It’s commonly used to iterate over an array or a Collections class (eg, ArrayList).
Syntax:
for(type var:arrayName){ Statements
using var;
}
Example:
Program to calculate sum of array elements. class
Main{
}
}
Sample Output:
Sum:100
multidimensional arrays
Multidimensional arrays are arrays of arrays with each element of the array holding the
reference of other array. These are also known as Jagged Arrays.
Syntax:
dataType[][] arrayName=new datatype[rowsize][columnnsize]; // 2 dimensional array
dataType[][][] arrayName=new datatype[][][];
System.out.print(arr[i][j] + “ “);
System.out.println();
}
}
}
jagged array
Jagged array is an array of arrays with different row size i.e. with different dimensions.
Example:
class Main {
int[][] a = {
{11, 3, 43},
{3, 5, 8, 1},
{9},
};
Java String
In Java, string is basically an object that represents sequence of char values. An array of
characters works same as Java string. For example:
1. char[] ch={'j','a','v','a','t','p','o','i','n','t'};
2. String s=new String(ch);
is same as:
1. String s="javatpoint";
Java String class provides a lot of methods to perform operations on strings such as
compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(),
substring() etc.