BE Java Module -1
BE Java Module -1
Eg:
Step1: get two input
Step 2: compute two numbers
Step 3: display output
Step 4: stop
History of Java
Source: https://thetapacademy.com/java-programming-language/
Java Name History
GreenTalk
James Gosling was leading a team named as 'Green' team. Target of this team was
to create a new project which can. Initially C++ was the original choice to
develop the project. James Gosling wanted to enhance C++ to achieve the target
but due to high memory usage, that idea was rejected and team started with a new
language initially named as GreenTalk. The file extension used as .gt. Later this
language was termed as Oak and finally to Java.
Oak
James Gosling renamed language to Oak. There was an Oak tree in front of his
office. James Gosling used this name as Oak represents solidarity and Oak tree is
the national tree of multiple countries like USA, France, Romania etc. But Oak
technologies already had Oak as a trademark and James team had to brainstrom
another title for the language.
Finally Java
Team put multiple names like DNA, Silk, Ruby and Java. Java was finalized by
the team. James Gosling tabled Java title based on type of espresso coffee bean.
Java is an island in Indonesia where new coffee was discovered termed as Java
coffee. As per James Gosling, Java was among the top choice along with Silk.
Finally Java was selected as it was quite unique and represented the essence of
being dynamic,revolutionary and fun to say.
Sun released the first public implementation as Java 1.0 in 1995. It
promised Write Once, Run Anywhere (WORA), providing no-cost run-times on
popular platforms.
On 13 November, 2006, Sun released much of Java as free and open source
software under the terms of the GNU General Public License (GPL).
On 8 May, 2007, Sun finished the process, making all of Java's core code free and
open-source, aside from a small portion of code to which Sun did not hold the
copyright.
The latest release of the Java Standard Edition is Java SE 21. With the
advancement of Java and its widespread popularity, multiple configurations were
built to suit various types of platforms. For example: J2EE for Enterprise
Applications, J2ME for Mobile Applications.
Java Versions History
Over the period of nearly 30 years, Java has seen many minor and major versions.
JDK
1 1995 Initial Draft version
Beta
23
2 JDK 1.0 Jan A stable variant JDK 1.0.2 was termed as JDK 1
1996
19
Major features like JavaBeans, RMI, JDBC, inner
3 JDK 1.1 Feb
classes were added in this release.
1997
8
HotSpot JVM, JNDI, JPDA, JavaSound and support for
5 JDK 1.3 May
Synthetic proxy classes were added.
2000
JDK 1.5 30
Various new features were added to the language like
7 or J2SE Sep
foreach, var-args, generics etc.
5 2004
21
JAVA SE Module system introduced which can be applied to JVM
11 Sep
9 platform.
2017
17
JAVA SE Feature added - Text Blocks (Multiline strings),
15 Sep
13 Enhanced Thread-local handshakes.
2019
15
JAVA SE Feature added - Sealed Classes, Hidden Classes, Foreign
17 Sep
15 Function and Memory API (Incubator).
2020
16 Feature added as preview - Records, Pattern Matching
JAVA SE
18 Mar for switch, Unix Domain Socket Channel (Incubator)
16
2021 etc.
20
JAVA SE Feature added - Record pattern, Vector API (Fourth
21 Sep
19 incubator), Structured Concurrency (Incubator) etc.
2022
• The documentation comments are understood by the Javadoc tool and can be used to
create HTML-based documentation.
Data types: The data type tells the compiler about the type of data to be stored
and the required memory. To store and manipulate different types of data, all
variables must have specified data types.
• Primitive Data Types
• Reference/Object Data Types
Primitive data types are predefined by the language and named by a keyword.
There are eight primitive data types supported by Java
Type Siz Range Min Max
e in
bits
Byte 8 -128 to -128 127
127
Short 16 -32,768 -32768 32767
to
32,767
Int 32 -231 to -2147483648 2147483647
231-1
Long 64 -263 to - 9223372036854775807
263-1 922337203685477580
8
Float 32 1.4e-045 1.4E-45 3.4028235E38
to
3.4e+03 Sufficient for storing 6 to
8 7 decimal digits
Char 16 0 to
65,535
Boolea 1 True or
n false
Double 8 4.9E-324 1.7976931348623157E30
8
Sufficient for storing 15
decimal digits
Operators: Operators in Java are the symbols used for performing specific
operations in Java. Operators make tasks like addition, multiplication, etc which
look easy although the implementation of these tasks is quite complex.
Operators are the building blocks of Java expressions, allowing you to perform
calculations, comparisons
1. Arithmetic Operators
They are used to perform simple arithmetic operations on primitive and non-
primitive data types.
• * : Multiplication
• / : Division
• % : Modulo
• + : Addition
• – : Subtraction
2. Unary Operators
Unary operators need only one operand. They are used to increment, decrement,
or negate a value.
• – : Unary minus, used for negating the values.
• + : Unary plus indicates the positive value (numbers are positive without
this, however). It performs an automatic conversion to int when the type of
its operand is the byte, char, or short. This is called unary numeric
promotion.
• ++ : Increment operator, used for incrementing the value by 1. There are
two varieties of increment operators.
o Post-Increment: Value is first used for computing the result and then
incremented.
o Pre-Increment: Value is incremented first, and then the result is
computed.
• – – : Decrement operator, used for decrementing the value by 1. There are
two varieties of decrement operators.
o Post-decrement: Value is first used for computing the result and then
decremented.
o Pre-Decrement: The value is decremented first, and then the result is
computed.
• ! : Logical not operator, used for inverting a boolean value.
3. Assignment Operator
‘=’ Assignment operator is used to assign a value to any variable. It has 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 other operators to
build a shorter version of the statement called a Compound Statement. For
example, instead of a = a+5, we can write a += 5.
• +=, for adding the left operand with the right operand and then assigning it
to the variable on the left.
• -=, for subtracting the right operand from the left operand and then
assigning it to the variable on the left.
• *=, for multiplying the left operand with the right operand and then
assigning it to the variable on the left.
• /=, for dividing the left operand by the right operand and then assigning it
to the variable on the left.
• %=, for assigning the modulo of the left operand by the right operand and
then assigning it to the variable on the left.
4. Relational Operators
These 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
Some of the relational operators are-
• ==, Equal to returns true if the left-hand side is equal to the right-hand side.
• !=, Not Equal to returns true if the left-hand side is not equal to the right-
hand side.
• <, less than: returns true if the left-hand side is less than the right-hand
side.
• <=, less than or equal to returns true if the left-hand side is less than or
equal to the right-hand side.
• >, Greater than: returns true if the left-hand side is greater than the right-
hand side.
• >=, Greater than or equal to returns true if the left-hand side is greater than
or equal to the right-hand side.
5. Logical Operators
These operators are used to perform “logical AND” and “logical OR” operations,
i.e., a function similar to AND gate and OR gate in digital electronics. One thing
to keep in mind is the second condition is not evaluated if the first one is false,
i.e., it has a short-circuiting effect. Used extensively to test for several conditions
for making a decision. Java also has “Logical NOT”, which returns true when the
condition is false and vice-versa
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
These operators are used to perform the manipulation of individual bits of a
number. They can be used with any of the integer types. They are used when
performing update and query operations of the Binary indexed trees.
• &, Bitwise AND operator: returns bit by bit AND of input values.
• |, Bitwise OR operator: returns bit by bit OR of input values.
• ^, Bitwise XOR operator: returns bit-by-bit XOR of input values.
• ~, Bitwise Complement Operator: This is a unary operator which returns
the one’s complement representation of the input value, i.e., with all bits
inverted.
8. Shift Operators
These operators are used to shift the bits of a number left or right, thereby
multiplying or dividing the number by two, respectively. They can be used when
we have to multiply or divide a number by two. General format-
number shift_op number_of_places_to_shift;
• <<, Left shift operator: shifts the bits of the number to the left and fills 0 on
voids left as a result. Similar effect as multiplying the number with some
power of two.
• >>, Signed Right shift operator: shifts the bits of the number to the right
and fills 0 on voids left as a result. The leftmost bit depends on the sign of
the initial number. Similar effect to dividing the number with some power
of two.
• >>>, Unsigned Right shift operator: shifts the bits of the number to the
right and fills 0 on voids left as a result. The leftmost bit is set to 0.
9. instanceof operator
The instance of the operator is used for type checking. It can be used to test if an
object is an instance of a class, a subclass, or an interface. General format-
object instance of class/subclass/interface
Operator Hierarchy
The operator precedence represents how two expressions are bind together. In an
expression, it determines the grouping of operators with operands and decides
how an expression will evaluate.
While solving an expression two things must be kept in mind the first is
a precedence and the second is associativity.
Arrays:
Java array is an object which contains elements of a similar data type.
Additionally, 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.
In Java, array is an object of a dynamically generated class. Java array inherits the
Object class, and implements the Serializable as well as Cloneable interfaces. We
can store primitive values or objects in an array in Java.
Advantages
o Code Optimization: It makes the code optimized, we can retrieve or sort
the data efficiently.
o Random access: We can get any data located at an index position.
Disadvantages
o Size Limit: We can store only the fixed size of elements in the array. It
doesn't grow its size at runtime. To solve this problem, collection
framework is used in Java which grows automatically.
Types of Array in java
There are two types of array.
• Single Dimensional Array
• Multidimensional 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;
//traversing array
for(int i=0;i<a.length;i++)//length is the property of array
{
System.out.println(a[i]);
}
}
}
}}
Few Examples on arrays
1) Java Program to copy all elements of one array into another array
2) Java Program to find the frequency of each element in the array
3) Java Program to left rotate the elements of an array
4) Java Program to print the duplicate elements of an array
5) Java Program to print the elements of an array
6) Java Program to print the elements of an array in reverse order
7) Java Program to print the elements of an array present on even position
8) Java Program to print the elements of an array present on odd position
9) Java Program to print the largest element in an array
10) Java Program to print the smallest element in an array
11) Java Program to print the number of elements present in an array
12) Java Program to print the sum of all the items of the array
13) Java Program to right rotate the elements of an array
14) Java Program to sort the elements of an array in ascending order
15) Java Program to sort the elements of an array in descending order
16) Find 3rd Largest Number in an Array
17) Find 2nd Largest Number in an Array
18) Find Largest Number in an Array
19) Find 2nd Smallest Number in an Array
20) Find Smallest Number in an Array
21) Remove Duplicate Element in an Array
22) Add Two Matrices
23) Multiply Two Matrices
24) Print Odd and Even Number from an Array
25) Transpose matrix
26) Java Program to subtract the two matrices
27) Java Program to determine whether a given matrix is an identity matrix
28) Java Program to determine whether a given matrix is a sparse matrix
29) Java Program to determine whether two matrices are equal
30) Java Program to display the lower triangular matrix
31) Java Program to display the upper triangular matrix
32) Java Program to find the frequency of odd & even numbers in the given
matrix
33) Java Program to find the product of two matrices
34) Java Program to find the sum of each row and each column of a matrix
35) Java Program to find the transpose of a given matrix
3 standard or default streams that Java has to provide which are also most
common in use:
1. System.in: This is the standard input stream that is used to read characters
from the keyboard or any other standard input device.
2. System.out: This is the standard output stream that is used to produce the
result of a program on an output device like the computer screen.
Here is a list of the various print functions that we use to output statements:
• print(): This method in Java is used to display a text on the console.
This text is passed as the parameter to this method in the form of
String. This method prints the text on the console and the cursor
remains at the end of the text at the console. The next printing takes
place from just here.
Syntax:
System.out.print(parameter);
println(): This method in Java is also used to display a text on the console. It
prints the text on the console and the cursor moves to the start of the next line at
the console. The next printing takes place from the next line.
Syntax:
System.out.println(parameter);
printf(): This is the easiest of all methods as this is similar to printf in C. Note
that System.out.print() and System.out.println() take a single argument, but
printf() may take multiple arguments. This is used to format the output in Java.
1. System.err: This is the standard error stream that is used to output all
the error data that a program might throw, on a computer screen or
any standard output device.
This stream also uses all the 3 above-mentioned functions to output the error
data:
• print()
• println()
• printf()
Types of Streams:
• Depending on the type of operations, streams can be divided into two
primary classes:
1. Input Stream: These streams are used to read data that must be
taken as an input from a source array or file or any peripheral
device. For eg., FileInputStream, BufferedInputStream,
ByteArrayInputStream etc.
PrintStream This contains the most used print() and println() method
DataOutputStream This contains method for writing java standard data types.
%b Any type " true " if non-null, " false " if null
Control Statements:
A programming language uses control statements to control the flow of execution
of a program based on certain conditions. These are used to cause the flow of
execution to advance and branch based on changes to the state of a program.
Java’s Selection statements:
• if
• if-else
• nested-if
• if-else-if
• switch-case
• jump – break, continue, return
while loop: A while loop is a control flow statement that allows code to be
executed repeatedly based on a given Boolean condition. The while loop can be
thought of as a repeating if statement.
Syntax :
while (boolean condition)
{
loop statements...
}
Example:
// Java Program to print Factorial of a number
import java.util.*;
public class Factorial
{
public static void main(String args[])
{
Scanner sc= new Scanner(System.in);
int factorial=1,i=1;
System.out.print("Enter number to find factorial- ");
int n= sc.nextInt();
while(i <= n)
{
factorial = factorial*i;
i++;
}
System.out.println("Factorial of "+n +"=" +factorial);
}
}
do while: do while loop is similar to while loop with only difference that it
checks for condition after executing the statements, and therefore is an example
of Exit Control Loop.
Syntax:
do
{
statements..
}
while (condition);
for loop: for loop provides a concise way of writing the loop structure. Unlike a
while loop, a for statement consumes the initialization, condition and
increment/decrement in one line thereby providing a shorter, easy to debug
structure of looping.
Syntax:
for (initialization condition; testing condition;increment/decrement)
{
statement(s)
}
Example: Java program to print Fibonacci number
import java.util.*;
class Fibonacci{
public static void main(String[] args) {
Nested for loop: Nested For Loop is a concept of using a for loop inside another
for loop (Similar to that of using nested if-else).
// Java Program to implement Nested for loop
import java.io.*;
class College {
public static void main(String[] args)
{
// Printing a 1 to 5 (5 times) first loop
for (int i = 1; i <= 5; i++) {
// second loop
for (int j = 1; j <= 5; j++) {
System.out.print(j + " ");
}
System.out.println();
}
}
}
Output
12345
12345
12345
12345
12345
For Each Loop: Enhanced for loop provides a simpler way to iterate through the
elements of a collection or array. It is inflexible and should be used only when
there is a need to iterate through the elements in a sequential manner without
knowing the index of the currently processed element.
Syntax:
for (T element:Collection obj/array)
{
// loop body
// statement(s)
}
jump: Java supports three jump statements: break, continue and return. These
three statements transfer control to another part of the program.
• Break: In Java, a break is majorly used for:
o Terminate a sequence in a switch statement (discussed above).
o To exit a loop.
o Used as a “civilized” form of goto.
• Continue: Sometimes it is useful to force an early iteration of a loop. That
is, you might want to continue running the loop but stop processing the
remainder of the code in its body for this particular iteration. This is, in
effect, a goto just past the body of the loop, to the loop’s end. The continue
statement performs such an action.
Return: The return statement is used to explicitly return from a method. That is,
it causes program control to transfer back to the caller of the method