0% found this document useful (0 votes)
6 views86 pages

Unit-1 - Introduction to JAVA

The document provides an introduction to Java and its fundamental concepts of Object-Oriented Programming (OOP), including classes, objects, inheritance, and polymorphism. It highlights Java's key features such as platform independence, security, and automatic memory management, as well as its syntax and data types. Additionally, it covers the setup of the Java environment, command line arguments, and various types of operators in Java.

Uploaded by

grebe64246
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
6 views86 pages

Unit-1 - Introduction to JAVA

The document provides an introduction to Java and its fundamental concepts of Object-Oriented Programming (OOP), including classes, objects, inheritance, and polymorphism. It highlights Java's key features such as platform independence, security, and automatic memory management, as well as its syntax and data types. Additionally, it covers the setup of the Java environment, command line arguments, and various types of operators in Java.

Uploaded by

grebe64246
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 86

Introduction to JAVA

Fundamentals of Object Oriented Programming


OOPs Concepts:

● Class
● Objects
● Data Abstraction
● Encapsulation
● Inheritance
● Polymorphism
● Dynamic Binding
● Message Passing
1. Class:
● A class is a user-defined data type. It consists of data members and
member functions, which can be accessed and used by creating an
instance of that class.
● It represents the set of properties or methods that are common to all
objects of one type.
2. Object:
● An Object is an instance of a Class. When a class is defined, no memory is
allocated but when it is instantiated (i.e. an object is created) memory is
allocated.
● An object has an identity, state, and behavior. Each object contains
data and code to manipulate the data.
● Objects can interact without having to know details of each other’s data
or code, it is sufficient to know the type of message accepted and type of
response returned by the objects.
3. Data Abstraction:
● Data abstraction refers to providing only essential information about the data to the
outside world, hiding the background details or implementation.
● Consider a real-life example of a man driving a car. The man only knows that pressing the
accelerators will increase the speed of the car or applying brakes will stop the car, but he
does not know about how on pressing the accelerator the speed is increasing, he does
not know about the inner mechanism of the car or the implementation of the accelerator,
brakes, etc in the car. This is what abstraction is.

4. Encapsulation:
● Encapsulation is defined as the wrapping up of data under a single unit. It is the
mechanism that binds together code and the data it manipulates.
● In Encapsulation, the variables or data of a class are hidden from any other class
and can be accessed only through any member function of their class in which they
are declared. As in encapsulation, the data in a class is hidden from other classes,
so it is also known as data-hiding.
5. Inheritance:
Inheritance is an important pillar of OOP(Object-Oriented Programming). The capability of a
class to derive properties and characteristics from another class is called Inheritance. When we
write a class, we inherit properties from other classes. So when we create a class, we do not
need to write all the properties and functions again and again, as these can be inherited from
another class that possesses it. Inheritance allows the user to reuse the code whenever possible
and reduce its redundancy.
6. Polymorphism:
The word polymorphism means having many forms. In simple words, we can define
polymorphism as the ability of a message to be displayed in more than one form.
For example, A person at the same time can have different characteristics. Like a
man at the same time is a father, a husband, an employee. So the same person
posses different behavior in different situations. This is called polymorphism.
7. Dynamic Binding:
● In dynamic binding, the code to be executed in response to the function call is
decided at runtime. Dynamic binding means that the code associated with a given
procedure call is not known until the time of the call at run time.
● Dynamic Method Binding One of the main advantages of inheritance is that some
derived class D has all the members of its base class B. Once D is not hiding any of
the public members of B, then an object of D can represent B in any context where
a B could be used. This feature is known as subtype polymorphism.
8. Message Passing:
● It is a form of communication used in object-oriented programming as well as
parallel programming. Objects communicate with one another by sending and
receiving information to each other.
● A message for an object is a request for execution of a procedure and therefore will
invoke a function in the receiving object that generates the desired results.
● Message passing involves specifying the name of the object, the name of the
function, and the information to be sent.
Overview of JAVA
Java is guaranteed to be Write Once, Run Anywhere. Java is −
● Object-Oriented: In Java, everything is an object. Java can be easily extended
since it is based on the object model.
● Platform Independent: Unlike many other programming languages, including C
and C++, when Java is compiled, it is not compiled into a platform-specific
machine but rather into platform-independent byte code. This byte code is
distributed over the web and interpreted by the virtual machine (JVM) on
whichever platform it is being run on.
● Simple: Java is designed to be easy to learn. If you understand the basic
concept of OOP Java, it would be easy to master.
● Secure: With Java's secure feature, it enables the development of virus-free,
tamper-free systems. Authentication techniques are based on public-key
encryption.
● Architecture-neutral: The Java compiler generates an architecture-neutral object
file format, which makes the compiled code executable on many processors with
the presence of the Java runtime system.
● Portable: Being architecture-neutral and having no implementation-dependent
aspects of the specification makes Java portable. Compiler in Java is written in ANSI C
with a clean portability boundary, which is a POSIX subset.
● Robust: Java makes an effort to eliminate error-prone situations by emphasizing
mainly compile-time error checking and runtime checking.
Multithreaded: With Java's multithreaded feature, it is possible to write programs that
can perform many tasks simultaneously. This design feature allows the developers to
construct interactive applications that can run smoothly.
● Interpreted: Java byte code is translated on the fly to native machine instructions and
is not stored anywhere. The development process is more rapid and analytical since
the linking is an incremental and light-weight process.
● High Performance: With the use of just-in-Time compilers, Java enables high
performance.
Distributed: Java is designed for the distributed environment of the internet.
● Dynamic: Java is considered to be more dynamic than C or C++ since it is designed to
adapt to an evolving environment. Java programs can carry an extensive amount of
run-time information that can be used to verify and resolve accesses to objects in run-
time.
Overview of Java
Some of the important concepts of Java include:

● A Java virtual machine (JVM), which provides the fundamental basis for platform independence
● Automated storage management techniques, such as garbage collection
● Language syntax that is similar to that of the C language

The result is a language that is object-oriented and efficient for application programming.

1.1.1 Java and Object-Oriented Programming Terminology


The following terms are common in Java application development in Oracle Database environment:

● Classes
● Objects
● Interfaces
● Encapsulation
● Inheritance
● Polymorphism
Java is a popular, general-purpose, high-level programming language that is widely used for building a variety of applications. It was
created by Sun Microsystems (now owned by Oracle Corporation) in the mid-1990s and has since become one of the most
widely used programming languages in the world.

Key Features of Java

1. Platform Independence (Write Once, Run Anywhere):


○ Java follows the principle of platform independence, meaning that once a program is written in Java, it can run on
any platform that has a Java Virtual Machine (JVM). The JVM interprets the compiled bytecode and allows it to
run on different operating systems (Windows, Mac, Linux, etc.).
2. Object-Oriented:
○ Java is an object-oriented programming (OOP) language, which means it emphasizes the use of objects and
classes. It promotes the use of concepts like inheritance, encapsulation, polymorphism, and abstraction, making code
easier to manage and maintain.
3. Syntax:
○ Java’s syntax is similar to C and C++, making it easier for developers familiar with these languages to learn Java. It
uses curly braces {} to define code blocks and semicolons ; to terminate statements.
4. Memory Management:
○ Java handles memory management automatically with garbage collection. The Java garbage collector takes care of
deallocating memory by automatically removing unused objects, thus preventing memory leaks.
5. Security:
○ Java provides several security features, such as bytecode verification, sandboxing, and encryption. These features
help ensure that Java programs are safe to run, especially in untrusted environments like web browsers.
4. Multithreading:
○ Java has built-in support for multithreading, allowing multiple parts of a program to execute
simultaneously. This is particularly useful for developing high-performance applications that require
parallel processing.
5. Rich API:
○ Java provides a large and comprehensive API (Application Programming Interface), which
includes libraries for networking, input/output (I/O), data structures, utilities, GUI, and more. The
vast number of libraries makes Java suitable for a wide range of applications.
6.Cross-Platform:
○ Java’s "Write Once, Run Anywhere" philosophy is enabled by the JVM. Java code is compiled into
bytecode, which is platform-independent. This bytecode is executed by the JVM, making Java
applications highly portable across different systems.
7. Distributed Computing:
○ Java includes support for networked applications through its libraries, making it suitable for
building distributed systems like web servers, cloud-based applications, and peer-to-peer systems.
8. Rich Ecosystem and Community:
○ Java has a vibrant and extensive ecosystem, including frameworks (e.g., Spring, Hibernate), tools
(e.g., Maven, Gradle), and a large global developer community. This makes finding resources,
support, and libraries easy for Java developers.
Setting up the environment in Java

Few things must be clear before setting up the environment which can better be perceived from the below image provided as follows:
● JDK(Java Development Kit): JDK is intended for software developers and
includes development tools such as the Java compiler, Javadoc, Jar, and a
debugger.
● JRE(Java Runtime Environment): JRE contains the parts of the Java libraries
required to run Java programs and is intended for end-users. JRE can be
viewed as a subset of JDK.
● JVM: JVM (Java Virtual Machine) is an abstract machine. It is a specification
that provides a runtime environment in which java bytecode can be
executed. JVMs are available for many hardware and software platforms.
Command line arguments
● The java command-line argument is an argument i.e. passed at the time of running the java
program.
● The arguments passed from the console can be received in the java program and it can be used
as an input.

public static void main(String args[]){


System.out.println("Your first argument is: "+args[0]);
}
}

compile by > javac CommandLineExample.java


run by > java CommandLineExample sonoo

Output: Your first argument is: sonoo


Example of command line arguments
class A{
public static void main(String args[]){

for(int i=0;i<args.length;i++)
System.out.println(args[i]);

}
}

compile by > javac A.java


run by > java A sonoo jaiswal 1 3 abc

Output: sonoo

jaiswal

