0% found this document useful (0 votes)
13 views25 pages

Java Unit-I

The document provides an overview of Java including its history, applications, and comparisons to C++. Java was created in 1995 as a platform-independent language and has since become widely used in various applications including desktop, web, and mobile. The document also outlines some key differences between Java and C++.
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)
13 views25 pages

Java Unit-I

The document provides an overview of Java including its history, applications, and comparisons to C++. Java was created in 1995 as a platform-independent language and has since become widely used in various applications including desktop, web, and mobile. The document also outlines some key differences between Java and C++.
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/ 25

By: ANKIT KUMAR BALIYAN

DEPARTMENT OF COMPUTER APPLICATION

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.

Platform: Any hardware or software environment in which a program runs, is known as


a platform. Since Java has a runtime environment (JRE) and API, it is called a platform.

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:

1. Desktop Applications such as acrobat reader, media player, antivirus, etc.


2. Web Applications such as irctc.co.in, javatpoint.com, etc.
3. Enterprise Applications such as banking applications.
4. Mobile
By: ANKIT KUMAR BALIYAN
DEPARTMENT OF COMPUTER APPLICATION

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.

Why Java was named as "Oak"?

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

Comparison C++ Java


Index

Platform- C++ is platform-dependent. Java is platform-independent.


independent

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.

Goto C++ supports Java doesn't support the goto


the goto statement. statement.

Multiple C++ supports multiple Java doesn't support multiple


inheritance inheritance. inheritance through class. It can
be achieved by using interfaces in
java.

Operator C++ supports operator Java doesn't support operator


Overloading overloading. overloading.

Pointers C++ supports pointers. You Java supports pointer internally.


can write a pointer program However, you can't write the
pointer program in java. It means
By: ANKIT KUMAR BALIYAN
DEPARTMENT OF COMPUTER APPLICATION

in C++. java has restricted pointer support


in java.

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

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.

Java Primitive Data Types


In Java language, primitive data types are the building blocks of data manipulation.
These are the most basic data types available in Java language.

There are 8 types of primitive data types:

o boolean data type


o byte data type
o char data type
o short data type
o int data type
o long data type
o float data type
o double data type

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.

Java provides three types of control flow statements.


By: ANKIT KUMAR BALIYAN
DEPARTMENT OF COMPUTER APPLICATION

1. Decision Making statements


o if statements
o switch statement
2. Loop statements
o do while loop
o while loop
o for loop
o for-each loop
3. Jump statements
o break statement
o continue statement

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

Let's understand the if-statements one by one.

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

Syntax of if statement is given below.

1. if(condition) {
2. statement 1; //executes when condition is true
3. }

Student.java

1. public class Student {


2. public static void main(String[] args) {
3. int x = 10;
4. int y = 12;
5. if(x+y > 20) {
6. System.out.println("x + y is greater than 20");
7. }
8. }
9. }

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. }

Consider the following example.

Student.java
By: ANKIT KUMAR BALIYAN
DEPARTMENT OF COMPUTER APPLICATION

1. public class Student {


2. public static void main(String[] args) {
3. int x = 10;
4. int y = 12;
5. if(x+y < 10) {
6. System.out.println("x + y is less than 10");
7. } else {
8. System.out.println("x + y is greater than 20");
9. }
10. }
11. }

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.

Syntax of Nested if-statement is given below.

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. }

Consider the following example.

Student.java

1. public class Student {


2. public static void main(String[] args) {
By: ANKIT KUMAR BALIYAN
DEPARTMENT OF COMPUTER APPLICATION

3. String address = "Delhi, India";


4.
5. if(address.endsWith("India")) {
6. if(address.contains("Meerut")) {
7. System.out.println("Your city is Meerut");
8. }else if(address.contains("Noida")) {
9. System.out.println("Your city is Noida");
10. }else {
11. System.out.println(address.split(",")[0]);
12. }
13. }else {
14. System.out.println("You are not living in India");
15. }
16. }
17. }

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.

The syntax to use the switch statement is given below.

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

12. default statement;


13. }

Consider the following example to understand the flow of the switch statement.

Student.java

