Lecture Notes Unit 1 Java

Download as pdf or txt
Download as pdf or txt
You are on page 1of 37
At a glance
Powered by AI
The key takeaways are the relationship between JVM, JRE and JDK and the features of the Java programming language.

The main components of Java are the JVM, JRE and JDK. JVM executes Java bytecode, JRE provides runtime libraries to execute Java programs, and JDK is used for development and contains tools like compilers.

Some important features of Java include being simple, object-oriented, platform independent, secure, robust, architecture neutral, interpreted, high performance, multithreaded, distributed and dynamic.

What is JVM?

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.

Working of Java Program

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.

JRE is the superset of JVM.

Java Runtime Environment

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

If you want to develop Java applications, download JDK.


Relationship between JVM, JRE, and JDK.

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 most important features of Java language is given below.

1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Interpreted
9. High Performance
10. Multithreaded
11. Distributed
12. Dynamic

Simple

Java is very easy to learn, and its syntax is simple, clean and easy to understand. According to
Sun, Java language is a simple programming language because:

o Java syntax is based on C++ (so easier for programmers to learn it after C++).
o Java has removed many complicated and rarely-used features, for example, explicit
pointers, operator overloading, etc.
o There is no need to remove unreferenced objects because there is an Automatic Garbage
Collection in Java.

Object-oriented

Java is an object-oriented programming language. Everything in Java is an object. Object-


oriented means we organize our software as a combination of different types of objects that
incorporates both data and behavior.

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


and maintenance by providing some rules.

Basic concepts of OOPs are:


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

Platform Independent

Java is platform independent because it is different from other languages like C, C++, etc. which
are compiled into platform specific machines while Java is a write once, run anywhere language.
A platform is the hardware or software environment in which a program runs.
There are two types of platforms software-based and hardware-based. Java provides a software-
based platform.

The Java platform differs from most other platforms in the sense that it is a software-based
platform that runs on 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++.

Principles of Object-Oriented Programming System


Object means a real-world entity such as a pen, chair, table, computer, watch, etc. Object-
Oriented Programming is a methodology or paradigm to design a program using classes and
objects. It simplifies software development and maintenance by providing some concepts:

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.

Why use inheritance in java


o For Method Overriding (so runtime polymorphism can be achieved).
o For Code Reusability.

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.

Data types in Java


Java has two categories of data:
 Primitive Data Type: such as boolean, char, int, short, byte, long, float and double
 Non-Primitive Data Type or Object Data type: such as String, Array, etc.
Primitive Data Type
Primitive data are only single values and have no special capabilities.

There are 8 primitive data types:


1. boolean: boolean data type represents only one bit of information either true or false,
but the size of boolean data type is virtual machine-dependent. Values of type boolean
are not converted implicitly or explicitly (with casts) to any other type. But the programmer
can easily write conversion code.
Syntax:
boolean booleanVar;
Size:
virtual machine dependent
Values:
true, false
Default Value:
false

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

4. int: It is a 32-bit signed two’s complement integer.


Syntax:
int intVar;
Size:
4 byte ( 32 bits )
Values:
-2, 147, 483, 648 to 2, 147, 483, 647 (inclusive)
Default Value:
0
Note: In Java SE 8 and later, we can use the int data type to represent an unsigned 32-bit
integer, which has value in the range [0, 232-1]. Use the Integer class to use int data type as
an unsigned integer.
5. long: The long data type is a 64-bit two’s complement integer.
Syntax:
long longVar;
Size:
8 byte ( 64 bits )
Values:
-9, 223, 372, 036, 854, 775, 808
to
9, 223, 372, 036, 854, 775, 807
(inclusive)
Default Value:
0
Note: In Java SE 8 and later, you can use the long data type to represent an unsigned 64-bit
long, which has a minimum value of 0 and a maximum value of 264-1. The Long class also
contains methods like compareUnsigned, divideUnsigned etc to support arithmetic
operations for unsigned long.
6. float: The float data type is a single-precision 32-bit IEEE 754 floating point. Use a float
(instead of double) if you need to save memory in large arrays of floating point numbers.
Syntax:
float floatVar;
Size:
4 byte ( 32 bits )
Values:
upto 7 decimal digits
Default Value:
0.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

