0% found this document useful (0 votes)
5 views20 pages

JAVA

The document serves as a comprehensive guide to Java programming, covering key concepts such as variables, data types, operators, control flow statements, and Java-specific conventions like case sensitivity and naming conventions. It explains the different types of variables (local, instance, static), data types (primitive and non-primitive), and access modifiers (private, default, protected, public). Additionally, it details control flow mechanisms including if statements, switch cases, loops, and input handling from the console.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views20 pages

JAVA

The document serves as a comprehensive guide to Java programming, covering key concepts such as variables, data types, operators, control flow statements, and Java-specific conventions like case sensitivity and naming conventions. It explains the different types of variables (local, instance, static), data types (primitive and non-primitive), and access modifiers (private, default, protected, public). Additionally, it details control flow mechanisms including if statements, switch cases, loops, and input handling from the console.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

CPEN 60-65 REVIEWER

CPEN 60 LESSON

VARIABLES

Note about Java: Case sensitivity − java is case sensitive, which means identifier hello and Hello
would have different meaning in java.

Class names − for all class names the first letter should be in upper case. If several words are used
to form a name of the class, each inner word's first letter should be in upper case. Example: class
Helloworld

Method names − all method names should start with a lower case letter. If several words are used
to form the name of the method, then each inner word's first letter should be in upper case.

Example: public void myMethodName()

Program file name − Name of the program file should exactly match the class name. When saving
the file, you should save it using the class name (remember java is case sensitive) and append '.
Java' to the end of the name (if the file name and the class name do not match, your program will
not compile).

But please make a note that in case you do not have a public class present in the file then file name
can be different than class name. It is also not mandatory to have a public class in the file.

Comments in java

Java supports single-line and multi-line comments very similar to C and C++. All characters
available inside any comment are ignored by java compiler.

Example

/*

*
*
*/

//

/* ... */

Java Keywords: Also known as reserved words. Keywords are particular words that act as a key
to a code. These are predefined words by Java so they cannot be used as a variable or object name
or class name. Here are the list of keywords in Java.
Java Package

A java package is a group of similar types of classes, interfaces and sub-packages. Package in java
can be categorized in two form, built-in package and user-defined package. There are many built-
in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.

Advantage of Java Package:

1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.

2) Java package provides access protection.

3) Java package removes naming collision.

Java Identifiers

All java components require names. Names used for classes, variables, and methods are called
identifiers..

In java, there are several points to remember about identifiers. They are as follows −

• All identifiers should begin with a letter (A to Z or a to z), currency character ($) or an underscore
(_).
• After the first character, identifiers can have any combination of characters.
• A key word cannot be used as an identifier.
• Most importantly, identifiers are case sensitive.
• Examples of legal identifiers: age, $salary, _value, __1_value.
• Examples of illegal identifiers: 123abc, -salary.

Java Modifiers
Modifiers are keywords that you add to those definitions to change their meanings. The access
modifiers in Java specifies the accessibility or scope of a field, method, constructor, or class. We
can change the access level of fields, constructors, methods, and class by applying the access
modifier on it.
• Java Access Modifiers – Private, Default, Protected, Public
• Non Access Modifiers – Static, Final, Abstract, Synchronized

Java Access Modifiers


• Private: The access level of a private modifier is only within the class. It cannot be accessed from
outside the class.

Java Access Modifiers


• Default: The access level of a default modifier is only within the package. It cannot be accessed
from outside the package. If you do not specify any access level, it will be the default

Java Access Modifiers


• Protected: The access level of a protected modifier is within the package and outside the package
through child class. If you do not make the child class, it cannot be accessed from outside the
package.

Java Access Modifiers


• Public: The access level of a public modifier is everywhere. It can be accessed from within the
class, outside the class, within the package and outside the package. The public access modifier is
accessible everywhere. It has the widest scope among all other modifiers.
Variables - a container which holds the value while the Java program is executed. A variable is
assigned with a data type. Variable is a name of memory location. A variable is the name of a
reserved area allocated in memory. In other words, it is a name of the memory location. It is a
combination of "vary + able" which means its value can be changed.