1. public class Student implements Cloneable {


2. public static void main(String[] args) {
3. int num = 2;
4. switch (num){
5. case 0:
6. System.out.println("number is 0");
7. break;
8. case 1:
9. System.out.println("number is 1");
10. break;
11. default:
12. System.out.println(num);
13. }
14. }
15. }

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

Let's understand the loop statements one by one.

Java for loop


In Java, for loop is similar to C and C++. It enables us to initialize the loop variable,
check the condition, and increment/decrement in a single line of code. We use the for
loop only when we exactly know the number of times, we want to execute the block of
code.

1. for(initialization, condition, increment/decrement) {


2. //block of statements
3. }

Calculation.java

1. public class Calculattion {


2. public static void main(String[] args) {
3. // TODO Auto-generated method stub
4. int sum = 0;
5. for(int j = 1; j<=10; j++) {
6. sum = sum + j;
7. }
8. System.out.println("The sum of first 10 natural numbers is " + sum);
9. }
10. }

Output:

The sum of first 10 natural numbers is 55


By: ANKIT KUMAR BALIYAN
DEPARTMENT OF COMPUTER APPLICATION

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.

1. for(data_type var : array_name/collection_name){


2. //statements
3. }

Consider the following example to understand the functioning of the for-each loop in
Java.

Calculation.java

1. public class Calculation {


2. public static void main(String[] args) {
3. // TODO Auto-generated method stub
4. String[] names = {"Java","C","C++","Python","JavaScript"};
5. System.out.println("Printing the content of the array names:\n");
6. for(String name:names) {
7. System.out.println(name);
8. }
9. }
10. }

Output:

Printing the content of the array names:

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.

The syntax of the while loop is given below.

1. while(condition){
2. //looping statements
3. }

Calculation .java

1. public class Calculation {


2. public static void main(String[] args) {
3. // TODO Auto-generated method stub
4. int i = 0;
5. System.out.println("Printing the list of first 10 even numbers \n");
6. while(i<=10) {
7. System.out.println(i);
8. i = i + 2;
9. }
10. }
11. }

Output:

Printing the list of first 10 even numbers

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

1. public class Calculation {


2. public static void main(String[] args) {
3. // TODO Auto-generated method stub
4. int i = 0;
5. System.out.println("Printing the list of first 10 even numbers \n");
6. do {
7. System.out.println(i);
8. i = i + 2;
9. }while(i<=10);
10. }
11. }

Output:

Printing the list of first 10 even numbers


0
2
4
6
8
10
By: ANKIT KUMAR BALIYAN
DEPARTMENT OF COMPUTER APPLICATION

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.

Types of Array in java


There are two types of array.

o Single Dimensional Array


o Multidimensional Array
By: ANKIT KUMAR BALIYAN
DEPARTMENT OF COMPUTER APPLICATION

Single Dimensional Array in Java


Syntax to Declare an Array in Java

1. dataType[] arr; (or)


2. dataType []arr; (or)
3. dataType arr[];

Instantiation of an Array in Java

1. arrayRefVar=new datatype[size];

Example of Java Array


Let's see the simple example of java array, where we are going to declare, instantiate,
initialize and traverse an array.

1. //Java Program to illustrate how to declare, instantiate, initialize


2. //and traverse the Java array.
3. class Testarray{
4. public static void main(String args[]){
5. int a[]=new int[5];//declaration and instantiation
6. a[0]=10;//initialization
7. a[1]=20;
8. a[2]=70;
9. a[3]=40;
10. a[4]=50;
11. //traversing array
12. for(int i=0;i<a.length;i++)//length is the property of array
13. System.out.println(a[i]);
14. }}

Output:

10
20
70
40
By: ANKIT KUMAR BALIYAN
DEPARTMENT OF COMPUTER APPLICATION
50

For-each Loop for Java Array


We can also print the Java array using for-each loop. The Java for-each loop prints the
array elements one by one. It holds an array element in a variable, then executes the
body of the loop.

The syntax of the for-each loop is given below:

1. for(data_type variable:array){
2. //body of the loop
3. }

1. //Java Program to print the array elements using for-each loop


2. class Testarray1{
3. public static void main(String args[]){
4. int arr[]={33,3,4,5};
5. //printing array using for-each loop
6. for(int i:arr)
7. System.out.println(i);
8. }}