Non-Primitive Data Type or Reference Data Types


The Reference Data Types will contain a memory address of variable value because the
reference types won’t store the variable value directly in memory. They
are strings, objects, arrays, etc.
 String: Strings are defined as an array of characters. The difference between a character
array and a string is the string is terminated with a special character ‘\0’.
Below is the basic syntax for declaring a string in Java programming language.
Syntax:
<String_Type> <string_variable> = “<sequence_of_string>”;
Example:
// Declare String without using new operator
String s = "GeeksforGeeks";

// Declare String using new operator


String s1 = new String("GeeksforGeeks");
 Class: A class is a user-defined blueprint or prototype from which objects are created. It
represents the set of properties or methods that are common to all objects of one type. In
general, class declarations can include these components, in order:
1. Modifiers : A class can be public or has default access (Refer this for details).
2. Class name: The name should begin with a initial letter (capitalized by convention).
3. 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.
4. 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.
5. Body: The class body surrounded by braces, { }.
Array: 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.

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.

Example for simple For loop


public class ForDemo1
{
public static void main(String[] args)
{
int n, i;
n=2;
for(i=1;i<=10;i++)
{
System.out.println(n+"*"+i+"="+n*i);
}
}
}

Example for Nested for loop

public class ForDemo2


{
public static void main(String[] args)
{
for(inti=1;i<=5;i++)
{
for(int j=1;j<=i;j++)
{
System.out.print("* ");
}
System.out.println();
}
}
}
for-each Loop
In Java, for each loop is used for traversing array or collection. In this loop, there is no need for
increment or decrement operator.
Syntax:
for(Type var:array)
{
//code for execution
}
Example:
public class ForEachDemo1
{
public static void main(String[] args)
{
inta[]={20,21,22,23,24};
for(int i:a)
{
System.out.println(i);
}
}
}

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:

public class SwitchDemo1{


public static void main(String[] args)
{
int day = 3;
String dayName;
switch (day) {
case 1:
dayName = "Today is Monday";
break;
ase 2:
dayName = "Today is Tuesday";
break;
case 3:
dayName = "Today is Wednesday";
break;
case 4:
dayName = "Today is Thursday";
break;
case 5:
dayName = "Today is Friday";
break;
case 6:
dayName = "Today is Saturday";
break;
case 7:
dayName = "Today is Sunday";
break;
default:
dayName = "Invalid day";
break;
}
System.out.println(dayName);
}
}

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)

 Narrowing Casting(Explicitly done)

Widening or Automatic type converion


Automatic Type casting take place when,
 the two types are compatible
 the target type is larger than the source type
Example:
public class Test
{
public static void main(String[] args)
{
int i = 100;
long l = i; //no explicit type casting required
float f = l; //no explicit type casting required
System.out.println("Int value "+i);
System.out.println("Long value "+l);
System.out.println("Float value "+f);
}
}

Output:
Int value 100
Long value 100
Float value 100.0

Narrowing or Explicit type conversion


When you are assigning a larger type value to a variable of smaller type, then you need to
perform explicit type casting. If we don't perform casting then compiler reports compile time
error.

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

System.out.println("Double value "+d);


System.out.println("Long value "+l);
System.out.println("Int value "+i);
}
}
Output:
Double value 100.04
Long value 100
Int value 100
Example of Explicit Conversion

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:

Double value 120.04


Long value 120
Int value 120
Example for Conversion of int and double into a byte
Here, we are converting int and double type to byte type by using explicit type casting.

class Demo2

public static void main(String args[])

byte b;

int i = 355;

double d = 423.150;

b = (byte) i;

System.out.println("Conversion of int to byte: i = " + i + " b = " + b);

System.out.println("*************************************************");

b = (byte) d;

System.out.println("Conversion of double to byte: d = " + d + " b= " + b);

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 :

The general form of a one-dimensional array declaration is

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.

Instantiating an Array in Java