abc
Java Data Types
Data types in Java are of different sizes and values that can be stored in the
variable that is made as per convenience and circumstances to cover up all
test cases. Java has two categories in which data types are segregated

1. Primitive Data Type: such as boolean, char, int, short, byte, long,
float, and double. The Boolean with uppercase B is a wrapper class for
the primitive data type boolean in Java.
2. Non-Primitive Data Type or Object Data type: such as String, Array,
etc.
Primitive Data Types 1.5. float
1.1. byte ● Size: 4 bytes (32 bits)
● Range: ±3.40282347E+38F (6-7 significant decimal digits)
● Size: 1 byte (8 bits) ● Description: The float type is used for single-precision floating-
● Range: -128 to 127 point numbers (decimals). It is less precise than double.
● Description: The byte type is used to save memory in large arrays
when the memory savings are crucial. It is the smallest data type.
1.6. double
1.2. short
● Size: 8 bytes (64 bits)
● Size: 2 bytes (16 bits) ● Range: ±1.7976931348623157E+308 (15 decimal digits of
● Range: -32,768 to 32,767 precision)
● Description: The short type is used when you need a larger range ● Description: The double type is used for double-precision
than byte but want to save memory compared to int. floating-point numbers (decimals). It provides more precision
than float and is the default choice for floating-point
1.3. int
calculations.
● Size: 4 bytes (32 bits) 1.7. char
● Range: -2^31 to 2^31 - 1 (-2,147,483,648 to 2,147,483,647) ● Size: 2 bytes (16 bits)
● Description: The int type is the default choice for integer values. It is ● Range: 0 to 65,535 (unsigned)
used when you need a larger range than byte and short. ● Description: The char type is used to represent a single
1.4. long character. It is based on Unicode, so it can store characters
from most languages and symbols.
● Size: 8 bytes (64 bits) 1.8. boolean
● Range: -2^63 to 2^63 - 1 (-9,223,372,036,854,775,808 to
● Size: 1 bit (but JVM optimizes memory)
9,223,372,036,854,775,807)
● Description: The long type is used when a wider range of values is ● Values: true or false
required than int. Typically used for large numbers or timestamps. ● Description: The boolean type is used for representing binary
Types of Operators in Java
1. Arithmetic Operators
2. Unary Operators
3. Assignment Operator
4. Relational Operators
5. Logical Operators
6. Ternary Operator
7. Bitwise Operators
8. Shift Operators
9. instance of operator
1. Arithmetic Operators

Arithmetic Operators are used to perform simple arithmetic operations on primitive and non-primitive
data types.

● * : Multiplication
● / : Division
● % : Modulo
● + : Addition
● – : Subtraction2. Unary Operators

Unary Operators need only one operand. They are used to increment, decrement, or negate
a value.

● - , Negates the value.


● + , Indicates a positive value (automatically converts byte, char, or short to int).
● ++ , Increments by 1.
○ Post-Increment: Uses value first, then increments.
○ Pre-Increment: Increments first, then uses value.
● -- , Decrements by 1.
○ Post-Decrement: Uses value first, then decrements.
○ Pre-Decrement: Decrements first, then uses value.
3. Assignment Operator

‘=’ Assignment operator is used to assign a value to any variable.


It has right-to-left associativity, i.e. value given on the right-hand side of the operator is
assigned to the variable on the left, and therefore right-hand side value must be
declared before using it or should be a constant.
The general format of the assignment operator is:
variable = value

In many cases, the assignment operator can be combined with others to create
shorthand compound statements. For example, a += 5 replaces a = a + 5. Common
compound operators include:

● += , Add and assign.


● -= , Subtract and assign.
● *= , Multiply and assign.
● /= , Divide and assign.
4. Relational Operators

Relational Operators are used to check for relations like equality, greater than, and
less than.
They return boolean results after the comparison and are extensively used in
looping statements as well as conditional if-else statements. The general format
is ,
variable relation_operator value

Relational operators compare values and return boolean results:

● == , Equal to.

● != , Not equal to.

● < , Less than.

● <= , Less than or equal to.


5. Logical Operators

Logical Operators are used to perform “logical AND” and “logical OR” operations, similar to
AND gate and OR gate in digital electronics. They have a short-circuiting effect, meaning the
second condition is not evaluated if the first is false.
Conditional operators are:

● &&, Logical AND: returns true when both conditions are true.
● ||, Logical OR: returns true if at least one condition is true.
● !, Logical NOT: returns true when a condition is false and vice-versa
6. Ternary operator

The Ternary Operator is a shorthand version of the if-else statement. It has three operands and
hence the name Ternary. The general format is ,
condition ? if true : if false

The above statement means that if the condition evaluates to true, then execute the
statements after the ‘?’ else execute the statements after the ‘:’.

7. Bitwise Operators

Bitwise Operators are used to perform the manipulation of individual bits of a number and with
any of the integer types. They are used when performing update and query operations of the
Binary indexed trees.

● & (Bitwise AND) – returns bit-by-bit AND of input values.


● | (Bitwise OR) – returns bit-by-bit OR of input values.
● ^ (Bitwise XOR) – returns bit-by-bit XOR of input values.
● ~ (Bitwise Complement) – inverts all bits (one’s complement).
8. Shift Operators
Shift 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. The
general format ,
number shift_op number_of_places_to_shift;

● << (Left shift) – Shifts bits left, filling 0s (multiplies by a power

of two).
● >> (Signed right shift) – Shifts bits right, filling 0s (divides by

a power of two), with the leftmost bit depending on the sign.


● >>> (Unsigned right shift) – Shifts bits right, filling 0s, with

the leftmost bit always 0.


import java.io.*; Output:

// Main class 8

0
class GFG {
16
// main driver method
public static void main(String[] args)
{ int number = 2;
// 2 bit left shift operation
int Ans = number << 2;
System.out.println(Ans);
Ans = number >> 2;
System.out.println(Ans);
number =64;
Ans = number >> 2;
System.out.println(Ans); } }
9. instanceof operator
2)
● The instance of operator is used for
class Animal{}
type checking. It can be used to test if
an object is an instance of a class, a class Dog1 extends
subclass, or an interface. The general Animal{//Dog inherits Animal
format ,
● object instance of
public static void main(String
class/subclass/interface
args[]){
1)
class Simple1{ Dog1 d=new Dog1();
public static void main(String args[]){ System.out.println(d instanceof
Simple1 s=new Simple1(); Animal);//true
System.out.println(s
}
instanceofSimple1);//true
} }
}

Output:true
Output:true
What is Expression in Java?
In Java, an expression is a combination of values, variables, operators, and method invocations that are
evaluated to produce a single value. An expression can be a single value or a combination of values that
produce a result. Expressions can be used in various contexts, such as in assignments, conditional
statements, and loops.

Types of Expressions in Java


1. Arithmetic expressions: These expressions involve arithmetic operations such as addition,
subtraction, multiplication, and division. For example, 2+3 is an arithmetic expression that
evaluates to 5.
2. Relational expressions: These expressions involve comparing two values using relational
operators such as "greater than," "less than," "equal to," and "not equal to." For example, 4<5 is a
relational expression that evaluates to true.
3. Logical expressions: These expressions involve logical operations such as "AND," "OR," and
"NOT." For example, (2<3)&&(3<4) is a logical expression that evaluates to true.
4. Conditional expressions: These expressions involve using the ternary operator "?:" to assign a
value based on a condition. For example, int x = (5<6)?2:3; assigns the value 2 to x since 5 is less
than 6.
5. Assignment expressions: These expressions involve assigning a value to a variable. For
example, int x = 5; assigns the value 5 to the variable x.
Control Statements in Java
Java provides three types of control flow statements.

1. Decision Making statements


○ if statements
○ switch statement

2. Loop statements
○ do while loop
○ while loop
○ for loop
○ for-each loop

3. Jump statements
○ break statement
○ continue statement
Decision-Making statements:
● decision-making statements decide which statement to
execute and when.
● Decision-making statements evaluate the Boolean
expression and control the program flow depending upon the
result of the condition provided.
● There are two types of decision-making statements in Java,
i.e.,
1. If statement and
2. switch statement.
If Statement:

The condition of the If statement gives a Boolean value, either


true or false. In Java, there are four types of if-statements given
below.

1. Simple if statement
2. if-else statement
3. if-else-if ladder
4. Nested if-statement
Simple if statement:

It evaluates a Boolean expression and enables the program to


enter a block of code if the expression evaluates to true.
Syntax of if statement is given below.

if(condition) {

statement 1; //executes when condition is true

}
Student.java
public class Student

public static void main(String[] args)

int x = 10;

int y = 12;

if(x+y > 20)

System.out.println("x + y is greater than 20");

}
if-else statement

The if-else statement is an extension to the if-statement, which uses another


block of code, i.e., else block. The else block is executed if the condition of
the if-block is evaluated as false.

Syntax:

if(condition) {

statement 1; //executes when condition is true

else{

statement 2; //executes when condition is false


Student.java
public class Student {

public static void main(String[ ] args) {

int x = 10;

int y = 12;

if(x+y < 10) {

System.out.println("x + y is less than 10");

else {

System.out.println("x + y is greater than 20");

}
if-else-if ladder:
The if-else-if statement contains the if-statement followed by multiple else-if statements.

Syntax of if-else-if statement is given below.

if(condition 1)

{ statement 1; //executes when condition 1 is true }

else if(condition 2)

{ statement 2; //executes when condition 2 is true }

else

statement 2; //executes when all the conditions are false

}
Nested if-statement
In nested if-statements, the if statement can contain a if or if-else statement inside another if or else-if
statement.

Syntax of Nested if-statement is given below.

if(condition 1)

statement 1; //executes when condition 1 is true

if(condition 2)

{ statement 2; //executes when condition 2 is true }

else

{ statement 2; //executes when condition 2 is false }

}
Student.java
public class Student {

public static void main(String[] args) {

String address = "Delhi, India";

if(address.endsWith("India")) {

if(address.contains("Meerut"))

{ System.out.println("Your city is Meerut"); }

else if (address.contains("Noida"))

{ System.out.println("Your city is Noida"); }

else

{ System.out.println(address.split(",")[0]); }

else

{ System.out.println("You are not living in India"); }}}


Switch Statement:
● The switch statement contains multiple blocks of code called cases and a single
case is executed based on the variable which is being switched.
● The switch statement is easier to use instead of if-else-if statements. It also enhances
the readability of the program
● The case variables can be int, short, byte, char, or enumeration. String type is
also supported since version 7 of Java. Cases cannot be duplicate
● Default statement is executed when any of the case doesn't match the value of
expression. It is optional.
● Break statement terminates the switch block when the condition is satisfied.
It is optional, if not used, next case is executed.
● While using switch statements, we must notice that the case expression will be of the
same type as the variable. However, it will also be a constant value.
Student.java
public class Student {

public static void main(String[] args) {

int num = 2;

switch (num){

case 0:

System.out.println("number is 0");

break;

case 1:

System.out.println("number is 1");

break;

default:

System.out.println(num); } } }
Loop Statements
● In programming, sometimes we need to execute the block of
code repeatedly while some condition evaluates to true.
● Loop statements are used to execute the set of instructions in a
repeated order.
● The execution of the set of instructions depends upon a particular
condition.
● In Java, we have three types of loops that execute similarly.
However, there are differences in their syntax and condition
checking time.
1. for loop
2. while loop
3. do-while loop
for loop
● It enables us to initialize the loop variable, check the
condition, and increment/decrement in a single line of code.
● We use the for loop only when we exactly know the number of
times, we want to execute the block of code.

for(initialization, condition, increment/decrement)

//block of statements

}
The flow chart for the for-loop is given below.
Calculation.java
class Calculation {

public static void main(String[] args) {

int sum = 0;

for(int j = 1; j<=10; j++)

sum = sum + j;

System.out.println("The sum of first 10 natural numbers is " + sum);

}
Find a factorial using for loop
import java.util.Scanner; // Factorial using For Loop

class Factorial { int fact = 1;

public static void main(String[] args) { for (int i = 1; i <= num; i++) {

Scanner sc = new Scanner(System.in); fact *= i; }

// Ask for input System.out.println("Factorial using For Loop: " + fact);

System.out.println ("Enter a number :"); sc.close();

int num = sc.nextInt(); }

}
Java while loop
● The while loop is also used to iterate over the number of statements multiple
times. However, if we don't know the number of iterations in advance, it
is recommended to use a while loop.
● It is also known as the entry-controlled loop since the condition is checked at
the start of the loop. If the condition is true, then the loop body will be
executed; otherwise, the statements after the loop will be executed.

The syntax of the while loop is given below.

while(condition){

//looping statements

}
Calculation .java
public class Calculation {

public static void main(String[] args) {

int i = 0;

System.out.println("Printing the list of even numbers up to 10 \n");

while(i<=10) {

System.out.println(i);

i = i + 2;

}
Find a factorial using for loop
import java.util.Scanner; int fact = 1;

class Factorial { int i = 1;

public static void main(String[] args) { while (i <= num)

Scanner sc = new Scanner(System.in); { fact *= i;

// Ask for input i++; }

System.out.print("Enter a number :"); System.out.println("Factorial using While Loop: " + fact);

int num = sc.nextInt(); sc.close();

}
do-while loop
● The do-while loop checks the condition at the end of the loop after executing
the loop statements.
● When the number of iteration is not known and we have to execute the loop at least
once, we can use do-while loop.
● It is also known as the exit-controlled loop since the condition is not checked in
advance. The syntax of the do-while loop is given below.

do

//statements

} while (condition);
The flow chart of the do-while loop is given in the following
image.
Calculation.java
class Calculation {

public static void main(String[] args) {

int i = 0;

System.out.println("Printing the list of even numbers upto 10 \n");

do {

System.out.println(i);

i = i + 2;

}while(i<=10);

}
Find a factorial using for loop
int fact = 1;
import java.util.Scanner;
int j = 1;
class Factorial {
do {
public static void main(String[] args) {
fact*= j;
Scanner sc = new Scanner(System.in);
j++; }
// Ask for input
while (j <= num);
System.out.print("Enter a number :");
System.out.println("Factorial using Do-While Loop: " + fact);
int num = sc.nextInt();
sc.close(); } }
Jump Statements

● Jump statements are used to transfer the control of the


program to the specific statements.
● In other words, jump statements transfer the execution
control to the other part of the program.
There are two types of jump statements in Java, i.e.,
1) break and
2) continue.
Java break statement
● The break statement is used to break the current flow of
the program and transfer the control to the next
statement outside a loop or switch statement.
● The break statement cannot be used independently in the
Java program, i.e., it can only be written inside the loop
or switch statement.
BreakExample.java

public class Breakexample {

public static void main(String[] args) {

for(int i = 0; i<= 10; i++) {

System.out.println(i);

if(i==6) {

break;

}
Java continue statement

● Unlike break statement, the continue statement doesn't


break the loop, whereas,
● it skips the specific part of the loop and
● jumps to the next iteration of the loop immediately.
class Main {

public static void main(String[] args)

{ for (int i = 1; i <= 10; ++i)

if (i > 4 && i < 9)

{ continue; }

System.out.println(i);

}
Java Arrays
● Java array is an object which contains elements of a similar data
type.
● The elements of an array are stored in a contiguous memory
location.
● It is a data structure where we store similar elements.
● We can store only a fixed set of elements in a Java array.
● Array in Java is index-based, the first element of the array is
stored at the 0th index, 2nd element is stored on 1st index and so
on.
Example of Java Array

class Testarray{

public static void main(String args[]){

int a[]=new int[5];//declaration and instantiation

a[0]=10;//initialization

a[1]=20;

a[2]=70;

a[3]=40;

a[4]=50;

for(int i=0;i<a.length;i++)//length is the property of array

System.out.println(a[i]);

}}
Java String
InJava, string is basically an object that represents sequence of char
values. An array of characters works same as Java string. For example:

char[] ch={'j','a','v','a','t','p','o','i','n','t'};

String s=new String(ch);


is same as:

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

● Java ArrayList is a part of collections framework and it is a


class of java.util package.
● It provides us with dynamic arrays in Java.
● Though, it may be slower than standard arrays but can be helpful in
programs where lots of manipulation in array is required.
● The main advantage of ArrayList is, unlike normal arrays, we
don’t need to mention the size when creating ArrayList.
● It automatically adjusts its capacity as elements are added or
removed.
import java.util.ArrayList;
class Main {
public static void main (String[] args) {
// Creating an ArrayList
ArrayList<Integer> a = new ArrayList<Integer>();
a.add(1); // Adding Element in ArrayList
a.add(2);
a.add(3);
System.out.println(a); // Printing ArrayList } }
LinkedList in Java

● Linked List is a part of the Collection framework present in


java.util package.
● This class is an implementation of the LinkedList data structure which is a
linear data structure where the elements are not stored in contiguous
locations and every element is a separate object with a data part and
address part.
● The elements are linked using pointers and addresses and each element is
known as a node.
Java program to add elements to a LinkedList
import java.util.LinkedList;
public class AddElements {
public static void main(String[] args) { // Main driver method
LinkedList<String> l = new LinkedList<String>(); // Creating a
LinkedList
l.add("One"); // Adding elements to the LinkedList using
add() method
l.add("Two");
l.add("Three");
l.add("Four");
l.add("Five");
System.out.println(l); // Printing the LinkedList
}
}
List Iterator class
public interface ListIterator<E extends Iterator<E>

● An iterator for lists that allows the programmer to traverse the list in either
direction, modify the list during iteration, and obtain the iterator's current
position in the list.
● A ListIterator has no current element; its cursor position always lies between the
element that would be returned by a call to previous() and the element that would be
returned by a call to next().
● An iterator for a list of length n has n+1 possible cursor positions, as illustrated by the
carets (^) below:
Element(0) Element(1) Element(2) ... Element(n-1)

cursor positions: ^ ^ ^ ^ ^

● Note that the remove() and set(Object) methods are not defined in terms of the cursor
position; they are defined to operate on the last element returned by a call to next() or
previous().
● This interface is a member of the Java Collections Framework.
Java ListIterator
Like Iterator, ListIterator is a Java Iterator, which is used to iterate elements one-by-one from a List
implemented object.
● It is available since Java 1.2.
● It extends Iterator interface.
● It is useful only for List implemented classes.
● Unlike Iterator, It supports all four operations: CRUD (CREATE, READ, UPDATE and DELETE).
● Unlike Iterator, It supports both Forward Direction and Backward Direction iterations.
● It is a Bi-directional Iterator.
● It has no current element; its cursor position always lies between the element that would be
returned by a call to previous() and the element that would be returned by a call to next().

NOTE:- What is CRUD operations in Collection API?


● CREATE: Adding new elements to Collection object.
● READ: Retrieving elements from Collection object.
● UPDATE: Updating or setting existing elements in Collection object.
● DELETE: Removing elements from Collection object.
Java ListIterator Class Diagram
In Java, ListIterator is an interface in Collection API. It extends Iterator interface. To support Forward and Backward
Direction iteration and CRUD operations, it has the following methods. We can use this Iterator for all List implemented
classes like ArrayList, CopyOnWriteArrayList, LinkedList, Stack, Vector, etc.
Java ListIterator Methods
Java ListIterator interface has the following Methods.
● void add(E e): Inserts the specified element into the list.
● boolean hasNext(): Returns true if this list iterator has more elements when traversing the list in
the forward direction.
● boolean hasPrevious(): Returns true if this list iterator has more elements when traversing the
list in the reverse direction.
● E next(): Returns the next element in the list and advances the cursor position.
● int nextIndex(): Returns the index of the element that would be returned by a subsequent call to
next().
● E previous(): Returns the previous element in the list and moves the cursor position backwards.
● int previousIndex(): Returns the index of the element that would be returned by a subsequent
call to previous().
● void remove(): Removes from the list the last element that was returned by next() or previous().
● void set(E e): Replaces the last element returned by next() or previous() with the specified
element.
import java.util.*;
// for-each loop creates
public class ListIteratorDemo { Internal Iterator here.
for (String s :
// Main driver method names) {
public static void main(String[] args)
{ System.out.println(s);
// Creating a list of names }
List<String> names = new LinkedList<>(); }
}
names.add("Welcome");
names.add("To");
names.add("Gfg");
// Getting ListIterator
ListIterator<String> namesIterator = names.listIterator();

// Traversing elements using next() method


while (namesIterator.hasNext()) {
System.out.println(namesIterator.next());
}
ListIterator is a bi-directional iterator. For this functionality, it has two kinds
of methods:

1. Forward direction iteration

● hasNext(): This method returns true when the list has more elements to traverse while
traversing in the forward direction
● next(): This method returns the next element of the list and advances the position of
the cursor.
● nextIndex(): This method returns the index of the element that would be returned on
calling the next() method.

2. Backward direction iteration

● hasPrevious(): This method returns true when the list has more elements to traverse
while traversing in the reverse direction
● previous(): This method returns the previous element of the list and shifts the cursor
one position backward.
● previousIndex(): This method returns the index of the element that would be returned
import java.util.*;
// Traversing elements, the iterator is
at the end at this point
public class GFG { System.out.println("Backward Direction
Iteration:");
public static void main(String[] args) while (listIterator.hasPrevious())
{ {
// list of names
List<String> names = new System.out.println(listIterator.previous()
LinkedList<>(); );
names.add("learn"); }
names.add("from"); }
names.add("Geeksforgeeks"); }

// Getting ListIterator
ListIterator<String> listIterator
= names.listIterator();
// Traversing elements
System.out.println("Forward
Direction Iteration:");
while (listIterator.hasNext()) {

System.out.println(listIterator.next());
}
Java HashSet
Java HashSet class is used to create a collection that uses a hash table for storage. It inherits
the AbstractSet class and implements Set interface.

The important points about Java HashSet class are:

○ HashSet stores the elements by using a mechanism called hashing.


○ HashSet contains unique elements only.
○ HashSet allows null value.
○ HashSet class is non synchronized.
○ HashSet doesn't maintain the insertion order. Here, elements are inserted on the basis of
their hashcode.
○ HashSet is the best approach for search operations.
○ The initial default capacity of HashSet is 16, and the load factor is 0.75.

Difference Between List and Set


A list can contain duplicate elements whereas Set contains unique elements only.
Hierarchy of HashSet class
The HashSet class extends AbstractSet class which implements Set interface.
The Set interface inherits Collection and Iterable interfaces in hierarchical order.

● A HashSet in Java is a collection class that implements


the Set interface, which means it stores a collection of
unique elements.
● It does not allow duplicate elements. Internally, a
HashSet uses a HashMap to store its elements.
● Each element in the HashSet is stored as a key in the
HashMap, with a dummy value associated with it.
● HashSet uses the hash code of an element to
determine its position in the underlying hash table,
which allows for constant-time performance for basic
operations like add, remove, and contains, assuming a
good hash function.
● One of the key features of a HashSet is its ability to maintain a collection of
elements without any specific order. It means that the order in which elements
are added to a HashSet is not preserved when iterating over the elements.
● If we need to maintain the insertion order, we can use a LinkedHashSet, which
is another implementation of the Set interface that maintains the insertion
order of its elements.
● HashSet does not allow null elements, but it can contain a single null value.
● If we attempt to add a duplicate element to a HashSet, the add method will
return false and the HashSet will remain unchanged.
● HashSet also provides methods for set operations like union, intersection, and
difference. However, unlike some other collection classes, HashSet is not
synchronized, meaning that it is not thread-safe.
● If you need a synchronized (thread-safe) version of HashSet, we can use the
Collections.synchronizedSet method to wrap your HashSet with a synchronized
set.
Java HashSet Example
Let's see a simple example of HashSet. Notice, the elements iterate in an unordered collection.

import java.util.*;
class HashSetExample1{
public static void main(String args[]){

//Creating HashSet and adding Output:


elements Five
HashSet<String> set=new HashSet(); One
Four
set.add("One"); Two
set.add("Two"); Three

set.add("Three");
set.add("Four");
set.add("Five");
Iterator<String> i=set.iterator();

while(i.hasNext())
{
System.out.println(i.next());
Ignoring Duplicate Elements
In this example, we see that HashSet does not allows duplicate elements.

import java.util.*;
class HashSetExample2{ Output:
public static void main(String args[]){
Ajay
//Creating HashSet and adding elements Vijay
HashSet<String> set=new HashSet<String>(); Ravi
set.add("Ravi");
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
//Traversing elements
Iterator<String> itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Removing Elements HashSet<String> set1=new
Here, we see different ways to remove an element. HashSet<String>();
set1.add("Ajay");
set1.add("Gaurav");
set.addAll(set1);
import java.util.*;
System.out.println("Updated List: "+set);
class HashSetExample3{
public static void main(String args[]){ //Removing all the new elements from
HashSet<String> set=new HashSet<String>(); HashSet
set.add("Ravi"); set.removeAll(set1);
set.add("Vijay"); System.out.println("After invoking
set.add("Arun"); removeAll() method: "+set);
//Removing elements on the basis of
set.add("Sumit");
specified condition
System.out.println("An initial list of set.removeIf(str->str.contains("Vijay"));
elements: "+set); System.out.println("After invoking
//Removing specific element from HashSet removeIf() method: "+set);
set.remove("Ravi"); //Removing all the elements available in
System.out.println("After invoking remove(object) the set
method: "+set); set.clear();
System.out.println("After invoking clear()
method: "+set);
}
An initial list of elements: [Vijay, Ravi, Arun, Sumit]

After invoking remove(object) method: [Vijay, Arun, Sumit]

Updated List: [Vijay, Arun, Gaurav, Sumit, Ajay]

After invoking removeAll() method: [Vijay, Arun, Sumit]

After invoking removeIf() method: [Arun, Sumit]

After invoking clear() method: []


Java HashSet from another Collection
import java.util.*;
class HashSetExample4{
public static void main(String args[]){
ArrayList<String> list=new
ArrayList<String>();
list.add("Ravi");
list.add("Vijay");
list.add("Ajay");
Output:
HashSet<String> set=new HashSet(list);
Vijay
set.add("Gaurav");
Ravi
Iterator<String> i=set.iterator();
Gaurav
while(i.hasNext())
{ Ajay
System.out.println(i.next());
}
}
}
Java HashSet Example: Book
Let's see a HashSet example where we are adding books to set and printing all the books.

//Adding Books to HashSet


import java.util.*; set.add(b1);
class Book { set.add(b2);
int id; set.add(b3);
String name,author,publisher; //Traversing HashSet
int quantity; for(Book b:set){
public Book(int id, String name, String author, String publisher, int System.out.println(b.id+"
quantity) { "+b.name+" "+b.author+"
this.id = id; "+b.publisher+" "+b.quantity);
this.name = name; }
this.author = author; }
this.publisher = publisher; }
this.quantity = quantity;
}
}
public class HashSetExample { Output:
public static void main(String[] args) {
HashSet<Book> set=new HashSet<Book>(); 101 Let us C Yashwant Kanetkar BPB 8
//Creating Books 102 DCN Forouzan Mc Graw Hill 4
Book b1=new Book(101,"Let us C","Yashwant 103 Operating System Galvin Wiley 6
Kanetkar","BPB",8);
Book b2=new Book(102,"DCN", "Forouzan","Mc Graw
Hill",4);
Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
Java Vector
● Vector is like the dynamic array which can grow or shrink its size. Unlike array, we can
store n-number of elements in it as there is no size limit. It is a part of Java Collection
framework since Java 1.2. It is found in the java.util package and implements the List interface,
so we can use all the methods of List interface here.
● It is recommended to use the Vector class in the thread-safe implementation only. If
you don't need to use the thread-safe implementation, you should use the ArrayList, the
ArrayList will perform better in such case.
● The Iterators returned by the Vector class are fail-fast. In case of concurrent modification, it
fails and throws the ConcurrentModificationException.
● It is similar to the ArrayList, but with two differences-
● Vector is synchronized. Synchronized basically means that only one thread can
access methods of that particular class at any given time. A Synchronized class is a
thread-safe class.
● Non-Synchronized means that two or more threads can access the methods of that
particular class at any given time.
● Java Vector contains many legacy methods that are not the part of a collections framework.
import java.util.*;
public class VectorExample {
public static void main(String args[]) {
//Create a vector
Vector<String> vec = new Vector<String>();
//Adding elements using add() method of List
vec.add("Tiger");
vec.add("Lion");
vec.add("Dog");
vec.add("Elephant");
//Adding elements using addElement() method of Vector
vec.addElement("Rat");
vec.addElement("Cat");
vec.addElement("Deer");

System.out.println("Elements are: "+vec);


}
}
1) ArrayList is not synchronized. Vector is synchronized.

2) ArrayList increments 50% of current array Vector increments 100% means doubles the
size if the number of elements exceeds from array size if the total number of elements
its capacity. exceeds than its capacity.

3) ArrayList is not a legacy class. It is Vector is a legacy class.


introduced in JDK 1.2.

4) ArrayList is fast because it is non- Vector is slow because it is synchronized, i.e.,


synchronized. in a multithreading environment, it holds the
other threads in runnable or non-runnable
state until current thread releases the lock of
the object.

5) ArrayList uses the Iterator interface to A Vector can use the Iterator interface or
traverse the elements. Enumeration interface to traverse the
elements.

You might also like