Output:

33
3
4
5

Multidimensional Array in Java


In such case, data is stored in row and column based index (also known as matrix form).

Syntax to Declare Multidimensional Array in Java


By: ANKIT KUMAR BALIYAN
DEPARTMENT OF COMPUTER APPLICATION

1. dataType[][] arrayRefVar; (or)


2. dataType [][]arrayRefVar; (or)
3. dataType arrayRefVar[][]; (or)
4. dataType []arrayRefVar[];

Example to instantiate Multidimensional Array in Java

1. int[][] arr=new int[3][3];//3 row and 3 column

Example to initialize Multidimensional Array in Java

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;

Example of Multidimensional Java Array


Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional
array.

1. //Java Program to illustrate the use of multidimensional array


2. class Testarray3{
3. public static void main(String args[]){
4. //declaring and initializing 2D array
5. int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
6. //printing 2D array
7. for(int i=0;i<3;i++){
8. for(int j=0;j<3;j++){
9. System.out.print(arr[i][j]+" ");
10. }
By: ANKIT KUMAR BALIYAN
DEPARTMENT OF COMPUTER APPLICATION

11. System.out.println();
12. }
13. }}

Output:

1 2 3
2 4 5
4 4 5

Let's see a simple example that adds two matrices.

1. //Java Program to demonstrate the addition of two matrices in Java


2. class Testarray5{
3. public static void main(String args[]){
4. //creating two matrices
5. int a[][]={{1,3,4},{3,4,5}};
6. int b[][]={{1,3,4},{3,4,5}};
7.
8. //creating another matrix to store the sum of two matrices
9. int c[][]=new int[2][3];
10.
11. //adding and printing addition of 2 matrices
12. for(int i=0;i<2;i++){
13. for(int j=0;j<3;j++){
14. c[i][j]=a[i][j]+b[i][j];
15. System.out.print(c[i][j]+" ");
16. }
17. System.out.println();//new line
18. }
19.
20. }}

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.

1. //Java Program to multiply two matrices


2. public class MatrixMultiplicationExample{
3. public static void main(String args[]){
4. //creating two matrices
5. int a[][]={{1,1,1},{2,2,2},{3,3,3}};
6. int b[][]={{1,1,1},{2,2,2},{3,3,3}};
7.
8. //creating another matrix to store the multiplication of two matrices
9. int c[][]=new int[3][3]; //3 rows and 3 columns
10.
11. //multiplying and printing multiplication of 2 matrices
12. for(int i=0;i<3;i++){
13. for(int j=0;j<3;j++){
14. c[i][j]=0;
15. for(int k=0;k<3;k++)
16. {
17. c[i][j]+=a[i][k]*b[k][j];
18. }//end of k loop
19. System.out.print(c[i][j]+" "); //printing matrix element
20. }//end of j loop
21. System.out.println();//new line
22. }
23. }}

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.

The java.lang.String class implements Serializable, Comparable and CharSequence interfaces.

How to create a string object?


There are two ways to create String object:

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

In such case, JVM

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).

Java String Example


StringExample.java

public class StringExample{

1. public static void main(String args[]){


2. String s1="java";//creating string by Java string literal
3. char ch[]={'s','t','r','i','n','g','s'};
4. String s2=new String(ch);//converting char array to string
5. String s3=new String("example");//creating Java string by new keyword
6. System.out.println(s1);
7. System.out.println(s2);
8. System.out.println(s3);
9. }}

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

1. public class CharAtExample{


2. public static void main(String args[]){
3. String name="javatpoint";
4. char ch=name.charAt(4);//returns the char value at the 4th index
5. System.out.println(ch);
6. }}

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

The signature of the string length() method is given below:

1. public int length()


By: ANKIT KUMAR BALIYAN
DEPARTMENT OF COMPUTER APPLICATION

1. public class LengthExample{


2. public static void main(String args[]){
3. String s1="javaprograming";
4. String s2="python";
5. System.out.println("string length is: "+s1.length());//10 is the length of javatpoint string
6. System.out.println("string length is: "+s2.length());//6 is the length of python string
7. }}

Output:

string length is: 10


string length is: 6

You might also like