When an array is declared, only a reference of array is created. To actually create or give
memory to array, you create an array like this:The general form of new as it applies to one-
dimensional arrays appears as follows:
var-name = new type [size];
Here, type specifies the type of data being allocated, size specifies the number of elements in the
array, and var-name is the name of array variable that is linked to the array. That is, to use new to
allocate an array, you must specify the type and number of elements to allocate.
Example:
int intArray[]; //declaring array
intArray = new int[20]; // allocating memory to array
OR
int[] intArray = new int[20]; // combining both statements in one
Note :
1. The elements in the array allocated by new will automatically be initialized to zero (for
numeric types), false (for boolean), or null (for reference types).Refer Default array values
in Java
2. Obtaining an array is a two-step process. First, you must declare a variable of the desired
array type. Second, you must allocate the memory that will hold the array, using new, and
assign it to the array variable. Thus, in Java all arrays are dynamically allocated.

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

Accessing Java Array Elements using for Loop


Each element in the array is accessed via its index. The index begins with 0 and ends at (total
array size)-1. All the elements of array can be accessed using Java for Loop.

// accessing the elements of the specified array using for loop


for (int i = 0; i < arr.length; i++)
System.out.println("Element at index " + i + " : "+ arr[i]);
// accessing the elements of the specified array using for each loop
for (int temp : arr)
System.out.println(temp);

Implementation:
class GFG
{
public static void main (String[] args)
{
// declares an Array of integers.
int[] arr;

// allocating memory for 5 integers.


arr = new int[5];

// initialize the first elements of the array


arr[0] = 10;

// initialize the remaining elements of the array


arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;

// accessing the elements of the specified array


for (int i = 0; i < arr.length; i++)
System.out.println("Element at index " + i + " : "+ arr[i]);
}
}
Output:
Element at index 0 : 10
Element at index 1 : 20
Element at index 2 : 30
Element at index 3 : 40
Element at index 4 : 50

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

// Elements of array are objects of a class Student.


public class GFG
{
public static void main (String[] args)
{
Student[] arr;
// allocating memory for 5 objects of type Student.
arr = new Student[5];
// initialize the first elements of the array
arr[0] = new Student(1,"aman");
// initialize the second elements of the array
arr[1] = new Student(2,"vaibhav");
// so on...
arr[2] = new Student(3,"shikar");
arr[3] = new Student(4,"dharmesh");
arr[4] = new Student(5,"mohit");
// accessing the elements of the specified array
for (int i = 0; i < arr.length; i++)
System.out.println("Element at " + i + " : " +
arr[i].roll_no +" "+ arr[i].name);
}
}
Output:
Element at 0 : 1 aman
Element at 1 : 2 vaibhav
Element at 2 : 3 shikar
Element at 3 : 4 dharmesh
Element at 4 : 5 mohit

What happens if we try to access element outside the array size?


JVM throws ArrayIndexOutOfBoundsException to indicate that array has been accessed with
an illegal index. The index is either negative or greater than or equal to size of array.
class GFG
{
public static void main (String[] args)
{
int[] arr = new int[2];
arr[0] = 10;
arr[1] = 20;

for (int i = 0; i <= arr.length; i++)


System.out.println(arr[i]);
}
}
Runtime error
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at GFG.main(File.java:12)

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

Passing Arrays to Methods

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.

// Java program to demonstrate // passing of array to method


class Test
{
public static void main(String args[])
{
int arr[] = {3, 1, 2, 5, 4};
// passing array to method m1
sum(arr);
}

public static void sum(int[] arr)


{
// getting sum of array values
int sum = 0;

for (int i = 0; i < arr.length; i++)


sum+=arr[i];
System.out.println("sum of array values : " + sum);
}
}
Output :
sum of array values : 15

Returning Arrays from Methods


As usual, a method can also return an array. For example, below program returns an array from
method m1.
// Java program to demonstrate
// return of array from method

class Test
{
// Driver method
public static void main(String args[])
{
int arr[] = m1();

for (int i = 0; i < arr.length; i++)


System.out.print(arr[i]+" ");

public static int[] m1()


{
// returning array
return new int[]{1,2,3};
}
}
Output:
123

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

int cloneArray[] = intArray.clone();

// will print false as deep copy is created for one-dimensional array


System.out.println(intArray == cloneArray);

for (int i = 0; i < cloneArray.length; i++) {


System.out.print(cloneArray[i]+" ");
}
}
}
Output:
false
123

 A clone of a multidimensional array (like Object[][]) is a “shallow copy” however, which is


