Lecture Notes Unit 1 Java
Lecture Notes Unit 1 Java
Lecture Notes Unit 1 Java
JVM (Java Virtual Machine) is an abstract machine that enables your computer to run a Java
program. When you run the Java program, Java compiler first compiles your Java code to
bytecode. Then, the JVM translates bytecode into native machine code (set of instructions that a
computer's CPU executes directly).
Java is a platform-independent language. It's because when you write Java code, it's ultimately
written for JVM but not your physical machine (computer). Since JVM executes the Java
bytecode which is platform-independent, Java is platform-independent.
What is JRE?
JRE (Java Runtime Environment) is a software package that provides Java class libraries, Java
Virtual Machine (JVM), and other components that are required to run Java applications.
If you need to run Java programs, but not develop them, JRE is what you need.
What is JDK?
JDK (Java Development Kit) is a software development kit required to develop applications in
Java. When you download JDK, JRE is also downloaded with it.
In addition to JRE, JDK also contains a number of development tools (compilers, JavaDoc, Java
Debugger, etc).
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.
1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Interpreted
9. High Performance
10. Multithreaded
11. Distributed
12. Dynamic
Simple
Java is very easy to learn, and its syntax is simple, clean and easy to understand. According to
Sun, Java language is a simple programming language because:
o Java syntax is based on C++ (so easier for programmers to learn it after C++).
o Java has removed many complicated and rarely-used features, for example, explicit
pointers, operator overloading, etc.
o There is no need to remove unreferenced objects because there is an Automatic Garbage
Collection in Java.
Object-oriented
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 the top of other hardware-based platforms. It has two components:
1. Runtime Environment
2. API(Application Programming Interface)
Java code can be run on multiple platforms, for example, Windows, Linux, Sun Solaris, Mac/OS,
etc. Java code is compiled by the compiler and converted into bytecode. This bytecode is a
platform-independent code because it can be run on multiple platforms, i.e., Write Once and Run
Anywhere(WORA).
Secured
Java is best known for its security. With Java, we can develop virus-free systems. Java is secured
because:
o No explicit pointer
o Java Programs run inside a virtual machine sandbox
o Classloader: Classloader in Java is a part of the Java Runtime Environment(JRE) which
is used to load Java classes into the Java Virtual Machine dynamically. It adds security by
separating the package for the classes of the local file system from those that are
imported from network sources.
o Bytecode Verifier: It checks the code fragments for illegal code that can violate access
right to objects.
o Security Manager: It determines what resources a class can access such as reading and
writing to the local disk.
Java language provides these securities by default. Some security can also be provided by an
application developer explicitly through SSL, JAAS, Cryptography, etc.
Robust
Robust simply means strong. Java is robust because:
o It uses strong memory management.
o There is a lack of pointers that avoids security problems.
o There is automatic garbage collection in java which runs on the Java Virtual Machine to
get rid of objects which are not being used by a Java application anymore.
o There are exception handling and the type checking mechanism in Java. All these points
make Java robust.
Architecture-neutral
Java is architecture neutral because there are no implementation dependent features, for example,
the size of primitive types is fixed.
In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4 bytes
of memory for 64-bit architecture. However, it occupies 4 bytes of memory for both 32 and 64-
bit architectures in Java.
Portable
Java is portable because it facilitates you to carry the Java bytecode to any platform. It doesn't
require any implementation.
High-performance
Java is faster than other traditional interpreted programming languages because Java bytecode is
"close" to native code. It is still a little bit slower than a compiled language (e.g., C++). Java is
an interpreted language that is why it is slower than compiled languages, e.g., C, C++, etc.
Distributed
Java is distributed because it facilitates users to create distributed applications in Java. RMI and
EJB are used for creating distributed applications. This feature of Java makes us able to access
files by calling the methods from any machine on the internet.
Multi-threaded
A thread is like a separate program, executing concurrently. We can write Java programs that
deal with many tasks at once by defining multiple threads. The main advantage of multi-
threading is that it doesn't occupy memory for each thread. It shares a common memory area.
Threads are important for multi-media, Web applications, etc.
Dynamic
Java is a dynamic language. It supports dynamic loading of classes. It means classes are loaded
on demand. It also supports functions from its native languages, i.e., C and C++.
o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation
Objects in Java
Let us now look deep into what are objects. If we consider the real-world, we can find many
objects around us, cars, dogs, humans, etc. All these objects have a state and a behavior.
If we consider a dog, then its state is - name, breed, color, and the behavior is - barking,
wagging the tail, running.
If you compare the software object with a real-world object, they have very similar
characteristics.
Software objects also have a state and a behavior. A software object's state is stored in fields
and behavior is shown via methods.
So in software development, methods operate on the internal state of an object and the object-
to-object communication is done via methods.
Classes in Java
A class is a blueprint from which individual objects are created.
Following is a sample of a class.
Example
public class Dog {
String breed;
int age;
String color;
void barking() {
}
void hungry() {
}
void sleeping() {
}
}
A class can contain any of the following variable types.
Local variables − Variables defined inside methods, constructors or blocks are called
local variables. The variable will be declared and initialized within the method and the
variable will be destroyed when the method has completed.
Instance variables − Instance variables are variables within a class but outside any
method. These variables are initialized when the class is instantiated. Instance variables
can be accessed from inside any method, constructor or blocks of that particular class.
Class variables − Class variables are variables declared within a class, outside any
method, with the static keyword.
A class can have any number of methods to access the value of various kinds of methods. In the
above example, barking(), hungry() and sleeping() are methods.
Inheritance
1. Inheritance
2. Types of Inheritance
3. Why multiple inheritance is not possible in Java in case of class?
Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object. It is an important part of OOPs (Object Oriented programming
system).
The idea behind inheritance in Java is that you can create new classes that are built upon existing
classes. When you inherit from an existing class, you can reuse methods and fields of the parent
class. Moreover, you can add new methods and fields in your current class also.
Inheritance represents the IS-A relationship which is also known as a parent-child relationship.
Abstraction
Data Abstraction is the property by virtue of which only the essential details are displayed to the
user.The trivial or the non-essentials units are not displayed to the user. Ex: A car is viewed as a
car rather than its individual components.
Data Abstraction may also be defined as the process of identifying only the required
characteristics of an object ignoring the irrelevant details.The properties and behaviors of an
object differentiate it from other objects of similar type and also help in classifying/grouping the
objects.
Consider a real-life example of a man driving a car. The man only knows that pressing the
accelerators will increase the speed of car or applying brakes will stop the car but he does not
know about how on pressing the accelerator the speed is actually increasing, he does not know
about the inner mechanism of the car or the implementation of accelerator, brakes etc in the car.
This is what abstraction is.
Polymorphism
Polymorphism is the ability of an object to take on many forms. The most common use of
polymorphism in OOP occurs when a parent class reference is used to refer to a child class
object.
Any Java object that can pass more than one IS-A test is considered to be polymorphic. In Java,
all Java objects are polymorphic since any object will pass the IS-A test for their own type and
for the class Object.
Encapsulation
is one of the four fundamental OOP concepts. The other three are inheritance, polymorphism,
and abstraction.
Encapsulation in Java is a mechanism of wrapping the data (variables) and code acting on the
data (methods) together as a single unit. In encapsulation, the variables of a class will be hidden
from other classes, and can be accessed only through the methods of their current class.
Therefore, it is also known as data hiding.
To achieve encapsulation in Java −
Declare the variables of a class as private.
Provide public setter and getter methods to modify and view the variables values.
2. byte: The byte data type is an 8-bit signed two’s complement integer. The byte data type
is useful for saving memory in large arrays.
Syntax:
byte byteVar;
Size:
1 byte ( 8 bits )
Values:
-128 to 127
Default Value:
0
3. short: The short data type is a 16-bit signed two’s complement integer. Similar to byte,
use a short to save memory in large arrays, in situations where the memory savings actually
matters.
Syntax:
short shortVar;
Size:
2 byte ( 16 bits )
Values:
-32, 768 to 32, 767 (inclusive)
Default Value:
0
7. double: The double data type is a double-precision 64-bit IEEE 754 floating point. For
decimal values, this data type is generally the default choice.
Syntax:
double doubleVar;
Size:
8 byte ( 64 bits )
Values:
upto 16 decimal digits
Default Value:
0.0
Note: Both float and double data types were designed especially for scientific calculations,
where approximation errors are acceptable. If accuracy is the most prior concern then, it is
recommended not to use these data types and use BigDecimal class instead.
Please see this for details: Rounding off errors in Java
8. char: The char data type is a single 16-bit Unicode character.
Syntax:
char charVar;
Size:
2 byte ( 16 bits )
Values:
'\u0000' (0) to '\uffff' (65535)
Default Value:
'\u0000'
Why is the size of char is 2 byte in java..?
In other languages like C/C++ uses only ASCII characters and to represent all ASCII
characters 8-bits is enough,
But java uses Unicode system not ASCII code system and to represent Unicode system 8
bit is not enough to represent all characters so java uses 2 byte for characters.
Unicode defines a fully international character set that can represent most of the world’s
written languages. It is a unification of dozens of character sets, such as Latin,
Greeks,Cyrillic, Katakana, Arabic and many more.
Output:
char: G
integer: 89
byte: 4
short: 56
float: 4.7333436
double: 4.355453532
Operators in Java
Java provides many types of operators which can be used according to the need. They are
classified based on the functionality they provide. Some of the types are-
1. Arithmetic Operators
2. Unary Operators
3. Assignment Operator
4. Relational Operators
5. Logical Operators
6. Ternary Operator
7. Bitwise Operators
8. instance of operator
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, used for giving positive values. Only used when deliberately
converting a negative value to positive.
++ :Increment operator, used for incrementing the value by 1. There are two
varieties of increment operator.
Post-Increment : Value is first used for computing the result and then incremented.
Pre-Increment : Value is incremented first and then result is computed.
— : Decrement operator, used for decrementing the value by 1. There are two
varieties of decrement operator.
Post-decrement : Value is first used for computing the result and then decremented.
Pre-Decrement : Value is decremented first and then result is computed.
! : Logical not operator, used for inverting a boolean value.
3. Assignment Operator
‘=’ Assignment operator is used to assign a value to any variable. It has a right to left
associativity, i.e value given on right hand side of 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.
General format of assignment operator is,
variable = value;
In many cases assignment operator can be combined with other operators to build a
shorter version of statement called 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 variable on
the left.
-=, for subtracting left operand with right operand and then assigning it to variable
on the left.
*=, for multiplying left operand with right operand and then assigning it to variable
on the left.
/=, for dividing left operand with right operand and then assigning it to variable on
the left.
%=, for assigning modulo of left operand with right operand and then assigning it
to variable on the left.
int a = 5;
a += 5; //a = a+5;
4. Relational Operators
These operators are used to check for relations like equality, greater than, less than. They
return boolean result after the comparison and are extensively used in looping statements
as well as conditional if else statements. General format is,
variable relation_operator value
Some of the relational operators are-
==, Equal to : returns true of left hand side is equal to right hand side.
!=, Not Equal to : returns true of left hand side is not equal to right hand side.
<, less than : returns true of left hand side is less than right hand side.
<=, less than or equal to : returns true of left hand side is less than or equal to right
hand side.
>, Greater than : returns true of left hand side is greater than right hand side.
>=, Greater than or equal to: returns true of left hand side is greater than or equal
to right hand side.
5. Logical Operators
These operators are used to perform “logical AND” and “logical OR” operation, i.e. the
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.
Conditional operators are-
&&, Logical AND : returns true when both conditions are true.
|| Logical OR : returns true if at least one condition is true.
6. Ternary operator
Ternary operator is a shorthand version of if-else statement. It has three operands and
hence the name ternary. 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 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 Binary indexed tree.
&, 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
compliment representation of the input value, i.e. with all bits inversed.
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 of 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 initial number.
Similar effect as of 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.
8. instance of operator
Instance of 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-
Precedence and Associativity of Operators
Precedence and associative rules are used when dealing with hybrid equations involving more
than one type of operator. In such cases, these rules determine which part of the equation to
consider first as there can be many different valuations for the same equation. The below table
depicts the precedence of operators in decreasing order as magnitude with the top representing
the highest precedence and bottom shows the lowest precedence.
Control Statements
If Else Statement
In Java, if statement is used for testing the conditions. The condition matches the statement it
returns true else it returns false. There are four types of If statement they are:
i. if statement
ii. if-else statement
iii. if-else-if ladder
iv. nested if statement
if Statement
In Java, if statement is used for testing conditions. It is used for only true condition.
Syntax:
if(condition)
{
//code
Example:
public class IfDemo1 {
public static void main(String[] args)
{
int marks=70;
if(marks > 65)
{
System.out.print("First division");
}
}
}
if-else Statement
In Java, the if-else statement is used for testing conditions. It is used for true as well as for false
condition.
Syntax:
if(condition)
{
//code for true
}
else
{
//code for false
}
Example:
public class IfElseDemo1 {
public static void main(String[] args)
{
int marks=50;
if(marks > 65)
{
System.out.print("First division");
}
else
{
System.out.print("Second division");
}
}
}
if-else-if ladder Statement
In Java, the if-else-if ladder statement is used for testing conditions. It is used for testing one
condition from multiple statements.
Syntax:
if(condition1)
{
//code for if condition1 is true
}
else if(condition2)
{
//code for if condition2 is true
}
else if(condition3)
{
//code for if condition3 is true
}
...
else
{
//code for all the false conditions
}
Example:
public class IfElseIfDemo1 {
public static void main(String[] args) {
int marks=75;
if(marks<50){
System.out.println("fail");
}
else if(marks>=50 && marks<60){
System.out.println("D grade");
}
else if(marks>=60 && marks<70){
System.out.println("C grade");
}
else if(marks>=70 && marks<80){
System.out.println("B grade");
}
else if(marks>=80 && marks<90){
System.out.println("A grade");
}else if(marks>=90 && marks<100){
System.out.println("A+ grade");
}else{
System.out.println("Invalid!");
}
}
}
Nested if statement
In Java, the Nested if statement is used for testing conditions. In this, one if block is created
inside another if block when the outer block is true then only the inner block is executed.
Syntax:
if(condition)
{
//statement
if(condition)
{
//statement
}
}
Example:
public class NestedIfDemo1 {
public static void main(String[] args)
{
int age=25;
int weight=70;
if(age>=18)
{
if(weight>50)
{
System.out.println("You are eligible");
}
}
}
}
For Loop
In Java, for loop is used for executing a part of the program again and again. When the number
of execution is fixed then it is suggested to use for loop. In java there are 3 types of for loops,
they are as follows:
1. Simple for loop
2. For-each loop
3. labelled for loop
Syntax:
for(initialization;condition;increment/decrement)
{
//statement
}
Initialization: It is the initial condition which is executed only once at the starting of a
loop. It is an optional condition.
Condition: It is used to test a condition each time while executing. The execution
continues until the condition is false. It is an optional condition.
Statement: It is executed every time until the condition is false.
Increment/Decrement: It is used for incrementing and decrementing the value of a
variable. It is an optional condition.
Switch Statement
In Java, the switch statement is used for executing one statement from multiple conditions. it is
similar to an if-else-if ladder. In a switch statement,the expression can be of byte, short, char and
int data types. From JDK7 enum, String class and the Wrapper classes can also be used.
Following are some of the rules while using the switch statement:
1. There can be one or N numbers of cases.
2. The values in the case must be unique.
3. Each statement of the case can have a break statement. It is optional.
Syntax:
switch(expression)
{
case value1:
//code for execution;
break; //optional
case value2:
// code for execution
break; //optional
......
......
......
......
Case value n:
// code for execution
break; //optional
default:
// code for execution when none of the case is true;
}
Example:
While Loop
In Java, While loop is a control statement. It is used for iterating a part of the program several
times. When the number of iteration is not fixed then while loop is used.
Syntax:
while(condition)
{
//code for execution
}
Example:
public class WhileDemo1
{
public static void main(String[] args)
{
inti=1;
while(i<=10)
{
System.out.println(i);
i++;
}
}
}
do-while loop
In Java, the do-while loop is used to execute a part of the program again and again. If the number
of iteration is not fixed then the do-while loop is used. This loop executes at least once because
the loop is executed before the condition is checked.
Syntax:
do
{
//code for execution
}
while(condition);
Example:
public class DoWhileDemo1
{
public static void main(String[] args)
{
inti=1;
do
{
System.out.println(i);
i++;
}while(i<=10);
}
}
Break Statement
In Java, a break statement is used inside a loop. The loop is terminated immediately when a
break statement is encountered and resumes from the next statement.
Syntax:
jump-statement;
break;
Example:
public class BreakDemo1 {
public static void main(String[] args) {
for(inti=1;i<=10;i++){
if(i==8){
break;
}
System.out.println(i);
}
}
}
continue Statement
In Java, the Continue statement is used in loops. Continue statement is used to jump to the next
iteration of the loop immediately. It is used with for loop, while loop and do-while loop.
Example:
public class ContinueDemo1
{
public static void main(String[] args)
{
for(inti=1;i<=10;i++)
{
if(i==5)
{
continue;
}
System.out.println(i);
}
}
}
Type Casting
Casting is a process of changing one type value to another type. In Java, we can cast one type of
value to another type. It is known as type casting.
Example :
int x = 10;
byte y = (byte)x;
In Java, type casting is classified into two types,
Widening Casting(Implicit)
Output:
Int value 100
Long value 100
Float value 100.0
Example :
public class Test
{
public static void main(String[] args)
{
double d = 100.04;
long l = (long)d; //explicit type casting required
int i = (int)l; //explicit type casting required
Here, we have one more example of explicit casting, double type is stored into long, long is
stored into int etc.
class CastingDemo1
{
public static void main(String[] args)
{
double d = 120.04;
long l = (long)d;
int i = (int)l;
System.out.println("Double value "+d);
System.out.println("Long value "+l);
System.out.println("Int value "+i);
}
}
Output:
class Demo2
byte b;
int i = 355;
double d = 423.150;
b = (byte) i;
System.out.println("*************************************************");
b = (byte) d;
Output:
Conversion of int to byte: i = 355 b = 99
*************************************************
Conversion of double to byte: d = 423.15 b=89
Arrays in Java
An array is a group of like-typed variables that are referred to by a common name.Arrays in Java
work differently than they do in C/C++. Following are some important point about Java arrays.
In Java all arrays are dynamically allocated.(discussed below)
Since arrays are objects in Java, we can find their length using member length. This is
different from C/C++ where we find length using sizeof.
A Java array variable can also be declared like other variables with [] after the data type.
The variables in the array are ordered and each have an index beginning from 0.
Java array can be also be used as a static field, a local variable or a method parameter.
The size of an array must be specified by an int value and not long or short.
The direct superclass of an array type is Object.
Every array type implements the interfaces Cloneable and java.io.Serializable.
Array can contains primitives (int, char, etc) as well as object (or non-primitives) references of a
class depending on the definition of array. In case of primitives data types, the actual values are
stored in contiguous memory locations. In case of objects of a class, the actual objects are stored
in heap segment.
One-Dimensional Arrays :
type var-name[];
OR
type[] var-name;
An array declaration has two components: the type and the name. type declares the element type
of the array. The element type determines the data type of each element that comprises the array.
Like array of int type, we can also create an array of other primitive data types like char, float,
double..etc or user defined data type(objects of a class).Thus, the element type for the array
determines what type of data the array will hold.
Example:
// both are valid declarations
int intArray[];
or
int[] intArray;
byte byteArray[];
short shortsArray[];
boolean booleanArray[];
Although the above first declaration establishes the fact that intArray is an array variable, no
array actually exists. It simply tells to the compiler that this(intArray) variable will hold an
array of the integer type. To link intArray with an actual, physical array of integers, you must
allocate one using new and assign it to intArray.
Array Literal
In a situation, where the size of the array and variables of array are already known, array literals
can be used.
int[] intArray = new int[]{ 1,2,3,4,5,6,7,8,9,10 };
// Declaring array literal
The length of this array determines the length of the created array.
There is no need to write the new int[] part in the latest versions of Java
Implementation:
class GFG
{
public static void main (String[] args)
{
// declares an Array of integers.
int[] arr;
Arrays of Objects
An array of objects is created just like an array of primitive type data items in the following way.
Student[] arr = new Student[7]; //student is a user-defined class
The studentArray contains seven memory spaces each of size of student class in which the
address of seven Student objects can be stored.The Student objects have to be instantiated using
the constructor of the Student class and their references should be assigned to the array elements
in the following way.
// Java program to illustrate creating an array of
// objects
class Student
{
public int roll_no;
public String name;
Student(int roll_no, String name)
{
this.roll_no = roll_no;
this.name = name;
}
}
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. A multidimensional array is
created by appending one set of square brackets ([]) per dimension. Examples:
int[][] intArray = new int[10][20]; //a 2D array or matrix
int[][][] intArray = new int[10][20][10]; //a 3D array
class multiDimensional
{
public static void main(String args[])
{
// declaring and initializing 2D array
int arr[][] = { {2,7,9},{3,6,1},{7,4,2} };
// printing 2D array
for (int i=0; i< 3 ; i++)
{
for (int j=0; j < 3 ; j++)
System.out.print(arr[i][j] + " ");
System.out.println();
}
}
}
Output:
279
361
742
Like variables, we can also pass arrays to methods.For example, below program pass array to
method sum for calculating sum of array’s values.
class Test
{
// Driver method
public static void main(String args[])
{
int arr[] = m1();
Array Members
Now as you know that arrays are object of a class and direct superclass of arrays is
class Object.The members of an array type are all of the following:
The public final field length, which contains the number of components of the
array. length may be positive or zero.
All the members inherited from class Object; the only method of Object that is not
inherited is its clone method.
The public method clone(), which overrides clone method in class Object and throws
no checked exceptions.
Cloning of arrays
When you clone a single dimensional array, such as Object[], a “deep copy” is performed
with the new array containing copies of the original array’s elements as opposed to
references.
class Test
{
public static void main(String args[])
{
int intArray[] = {1,2,3};
// will print true as shallow copy is created i.e. sub-arrays are shared
System.out.println(intArray[0] == cloneArray[0]);
System.out.println(intArray[1] == cloneArray[1]);
}
}
Output:
false
true
true
Example:
// Java program to demonstrate Arrays.toString() method
import java.util.Arrays;