JAVA
JAVA
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.
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.
1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
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
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 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.
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
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.
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.
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.
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.
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.
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
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.
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.
//example
}
}
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 −
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 −
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.
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 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:
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
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:
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.
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
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
If data is organized in a systematic manner, it will become structured and meaningful. Therefore,
meaningful or processed data is called information.
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”
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.
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.
• 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.
• 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.
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
• One-dimensional Array: It has only one row of elements. It is stored in ascending storage location.
• 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
• 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
• Storage of matrices.
SORTING
- refers to ordering data in an increasing or decreasing fashion according to some linear relationship
among the data items
UNORDERED
➢ 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:
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.
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.
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.
2. Accessing Elements:
3. Modifying Elements:
5. Array length:
6. Copying Arrays:
- using loop:
-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.
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:
- 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:
- 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.
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
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.
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).
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.
• 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
• 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.
- 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