to say that it creates only a single new array with each element array a reference to an
original element array but subarrays are shared.
class Test
{
public static void main(String args[])
{
int intArray[][] = {{1,2,3},{4,5}};

int cloneArray[][] = intArray.clone();

// will print false


System.out.println(intArray == cloneArray);

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

Arrays Class in java.util package


The Arrays class in java.util package is a part of the Java Collection Framework. This class
provides static methods to dynamically create and access Java arrays. It consists of only
static methods and the methods of Object class. The methods of this class can be used by
the class name itself.
Need for the Java-Arrays Class:
There are often times when loops are used to do some tasks on an array like:
 Fill an array with a particular value.
 Sort an Arrays.
 Search in an Arrays.
 And many more.
Arrays class provides several static methods that can be used to perform these tasks directly
without the use of loops.
Some of the methods in Arrays class
1. static <T> List<T> asList(T… a): This method returns a fixed-size list backed by the
specified Arrays.
2. static int binarySearch(elementToBeSearched): These methods searches for the
specified element in the array with the help of Binary Search algorithm.
3. static <T> int binarySearch(T[] a, int fromIndex, int toIndex, T key,
Comparator<T> c): This method searches a range of the specified array for the specified
object using the binary search algorithm.
4. copyOf(originalArray, newLength): This method copies the specified array, truncating
or padding with the default value (if necessary) so the copy has the specified length.
5. copyOfRange(originalArray, fromIndex, endIndex): This method copies the specified
range of the specified array into a new Arrays.
6. static boolean deepEquals(Object[] a1, Object[] a2): This method returns true if the
two specified arrays are deeply equal to one another.
7. static int deepHashCode(Object[] a): This method returns a hash code based on the
“deep contents” of the specified Arrays.
8. static String deepToString(Object[] a): This method returns a string representation of
the “deep contents” of the specified Arrays.
9. equals(array1, array2): This method checks if both the arrays are equal or not.
10. fill(originalArray, fillValue): This method assigns this fillValue to each index of this
Arrays.
11. mismatch(array1, array2): This method finds and returns the index of the first
unmatched element between the two specified arrays.
12. parallelSort(originalArray): This method sorts the specified array using parallel sort.
13. sort(originalArray): This method sorts the complete array in ascending order.
14. sort(originalArray, fromIndex, endIndex): This method sorts the specified range of
array in ascending order.

Example:
// Java program to demonstrate Arrays.toString() method

import java.util.Arrays;

public class Main {


public static void main(String[] args)
{

// Get the Array


int intArr[] = { 10, 20, 15, 22, 35 };

// To print the elements in one line


System.out.println("Integer Array: " + Arrays.toString(intArr));
}
}
Output:
Integer Array: [10, 20, 15, 22, 35]

// Java program to demonstrate Arrays.binarySearch() method


import java.util.Arrays;
public class Main {
public static void main(String[] args)
{
// Get the Array
int intArr[] = { 10, 20, 15, 22, 35 };
Arrays.sort(intArr);
int intKey = 22;
System.out.println(intKey +" found at index ="+Arrays
.binarySearch(intArr, intKey));
}
}
Output:
22 found at index = 3

// Java program to demonstrate Arrays.copyOf() method


import java.util.Arrays;
public class Main {
public static void main(String[] args)
{
// Get the Array
int intArr[] = { 10, 20, 15, 22, 35 };
// To print the elements in one line
System.out.println("Integer Array: " + Arrays.toString(intArr));
System.out.println("\nNew Arrays by copyOf:\n");
System.out.println("Integer Array:"+Arrays.toString(Arrays.copyOf(intArr, 10)));
}
}
Output:
Integer Array: [10, 20, 15, 22, 35]
New Arrays by copyOf:
Integer Array: [10, 20, 15, 22, 35, 0, 0, 0, 0, 0]

// Java program to demonstrate Arrays.mismatch() method


import java.util.Arrays;
public class Main {
public static void main(String[] args)
{
// Get the Arrays
int intArr[] = { 10, 20, 15, 22, 35 };
// Get the second Arrays
int intArr1[] = { 10, 15, 22 };
// To compare both arrays
System.out.println("Mismatched at index:"+Arrays.mismatch(intArr, intArr1));
}
}
Output:
Mismatched at index: 1

You might also like