Examples of declarations of variables:

int a, b, c; // Declares three ints, a, b, and c.


int a = 25, b = 15; // Example of initialization
byte B = 21; // initializes a byte type variable B.
double pi = 3.14159; // declares and assigns a value of PI.
char a = 'a'; // the char variable a is initialized with value ‘a’

Three types of variables in java: local, instance and static.

Types of Variables:

*Local Variable

A variable declared inside the body of the method. Use this variable ONLY within that method
and the other methods in the class are not even aware that the variable exists. A local variable
cannot be defined with “static” keyword.

*Instance Variable

A variable declared inside the class but outside the body of the method, is called an instance
variable. It is not declared as static. It is called an instance variable because its value is instance-
specific and is not shared among instances.

*Static Variable

A variable that is declared as static is called a static variable. It cannot be local. You can create a
single copy of the static variable and share it among all the instances of the class. Memory
allocation for static variables happens only once when the class is loaded in the memory.

Data types in java

Data types specify the different sizes and values that can be stored in the variable. There are two
types of data types in java:

1. Primitive Data Types: the primitive data types include boolean, char, byte, short, int, long, float
and double.

2. Non-primitive data types: the non-primitive data types include classes, interfaces, and arrays.

Boolean data type:

The boolean data type is used to store only two possible values: true and false. This data type is
used for simple flags that track true/false conditions.
The boolean data type specifies one bit of information, but its "size" can't be defined precisely.
Example: boolean one = false

Byte data type

The byte data type is an example of primitive data type. It is an 8-bit signed two's complement
integer. Its value-range lies between -128 to 127 (inclusive). Its minimum value is -128 and
maximum value is 127. Its default value is 0.

The byte data type is used to save memory in large arrays where the memory savings is most
required. It saves space because a byte is 4 times smaller than an integer. It can also be used in
place of "int" data type.

Example: byte a = 10, byte b = -20

Short data type

The short data type is a 16-bit signed two's complement integer. Its value-range lies between -
32,768 to 32,767 (inclusive). Its minimum value is -32,768 and maximum value is 32,767. Its
default value is 0.
The short data type can also be used to save memory just like byte data type. A short data type is
2 times smaller than an integer.

Example: short x = 10000, short y = -5000

Int data type

The int data type is a 32-bit signed two's complement integer. Its value-range lies between -
2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its minimum value is -
2,147,483,648 and maximum value is 2,147,483,647. Its default value is 0.
The int data type is generally used as a default data type for integral values unless if there is no
problem about memory.

Example: int a = 600000, int b = -500000

Long Data Type

The long data type is a 64-bit two's complement integer. Its value-range lies between -
9,223,372,036,854,775,808(-2^63) to 9,223,372,036,854,775,807(2^63 -1)(inclusive). Its
minimum value is - 9,223,372,036,854,775,808and maximum value is 9,223,372,036,854,775,807.
Its default value is 0. The long data type is used when you need a range of values more than those
provided by int.

Example: long a = 2000000, long b = -3000000

Float Data Type

The float data type is a single-precision 32-bit IEEE 754 floating point. Its value range is unlimited.
It is recommended to use a float (instead of double) if you need to save memory in large arrays of
floating point numbers. The float data type should never be used for precise values, such as
currency. Its default value is 0.0f.

Example: float x = 234.5f


Double Data Type

The double data type is a double-precision 64-bit IEEE 754 floating point. Its value range is
unlimited. The double data type is generally used for decimal values just like float. The double
data type also should never be used for precise values, such as currency. Its default value is 0.0d.
Example: double d1 = 32.2

Char Data Type

The char data type is a single 16-bit unicode character. Its value-range lies between '\u0000' (or 0)
to '\uffff' (or 65,535 inclusive).The char data type is used to store characters.

