Java Unit-I
Java Unit-I
Java Programminig
UNIT-I
(Java Programming)
Java-Introduction
Java is a programming language and a platform. Java is a high level, robust, object-
oriented and secure programming language.
Java was developed by Sun Microsystems (which is now the subsidiary of Oracle) in the
year 1995. James Gosling is known as the father of Java. Before Java, its name was Oak.
Since Oak was already a registered company, so James Gosling and his team changed
the name from Oak to Java.
Simple.java
1. class Simple{
2. public static void main(String args[]){
3. System.out.println("Hello Java");
4. }
5. }
Application
According to Sun, 3 billion devices run Java. There are many devices where Java is
currently used. Some of them are as follows:
5. Embedded System
6. Smart Card
7. Robotics
8. Games, etc.
History of Java
The history of Java is very interesting. Java was originally designed for interactive television, but
it was too advanced technology for the digital cable television industry at the time. The history
of Java starts with the Green Team. Java team members (also known as Green Team), initiated
this project to develop a language for digital devices such as set-top boxes, televisions, etc.
However, it was best suited for internet programming. Later, Java technology was incorporated
by Netscape.
The principles for creating Java programming were "Simple, Robust, Portable, Platform-
independent, Secured, High Performance, Multithreaded, Architecture Neutral, Object-
Oriented, Interpreted, and Dynamic". Java was developed by James Gosling, who is known as
the father of Java, in 1995. James Gosling and his team members started the project in the early
'90s.
Currently, Java is used in internet programming, mobile devices, games, e-business solutions,
etc. Following are given significant points that describe the history of Java.
1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language
project in June 1991. The small team of sun engineers called Green Team.
2) Initially it was designed for small, embedded systems in electronic appliances like
set-top boxes.
By: ANKIT KUMAR BALIYAN
DEPARTMENT OF COMPUTER APPLICATION
3) Firstly, it was called "Greentalk" by James Gosling, and the file extension was .gt.
4) After that, it was called Oak and was developed as a part of the Green project.
5) Why Oak? Oak is a symbol of strength and chosen as a national tree of many
countries like the U.S.A., France, Germany, Romania, etc.
6) In 1995, Oak was renamed as "Java" because it was already a trademark by Oak
Technologies.
7) Why had they chose the name Java for Java language? The team gathered to choose
a new name. The suggested words were "dynamic", "revolutionary", "Silk", "jolt", "DNA",
etc. They wanted something that reflected the essence of the technology: revolutionary,
dynamic, lively, cool, unique, and easy to spell, and fun to say.
According to James Gosling, "Java was one of the top choices along
with Silk". Sinc C++ vs Java
There are many differences and similarities between the C++ programming language
and Java. A list of top differences between C++ and Java are given below:
By: ANKIT KUMAR BALIYAN
DEPARTMENT OF COMPUTER APPLICATION
Mainly used for C++ is mainly used for Java is mainly used for application
system programming. programming. It is widely used in
Windows-based, web-based,
enterprise, and mobile
applications.
Design Goal C++ was designed for Java was designed and created as
systems and applications an interpreter for printing systems
programming. It was an but later extended as a support
extension of the C network computing. It was
programming language. designed to be easy to use and
accessible to a broader audience.
Compiler and C++ uses compiler only. C++ Java uses both compiler and
Interpreter is compiled and run using interpreter. Java source code is
the compiler which converts converted into bytecode at
source code into machine compilation time. The interpreter
code so, C++ is platform executes this bytecode at runtime
dependent. and produces output. Java is
interpreted that is why it is
platform-independent.
Dat
a Call by Value C++ supports both call by Java supports call by value only.
and Call by value and call by reference. There is no call by reference in
Typ reference java.
es
Structure and C++ supports structures and Java doesn't support structures
Union unions. and unions.
Data
types
Thread Support C++ doesn't have built-in Java has built-in thread support.
specif
support for threads. It relies
y the
on third-party libraries for
differ
thread support.
ent
sizes
and Documentation C++ doesn't support Java supports documentation
values comment documentation comments. comment (/** ... */) to create
that documentation for java source
can code.
be
store
d in Virtual Keyword C++ supports virtual Java has no virtual keyword. We
the keyword so that we can can override all non-static
variab decide whether or not to methods by default. In other
le. override a function. words, non-static methods are
There virtual by default.
are
two
By: ANKIT KUMAR BALIYAN
DEPARTMENT OF COMPUTER APPLICATION
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.
Control Statements
Java compiler executes the code from top to bottom. The statements in the code are
executed according to the order in which they appear. However, Java provides
statements that can be used to control the flow of Java code. Such statements are called
control flow statements. It is one of the fundamental features of Java, which provides a
smooth flow of program.
Decision-Making statements:
As the name suggests, 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., If statement and switch statement.
1) If Statement:
In Java, the "if" statement is used to evaluate a condition. The control of the program is
diverted depending upon the specific condition. 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
1) Simple if statement:
It is the most basic statement among all control flow statements in Java. It evaluates a Boolean expression
and enables the program to enter a block of code if the expression evaluates to true.
By: ANKIT KUMAR BALIYAN
DEPARTMENT OF COMPUTER APPLICATION
1. if(condition) {
2. statement 1; //executes when condition is true
3. }
Student.java
Output:
x + y is greater than 20
2) 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:
1. if(condition) {
2. statement 1; //executes when condition is true
3. }
4. else{
5. statement 2; //executes when condition is false
6. }
Student.java
By: ANKIT KUMAR BALIYAN
DEPARTMENT OF COMPUTER APPLICATION
Output:
x + y is greater than 20
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.
1. if(condition 1) {
2. statement 1; //executes when condition 1 is true
3. if(condition 2) {
4. statement 2; //executes when condition 2 is true
5. }
6. else{
7. statement 2; //executes when condition 2 is false
8. }
9. }
Student.java
Output:
Delhi
Switch Statement:
In Java, Switch statements are similar to if-else-if statements. 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.
1. switch (expression){
2. case value1:
3. statement1;
4. break;
5. .
6. .
7. .
8. case valueN:
9. statementN;
10. break;
11. default:
By: ANKIT KUMAR BALIYAN
DEPARTMENT OF COMPUTER APPLICATION
Consider the following example to understand the flow of the switch statement.
Student.java
Output:
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. The switch permits
only int, string, and Enum type variables to be used.
Loop Statements
In programming, sometimes we need to execute the block of code repeatedly while
some condition evaluates to true. However, 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.
By: ANKIT KUMAR BALIYAN
DEPARTMENT OF COMPUTER APPLICATION
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
Calculation.java
Output:
for-each loop
Java provides an enhanced for loop to traverse the data structures like array or
collection. In the for-each loop, we don't need to update the loop variable. The syntax to
use the for-each loop in java is given below.
Consider the following example to understand the functioning of the for-each loop in
Java.
Calculation.java
Output:
Java
C
C++
Python
JavaScript
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
By: ANKIT KUMAR BALIYAN
DEPARTMENT OF COMPUTER APPLICATION
use a while loop. Unlike for loop, the initialization and increment/decrement doesn't
take place inside the loop statement in 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.
1. while(condition){
2. //looping statements
3. }
Calculation .java
Output:
0
2
4
6
8
10
By: ANKIT KUMAR BALIYAN
DEPARTMENT OF COMPUTER APPLICATION
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.
1. do
2. {
3. //statements
4. } while (condition);
The flow chart of the do-while loop is given in the following image.
Calculation.java
Output:
Arrays
Normally, an array is a collection of similar type of elements which has contiguous memory location.
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.
Moreover, Java provides the feature of anonymous arrays which is not available in
C/C++.
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.
1. arrayRefVar=new datatype[size];
Output:
10
20
70
40
By: ANKIT KUMAR BALIYAN
DEPARTMENT OF COMPUTER APPLICATION
50
1. for(data_type variable:array){
2. //body of the loop
3. }
Output:
33
3
4
5
1. arr[0][0]=1;
2. arr[0][1]=2;
3. arr[0][2]=3;
4. arr[1][0]=4;
5. arr[1][1]=5;
6. arr[1][2]=6;
7. arr[2][0]=7;
8. arr[2][1]=8;
9. arr[2][2]=9;
11. System.out.println();
12. }
13. }}
Output:
1 2 3
2 4 5
4 4 5
Output:
21. 2 6 8
22. 6 8 10
By: ANKIT KUMAR BALIYAN
DEPARTMENT OF COMPUTER APPLICATION
Let's see a simple example to multiply two matrices of 3 rows and 3 columns.
Output:
24. 6 6 6
25. 12 12 12
26. 18 18 18
String
In Java, string is basically an object that represents sequence of char values. An array of
characters works same as Java string. For example:
By: ANKIT KUMAR BALIYAN
DEPARTMENT OF COMPUTER APPLICATION
1. char[] ch={'j','a','v','a','t','p','o','i','n','t'};
2. String s=new String(ch);
is same as:
1. 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.
1. By string literal
2. By new keyword
1) String Literal
Java String literal is created by using double quotes. For Example:
1. String s="welcome";
Each time you create a string literal, the JVM checks the "string constant pool" first. If
the string already exists in the pool, a reference to the pooled instance is returned. If the
string doesn't exist in the pool, a new string instance is created and placed in the pool.
For example:
By: ANKIT KUMAR BALIYAN
DEPARTMENT OF COMPUTER APPLICATION
1. String s1="Welcome";
2. String s2="Welcome";//It doesn't create a new instance
2) By new keyword
1. String s=new String("Welcome");//creates two objects and one reference variable
will create a new string object in normal (non-pool) heap memory, and the literal "Welcome" will be
placed in the string constant pool. The variable s will refer to the object in a heap (non-pool).
Output:
java
strings
example
String Methods
By: ANKIT KUMAR BALIYAN
DEPARTMENT OF COMPUTER APPLICATION
charAt()
The Java String class charAt() method returns a char value at the given index number.
The index number starts from 0 and goes to n-1, where n is the length of the string. It
returns StringIndexOutOfBoundsException, if the given index number is greater than
or equal to this string length or a negative number.
Syntax
1. public char charAt(int index)
FileName: CharAtExample.java
Output:
7. t
length()
The Java String class length() method finds the length of a string. The length of the Java string is the
same as the Unicode code units of the string.
Signature
Output: