UNIT - I
What is Java?
Java is a high-level, general-purpose, object-oriented, and secure programming language developed by James
Gosling at Sun Microsystems, in 1991. It is formally known as OAK. In 1995, Sun Microsystem changed the
name to Java. In 2009, Sun Microsystem takeover by Oracle Corporation.
Editions of Java
Each edition of Java has different capabilities. There are three editions of Java:
o Java Standard Editions (JSE): It is used to create programs for a desktop computer.
o Java Enterprise Edition (JEE): It is used to create large programs that run on the server and
manages heavy traffic and complex transactions.
o Java Micro Edition (JME): It is used to develop applications for small devices such as set-top boxes,
phone, and appliances.
Java Platform
Java Platform is a collection of programs. It helps to develop and run a program written in the Java
programming language. Java Platform includes an execution engine, a compiler and set of libraries. Java is a
platform-independent language.
o Simple: Java is a simple language because its syntax is simple, clean, and easy to understand.
Complex and ambiguous concepts of C++ are either eliminated or re-implemented in Java. For
example, pointer and operator overloading are not used in Java.
o Object-Oriented: In Java, everything is in the form of the object. It means it has some data and
behaviour. A program must have at least one class and object.
o Robust: Java makes an effort to check error at run time and compile time. It uses a strong memory
management system called garbage collector. Exception handling and garbage collection features
make it strong.
o Secure: Java is a secure programming language because it has no explicit pointer and programs runs
in the virtual machine. Java contains a security manager that defines the access of Java classes.
OSO
JVM
Java
OS
Application
OS
OS
o Platform-Independent: Java provides a guarantee that code writes once and run anywhere. This
byte code is platform-independent and can be run on any machine.
o Portable: Java Byte code can be carried to any platform. No implementation-dependent features.
Everything related to storage is predefined, for example, the size of primitive data types.
o High Performance: Java is an interpreted language. Java enables high performance with the use of
the Just-In-Time compiler.
o Distributed: Java also has networking facilities. It is designed for the distributed environment of the
internet because it supports TCP/IP protocol. It can run over the internet. EJB and RMI are used to
create a distributed system.
o Multi-threaded: Java also supports multi-threading. It means to handle more than one job a time.
OOPs (Object Oriented Programming System)Concepts :
Object-oriented programming is a way of solving a complex problem by breaking them into a small sub-
problem. An object is a real-world entity. It is easier to develop a program by using an object. In OOPs, we
create programs using class and object in a structured manner.
Class: A class is a template or blueprint or prototype that defines data members and member functions of an
object. We can define a class by using the class keyword.
Object: An object is a real-world entity that can be identified distinctly. An object is the instance of the class.
For example, a desk, a circle can be considered as objects. An object has a unique behaviour, identity, and
state. Data fields with their current values represent the state of an object (also known as its properties or
attributes).
Abstraction: An abstraction is a method of hiding irrelevant information from the user. For example, the driver
only knows how to drive a car; there is no need to know how does the car run. We can make a class abstract by
using the keyword abstract. In Java, we use abstract class and interface to achieve abstraction.
Encapsulation: An encapsulation is the process of binding data and functions into a single unit. A class is an
example of encapsulation. In Java, Java bean is a fully encapsulated class.
Inheritance: Inheritance is the mechanism in which one class acquire all the features of another class. We can
achieve inheritance by using the extends keyword. It facilitates the reusability of the code.
Polymorphism: The polymorphism is the ability to appear in many forms. In other words, single action in
different ways. For example, a boy in the classroom behaves like a student, in house behaves like a son. There
are two types of polymorphism: run time polymorphism and compile-time polymorphism.
Java Applications :
1) Standalone Application
Standalone applications are also known as desktop applications or window-based applications. These are
traditional software that we need to install on every machine. Examples of standalone application are Media
player, antivirus, etc. AWT and Swing are used in Java for creating standalone applications.
2) Web Application
An application that runs on the server side and creates a dynamic page is called a web application.
Currently, Servlet, JSP, Struts, Spring, Hibernate, JSF, etc. technologies are used for creating web applications in
Java.
3) Enterprise Application
An application that is distributed in nature, such as banking applications, etc. is called an enterprise application.
It has advantages like high-level security, load balancing, and clustering. In Java, EJB is used for creating
enterprise applications.
4) Mobile Application
An application which is created for mobile devices is called a mobile application. Currently, Android and Java ME
are used for creating mobile applications.
Creating Hello World Example Program
class Simple
public static void main(String args[])
System.out.println("Hello Java");
Save the above file as Simple.java.
To compile:
Javac.Simple.java
To execute:
java Simple
Output:
Hello Java
Note :
o class keyword is used to declare a class in Java.
o public keyword is an access modifier that represents visibility. It means it is visible to all.
o static is a keyword. If we declare any method as static, it is known as the static method. The core
advantage of the static method is that there is no need to create an object to invoke the static
method. The main() method is executed by the JVM, so it doesn't require creating an object to invoke
the main() method. So, it saves memory.
o void is the return type of the method. It means it doesn't return any value.
o main represents the starting point of the program.
o String[] args or String args[] is used for command line argument.
o System.out.println() is used to print statement. Here, System is a class, out is an object of the
PrintStream class, println() is a method of the PrintStream class. We will discuss the internal working
of System.out.println() statement in the coming section.
o To write the simple program, you need to open notepad by start menu -> All Programs ->
Accessories -> Notepad and write a simple program as we have shownbelow:
o As displayed in the above diagram, write the simple program of Java in notepad and saved it as
Simple.java. In order to compile and run the above program, you need to open the command prompt
by start menu -> All Programs -> Accessories -> command prompt. When we have done with
all the steps properly, it shows the following output:
What happens at runtime?
At runtime, the following steps are performed:
Classloader: It is the subsystem of JVM that is used to load class files.
Java Tokens :
Tokens are the smallest individual unit of a java program which together forms a complete program. Tokens are
the building blocks of a Java program that are meaningful to the Java compiler.
The different tokens of java are –
o Keywords
o Identifiers
o Literals
o Operators
o Separators
o Comments
Keywords: These are the pre-defined reserved words . Each keyword has a special meaning. It is always
written in lower case. Java provides the following keywords:
01. 02. boolean 03. 04. 05. class
abstrac byte break
t
06. 07. catch 08. 09. 10.
case char continu
e default
11. do 12. double 13. 14. 15. final
else extend
s
16. 17. float 18. for 19. if 20.
finally implement
s
21. 22. 23. int 24. 25. long
import instanceof interfac
e
26. 27. new 28. 29. 30.
native packag private protected
e
31. 32. return 33. 34. 35. super
public short static
36. 37. 38. this 39. thro 40. throws
switch synchronize
d
41. 42. try 43. 44. 45. while
transie void volatile
nt
46. 47. const 48. 49. 50.
assert enum goto strictfp
Identifier: Identifiers is the name given to a variable, constant, function, class, and array. It usually defined
by the user. It uses letters, underscores, or a dollar sign as the first character. The label is also known as a
special kind of identifier that is used in the goto statement. Remember that the identifier name must be
different from the reserved keywords.
There are some rules to declare identifiers are:
o The first letter of an identifier must be a letter, underscore or a dollar sign. It cannot start with digits but may contain digits.
o The whitespace cannot be included in the identifier.
o Identifiers are case sensitive.
Some valid identifiers are:
1. PhoneNumber
2. PRICE
3. radius
4. a
5. a1
6. _phonenumber
7. $circumference
8. jagged_array
9. 12radius //invalid
Literals: In programming literal is a notation that represents a fixed value (constant) in the source code. It can be categorized as an
integer literal, string literal, Boolean literal, etc. It is defined by the programmer. Once it has been defined cannot be changed. Java
provides five types of literals are as follows:
o Integer
o Floating Point
o Character
o String
o Boolean
Literal Type
23 int
9.86 double
false, true boolean
'K', '7', '-' char
"javatpoint" String
null any reference type
Operaors: Operators are the special symbol that tells the compiler to perform a special operation. Java
provides different types of operators that can be classified according to the functionality they provide. There
are eight types of operators in Java, are as follows:
o Arithmetic Operators
o Assignment Operators
o Relational Operators
o Logical Operators
o Increment or decrement Operators
o Conditional Operator
o Bitwise Operators
o Special Operators
Arithmetic Operator : Operator used to perform mathematical operations like addition, subtraction, etc.
Operator Symbols
Arithmetic +,-,/,*,%
Unary ++ , - - , !
Assignment = , += , -= , *= , /= , %= , ^=
Relational ==, != , < , >, <= , >=
Logical && , ||
Ternary (Condition) ? (Statement1) : (Statement2);
Bitwise &,|,^,~
Shift << , >> , >>>
Separators: The separators in Java is also known as punctuators. There are nine separators in Java, are as
follows:
1. separator <= ; | , | . | ( | ) | { | } | [ | ]
Note that the first three separators (; , and .) are tokens that separate other tokens, and the last
six (3 pairs of braces) separators are also known as delimiters. For example, Math.pow(9, 3);
contains nine tokens.
o Square Brackets []: It is used to define array elements. A pair of square brackets represents the
single-dimensional array, two pairs of square brackets represent the two-dimensional array.
o Parentheses (): It is used to call the functions and parsing the parameters.
o Curly Braces {}: The curly braces denote the starting and ending of a code block.
o Comma (,): It is used to separate two values, statements, and parameters.
o Assignment Operator (=): It is used to assign a variable and constant.
o Semicolon (;): It is the symbol that can be found at end of the statements. It separates the two
statements.
o Period (.): It separates the package name form the sub-packages and class. It also separates a
variable or method from a reference variable.
Comments: Comments allow us to specify information about the program inside our Java code. Java compiler
recognizes these comments as tokens but excludes it form further processing. The Java compiler treats
comments as whitespaces. Java provides the following two types of comments:
o Line Oriented: It begins with a pair of forwarding slashes (//).
o Block-Oriented: It begins with /* and continues until it founds */.
Java Control Statements
Statements that can be used to control the flow of execution of Java code are called control 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.
1. Decision Making statements
o if statements
o switch statement
2. Loop statements
o do while loop
o while loop
o for loop
3. Jump statements
o break statement
o continue statement
Decision-Making or Conditional statements:
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. nested if statement
4. else – if ladder 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.
Syntax :
if(condition)
1. {
2. statement 1;
3. }
Flowchart :
Example :Student.java
1. public class Student
2. {
3. public static void main(String[] args)
4. {
5. int x = 10;
6. int y = 12;
7. if(x+y > 20)
8. {
9. System.out.println("x + y is greater than 20");
10. }
11. }
12. }
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. {
3. statement 1;
4. }
5. Else
6. {
7. statement 2;
8. }
Flowchart :
Example :
Student.java
1. public class Student
2. {
3. public static void main(String[] args)
4. {
5. int x = 10;
6. int y = 12;
7. if(x+y < 10)
8. {
9. System.out.println("x + y is less than10");
10. } else
11. {
12. System.out.println("x + y is greater than 20");
13. }
14. }
15. }
Output: x + y is greater than 20
3) if-else-if ladder:
The if-else-if statement contains the if-statement followed by multiple else-if statements. In other words, we
can say that it is the chain of if-else statements that create a decision tree where the program may enter in the
block of code where the condition is true. We can also define an else statement at the end of the chain.
Syntax :
1. if(condition 1)
2. {
3. statement 1;
4. }
5. else if(condition 2)
6. {
7. statement 2;
8. }
9. Else
10. {
11. statement 2;
12. }
Consider the following example.
Student.java
1. public class Student {
2. public static void main(String[] args) {
3. String city = "Delhi";
4. if(city == "Meerut") {
5. System.out.println("city is meerut");
6. }else if (city == "Noida") {
7. System.out.println("city is noida");
8. }else if(city == "Agra") {
9. System.out.println("city is agra");
10. }else {
11. System.out.println(city);
12. }
13. }
14. }
Output:
Delhi
4. 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) {
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.
Points to be noted about switch statement:
o The case variables can be int, short, byte, char, or enumeration. String type is also supported since
version 7 of Java
o Cases cannot be duplicate
o Default statement is executed when any of the case doesn't match the value of expression. It is
optional.
o Break statement terminates the switch block when the condition is satisfied.
It is optional, if not used, next case is executed.
o 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 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:
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.
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. }
The flow chart for the for-loop is given below.
Consider the following example to understand the proper functioning of the for loop in java.
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
Java 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
Java 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 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. }
The flow chart for the while loop is given in the following image.
Consider the following example.
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
Java 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.
Consider the following example to understand the functioning of the do-while loop in Java.
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
Jump Statements
Jump statements are used to transfer the control of the program to the specific statements. In other words,
jump statements transfer the execution control to the other part of the program. There are two types of jump
statements in Java, i.e., break and continue.
Java break statement
As the name suggests, the break statement is used to break the current flow of the program and transfer the
control to the next statement outside a loop or switch statement. However, it breaks only the inner loop in the
case of the nested loop.
The break statement cannot be used independently in the Java program, i.e., it can only be written inside the
loop or switch statement.
The break statement example with for loop
Consider the following example in which we have used the break statement with the for loop.
BreakExample.java
1. public class BreakExample {
2.
3. public static void main(String[] args) {
4. // TODO Auto-generated method stub
5. for(int i = 0; i<= 10; i++) {
6. System.out.println(i);
7. if(i==6) {
8. break;
9. }
10. }
11. }
12. }
Output:
0
1
2
3
4
5
6
break statement example with labeled for loop
Calculation.java
1. public class Calculation {
2.
3. public static void main(String[] args) {
4. // TODO Auto-generated method stub
5. a:
6. for(int i = 0; i<= 10; i++) {
7. b:
8. for(int j = 0; j<=15;j++) {
9. c:
10. for (int k = 0; k<=20; k++) {
11. System.out.println(k);
12. if(k==5) {
13. break a;
14. }
15. }
16. }
17.
18. }
19. }
20.
21.
22. }
Output:
0
1
2
3
4
5
Java continue statement
Unlike break statement, the continue statement doesn't break the loop, whereas, it skips the specific part of
the loop and jumps to the next iteration of the loop immediately.
Consider the following example to understand the functioning of the continue statement in Java.
1. public class ContinueExample {
2.
3. public static void main(String[] args) {
4. // TODO Auto-generated method stub
5.
6. for(int i = 0; i<= 2; i++) {
7.
8. for (int j = i; j<=5; j++) {
9.
10. if(j == 4) {
11. continue;
12. }
13. System.out.println(j);
14. }
15. }
16. }
17.
18. }
Output:
0
1
2
3
5
1
2
3
5
2
3
5