Example: char MyVar= ‘A’

Java Operators:
Operator in Java is a symbol that is used to perform operations.

•Arithmetic Operators
•Relational Operators
•Bitwise Operators
•Logical Operators
•Assignment Operators
•Misc Operators

Operator Precedence

Arithmetic Operators - Arithmetic operators are used in mathematical expressions in the same
way that they are used in algebra. Assume integer variable A holds 10 and variable B holds 20,
then:
Relational Operators – used for “comparing” variables and expressions Assume integer variable
A holds 10 and variable B holds 20,
then:

Bitwise Operators – Java defines several bitwise operators, which can be applied to the integer
types, long, int, short, char, and byte. Bitwise operator works on bits and performs bit-by-bit
operation. Assume if A = 60, B = 13;

Logical Operators – used to compare logical expressions. Assume Boolean variables A holds
true and variable B holds false
Misc. Operators:
Conditional operator (?:) - Conditional operator is also known as the ternary operator. This
operator consists of three operands and is used to evaluate Boolean expressions. The goal of the
operator is to decide, which value should be assigned to the variable.

variable x = (expression) ? value if true : value if false

//example

public class Test {

public static void main(String args[]) {


int a, b;
a = 10;
b = (a == 1) ? 20: 30;
System.out.println( "Value of b is : " + b );

b = (a == 10) ? 20: 30;


System.out.println( "Value of b is : " + b );

}
}

//output: Value of b is : 30 Value of b is : 20

Misc. Operators:

instanceof Operator - This operator is used only for object reference variables. The operator
checks whether the object is of a particular type (class type or interface type). instanceof operator
is written as −

( Object reference variable ) instanceof (class/interface type)

If the object referred by the variable on the left side of the operator passes the IS-A check for the
class/interface type on the right side, then the result will be true.

Following is an example −

public class Test {

public static void main(String args[]) {

String name = "James";

// following will return true since name is type of String

boolean result = name instanceof String;

System.out.println( result );

}
}
//true
CONTROL FLOW

Java Control statements control the flow of execution in a java program, based on data values and
conditional logic used. There are three main categories of control flow statements;
Selection statements: if, if-else and switch.
Loop Statements: while, do-while and for.
Transfer statements: break, continue, return, try-catch-finally and assert.

If Statement
The if statement executes a block of code only if the specified expression is true. If the value is
false, then the if block is skipped and execution continues with the rest of the program.

The simple if statement has the following syntax:


if (<conditional expression>)
<statement action>

If-else Statement

The if/else statement is an extension of the if statement. If the condition in the if statement fails,
the statements in the else block are executed.

The if-else statement has the following syntax:


if (<conditional expression>)
<statement action>
else <statement action>

Switch Case Statement

The switch case statement is also called as multi-way branching statement with several choices. A
switch statement is easier to implement than a series of if/else statements. The switch statement
begins with a keyword, followed by an expression that equates to a no long integral value.
After the controlling expression, there is a code block that contains zero or more labeled cases.
Each label must equate to an integer constant and each must be unique. When the switch statement
executes, it compares the value of the controlling expression to the values of each case label.
The program will select the value of the case label that equals the value of the controlling
expression and branch down that path to the end of the code block. If none of the case label values
match, then none of the codes within the switch statement code block will be executed.

Java includes a default label to use in cases where there are no matches. A nested switch within a
case block of an outer switch is also allowed. When executing a switch statement, the flow of the
program falls through to the next case. So, after every case, you must insert a break statement.

While Statements

The while statement is one of the looping constructs control statement that executes a block of
code while a condition is true. The loop will stop the execution if the testing expression evaluates
to false. The loop condition must be a boolean expression. The syntax of the while loop is:

while(<loop condition>) <statements>

Do-While loop Statement


The do-while loop is similar to the while loop, except that the test condition is performed at the
end of the loop instead of at the beginning. The do—while loop executes at least once without
checking the condition.

It begins with the keyword do, followed by the statements that making up the body of the loop.
Finally, the keyword while and the test expression completes the do-while loop. When the loop
condition becomes false, the loop is terminated and execution continues with the statement
immediately following the loop:

do
<loop condition>
While (<loop condition>);

For Loop

The for loop is a looping construct which can execute a set of instructions for a specified number
of times. It is a counter controlled loop.

Syntax is as follows:
for(<initialization>;<loop condition>;<increment expression>)
<loop body>

Initialization statement executes once before the loop begins. The <initialization> section can also
be a comma-separated list of expression statements.

Test expression, as long as the expression of statement is true, the loop will continue. If this
expression is evaluated as false the first time, the loop will never be executed.

Increment (update) expression that automatically executes after each repetition of the loop body.

All the sections in the for-header are optional. Any one of them can be left empty, but the two
semicolons are mandatory.

Continue Statement

A continue statement stops the current iteration of a loop (while, do or for) and causes execution
to resume at the top of the nearest enclosing loop. The continue statement can be used when you
do not want to execute the remaining statements in the loop, but you do not want to exit the loop
itself.

Syntax:
continue; //the unlabeled form
continue <label>; //the labeled form

It is possible to use a loop with a label and then use the label in the continue statement. The label
name is optional, and is usually only used when you wish to return to the outermost loop in a series
of nested loops.

Break Statement

The break statement terminates the enclosing loop (for, while, do or switch statement). Break
statement can be used when we want to jump immediately to the statement following the enclosing
control structure. As continue statement, can also provide a loop with a label, and then use the
label in break statement. The label name is optional, and is usually only used when you wish to
terminate the outermost loop in a series of nested loops.

Syntax:
break; //the unlabeled form
Break <label>; // labeled form

READING INPUT FROM CONSOLE


Reading input from the console enables the program to accept input from the user
Java uses System.out to refer to the standard output device, and System.in to the standard input
device. By default, the output device is the display monitor, and the input device is the keyboard.
To perform console output, you simply use the println method to display a primitive value or a
string to the console. To perform console input, you need to use the Scanner class to create an
object to read input from System.in

Scanner input = new Scanner(System.in);

The syntax new Scanner(System.in) creates an object of the Scanner type. The syntax Scanner
input declares that input is a variable whose type is Scanner. The whole line Scanner input = new
Scanner(System.in) creates a Scanner object and assigns its reference to the variable input. An
object may invoke its methods. To invoke a method on an object is to ask the object to perform a
task. You can invoke the nextDouble() method to read a double value as follows:

double radius = input.nextDouble();

The Scanner class is in the java.util package. It is imported in line 1. Line 6 creates a Scanner
object. Note the import statement can be omitted if you replace Scanner by java. util.Scanner in
line 6. Line 9 displays a string "Enter a number for radius: " to the console. This is known as a
prompt, because it directs the user to enter an input. Your program should always tell the user what
to enter when expecting input from the keyboard. Recall that the print method in line 9 is identical
to the println method, except that println moves to the beginning of the next line after displaying
the string, but print does not advance to the next line when completed. Line 6 creates a Scanner
object. The statement in line 10 reads input from the keyboard.

double radius = input.nextDouble()

After the user enters a number and presses the Enter key, the program reads the number and assigns
it to radius.
The Scanner class is in the java.util package. It is imported in line 1. There are two types of import
statements: specific import and wildcard import. The specific import specifies a single class in the
import statement. For example, the following statement imports Scanner from the package java.util.
import java.util.Scanner;

The wildcard import imports all the classes in a package by using the asterisk as the wildcard. For
example, the following statement imports all the classes from the package java.util.

import java.util.*;

CPEN 65 LESSON

Introduction to Java Programming Algorithms and Dimensionality of


Arrays

DATA

Based on Dictionary: The quantities, characters, or symbols on which operations are performed by
a computer, being stored and transmitted in the form of electrical signals and recorded on magnetic,
optical, or mechanical recording media.

INFORMATION

It gives meaning and increases the accuracy of the data.

Example: I will be an Engineer.

DATA BECOMES INFORMATION

If data is organized in a systematic manner, it will become structured and meaningful. Therefore,
meaningful or processed data is called information.

Data: !SRETHGIF ERA EW ,TNAROLAV ERA EW .LLAT DNATS

Information: STAND TALL. WE ARE VALORANT, WE ARE FIGHTERS!

Data needs to be managed to produce some meaningful information. To provide a proper way to
structure the data, we need to know about “Data Structure”

BASIC CONCEPT OF DATA STRUCTURE


Data structure is a branch of computer science. The study of data structure helps you to understand
how data is organized and how data flow is managed to increase efficiency of any process or
program. Data structure is the structural representation of logical relationship between data
elements. This means that a data structure organizes data items based on the relationship between
the data elements.

NEEDS FOR DATA STRUCTURE

• It gives different level of organization data.


• It tells how data can be stored and accessed in its elementary level.
• Provide operation on group of data, such as adding an item, looking up highest priority item, etc.
• Provide a means to manage huge amount of data efficiently.
• Provide fast searching and sorting of data.

GOALS OF DATA STRUCTURE

Correctness – Data structure is designed such that it operates for all kinds of input, which is based
on the domain of interest. In other words, correctness forms the primary goal of data structure,
which always depends on the specific problems that the data structure is intended to solve.

Efficiency – Data structure also needs to be efficient. It should process the data at high speed
without utilizing much of the computer resources such as memory space. In a real-time state, the
efficiency of a data structure is an important factor that determines the success and failure of the
process.

FEATURES OF DATA STRUCTURE

Robustness – Generally, all computer programmers wish to produce software that generates correct
output for every possible input provided to it, as well as execute efficiently on all hardware
platforms.

Adaptability – Software evolves due to ever changing market conditions or due to emerging
technologies.

Reusability – By implementing quality data structures, it is possible to develop reusable software,


which tends to be cost effective and time saving

CLASSIFICATION OF DATA STRUCTURE

• Primitive Data Structure – It can be manipulated or operated directly by the machine level
instructions. Basic data types such as integer, real, character, and Boolean come under primitive
data structures. They are also known as simple data types because they consist of characters that
cannot be divided.

• Non-primitive Data Structure - These data structures cannot be operated or manipulated directly
by the machine level instructions. They focus on formation of a set of data elements that is either
homogeneous (same data type) or heterogeneous (different data type). These are further divided
into linear and nonlinear data structure based on the structure and arrangement of data.

CLASSIFICATION OF DATA STRUCTURE

Non-primitive Data Structure


• Linear Data Structure - A data structure that maintains a linear relationship among its elements.
The data is arranged in a linear fashion. But in the memory, the arrangement may not be sequential.

Ex: Arrays, linked lists, stacks, queues.

• Non-linear Data Structure - Non-linear data structure is a kind of data structure in which data
elements are not arranged in a sequential order. There is a hierarchical relationship between
individual data items. Trees and graphs are examples of non-linear data structures.

Ex: Trees and graphs

ARRAY

Array, in general, refers to an orderly arrangement of data elements. It is type of data structure that
stores data elements in adjacent locations. Array is considered as linear data structure that stores
elements of same data types

DIMENSIONALITY OF ARRAY

Arrays can be classified as:

• One-dimensional Array: It has only one row of elements. It is stored in ascending storage location.

• Two-dimensional Array: It consists of multiple rows and columns of data elements.

• Multidimensional Array: Can be defined as array of arrays. Multidimensional arrays are not
bounded to two indices or two dimensions. They can include as many indices as required.

LIMITATIONS OF ARRAY

• Arrays are of fixed size.

• Data elements are stored in contiguous memory locations which may not be always available.

• Insertion and deletion of elements can be problematic because of shifting of elements from their
position

APPLICATIONS OF ARRAY

• Storing list of data elements belonging to same data type.

• Auxiliary storage for other data structures.

• Storage of binary tree elements of fixed count.

• Storage of matrices.

SORTING

- refers to ordering data in an increasing or decreasing fashion according to some linear relationship
among the data items

TWO (2) STEPS OF SORTING


1. Compare two items.

2. Swap two items or copy one item.

UNORDERED

THREE (3) SIMPLE ALGORITHMS

➢ Bubble Sort
➢ Selection Sort
➢ Insertion Sort

BUBBLE SORT

The bubble sort is known to be slow, but it’s conceptually the simplest of the sorting algorithms.
And for that reason, is a good beginning for our exploration of sorting techniques. Rule of bubble
sorting:

1. Compare two players.


2. If the one on the left is taller, swap them.
3. Move on position to the right

Upon the conclusion of the initial pass, the highest individual shall be positioned at the far right of
the line.

SELECTION SORT

Selection Sort is a simple sorting algorithm that works by repeatedly selecting the minimum
element from the unsorted part of the array and placing it at the beginning.

Let's consider the baseball players again. In the selection sort, you can no longer compare only
players standing next to each other. Thus, you'll need to remember a certain player's height.

It repeatedly finds the minimum element in the unsorted part of the array and swaps it with the
element at the current index. This process continues until the entire array is sorted.

INSERTION SORT

Insertion Sort is a simple comparisonbased sorting algorithm that builds the final sorted array one
item at a time. It is an efficient algorithm for small data sets or nearly sorted data but becomes less
efficient as the data size increases.

Insertion Sort works by repeatedly taking an element from the unsorted part of the array and
inserting it into its correct position in the sorted part of the array.

How insertion sort algorithm works:

1. The first element in the array is assumed to be sorted. Take the second element and store it
separately in TEMP.

2. Compare the second element with the first element. If the first element is greater than stored
TEMP, then TEMP should be swapped with first element.
3. Move to the third element. Compare it with the elements to its left in the sorted portion of the
array. Elements will continue to shift to the right if it is greater than TEMP. If TEMP is greater
than the elements to the left, it will be sent back into the array.

4. Continue this process for each element in the array, one at a time, until the entire array is sorted.

Operations on Arrays, Linear and Binary Search

ARRAY OPERATIONS

Once we create and initialize our arrays, we need to learn how to manipulate and use them. There
is a lot we can do with arrays in Java.

1. Declaration and Initialization:

- Declare an array: type[ ] arrayName;


- Initialize an array:

type[ ] arrayName = new type[size];


type[ ] arrayName = {element1, element2, … };

2. Accessing Elements:

- Access an element by its index:


arrayName[index] = element;

3. Modifying Elements:

- Modify an element by its index:


arrayName[index] = newValue;

4. Iterating Through an Array: - using a ‘for’ loop:

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


//do something here

- using an enhanced ‘for’ loop (for-each):


for (type variableName : arrayName) {
//do something here

5. Array length:

- get the length of an array:


arrayName.length;

6. Copying Arrays:

- using loop:

int[] copyArray = new int[originalArray.length];


for (int i = 0; i < originalArray.length; i++) {
copyArray[i] = originalArray[i];

- using ‘System.arraycopy’ or ‘Arrays.copyOf’ methods

7. Adding new element to an array:

-In Java, you cannot directly add elements to an array once it’s been created with a fixed size.
Arrays have a fixed length, and that length cannot be changed dynamically. To "add" elements to
an array, you typically have to create a new array with a larger size and copy the elements from
the old array into the new one.

1. Create a new array with a larger size.


2. Copy the elements from the old array into the new array.
3. Add the new element to the end of the new array

SEARCHING FOR AN ARRAY ELEMENT

Searching for an element in a Java array can be done using various methods, including linear search
and binary search. Linear Search: A linear search is a simple method to find an element in an array.
It involves iterating through the array sequentially until the target element is found. Binary Search:
Binary search is a more efficient method for finding an element in a sorted array. It divides the
array into smaller segments, reducing the search space in each step.

Linear Search:

- Linear searches can work on a data set whether it is sorted or unsorted.

- A linear search will stop running when it finds target or gets to the end of the list.

- A sequential search will potentially have to check every item in the list.

Binary Search:

- Binary searches only work on a sorted list.

- A binary search will cut the list in half after every iteration in which it does not find its target.

- Except in unusual circumstances, a binary search will not need to check all entries.
Recursion

In Java, a method that calls itself is known as a recursive method. And this process is known as
recursion. Recursion is a programming technique in which a function calls itself to solve a problem.

RECURSION – BASE CASE

The base case is the condition that serves as the termination point for the recursion. It's the point
at which the function stops calling itself and returns a result, preventing infinite recursion. Base
cases are essential in recursive algorithms because they ensure that the recursion eventually
terminates and provides a result. Without a base case, the recursive function would keep calling
itself indefinitely, leading to a stack overflow or other unintended consequences.

RECURSION vs ITERATION

ITERATION is a repetition of an internal process while RECURSION is the repetition of a


procedure.

FACTORIAL

The factorial of a non-negative integer is a mathematical operation that calculates the product of
all positive integers from 1 to that integer. It is denoted by an exclamation mark (!)

Linked list

A linked list is a linear data structure that includes a series of connected nodes. Here, each node
stores the data and the address of the next node.

We give the address of the first node a special name called HEAD. Also, the last node in the linked
list can be identified because its next portion points to NULL.

Linked List provides various methods that allow us to perform different operations in linked lists:

• Add Elements
• Access Elements
• Change Elements
• Remove Elements

• Add Elements
- method to add an element (node) at the end of the LinkedList.

• Access Elements get()


- method used to access an element from the Linked List.

• Change Elements set()


- method used to change an element from the Linked List.

• Remove Elements remove()


- method used to remove an element from the Linked List.
Java Stack Data Structure

STACK

Stack is kind of data structure which allows operations on data only at one end. It allows access to
the last inserted data only. Stack is also called LIFO (Last In First Out) data structure and Push
and Pop operations are related in such a way that only last item pushed (added to stack) can be
popped (removed from the stack).

In stack, manipulation always happens on the top of the stack.

CREATING A STACK

In order to create a stack, we must import the java.util.Stack package first. Once we import the
package, here is how we can create a stack in Java.

Stack stacks = new Stack(); // older Java version


Stack stacks = new Stack<>(); // newer Java version

Where ‘Type’ indicates the stack’s type. For example:


Stack stacks = new Stack<>();
Stack stacks = new Stack<>();

• push() Method
- To add an element to the top of the stack, we use the push() method.

• pop() Method
- This method is used to ‘pop’ or remove an element from the top of the stack.
• peek() Method
- The peek operation returns the top of the stack without removing the element

• isEmpty() / empty() Method


- Is used to check whether a stack is empty or not. The method is of boolean type and returns
true if the stack is empty else false

• search() Method
- We can search for an element on the stack using the search() method. The method returns
its position if the element is successfully found and returns -1 if the element is absent. This
index is counted from the top of the stack.

STACK ITERATE ELEMENTS


Iterate means to fetch the elements of the stack. We can fetch elements of the stack using three
different methods are as follows:

• Using iterator() Method


• Using forEach() Method
• Using listIterator() Method

- Using the iterator() Method: It is the method of the Iterator interface. It returns an iterator
over the elements in the stack. Before using the iterator() method import the
java.util.Iterator package.

- Using the forEach() Method: Java provides a forEach() method to iterate over the elements.
The method is defined in the Iterable and Stream interface.

- Using the listIterator() Method: This method returns a list iterator over the elements in the
mentioned list (in sequence), starting at the specified position in the list. It iterates the stack
from top to bottom.

QUEUE

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy