Java Unit 1
Java Unit 1
object-oriented programming
Object-oriented programming and procedural programming both are used to develop the
applications. Both of them are high-level programming languages.
Procedural Programming
It is defined as a programming language derived from the structure programming and based
on calling procedures. The procedures are the functions, routines, or subroutines that consist
of the computational steps required to be carried. It follows a step-by-step approach in order
to break down a task into a set of variables and routines via a sequence of instructions.
During the program's execution, a procedure can be called at any point, either by other
procedures or by itself. The examples of procedural programming are ALGOL, COBOL,
BASIC, PASCAL, FORTRAN, and C.
Object-oriented programming
1
routines via a sequence of
instructions.
2. Security It is less secure than Data hiding is possible in object-
OOPs. oriented programming due to
abstraction. So, it is more secure
than procedural programming.
3. Approach It follows a top-down It follows a bottom-up approach.
approach.
4. Data In procedural In OOP, objects can move and
movement programming, data moves communicate with each other via
freely within the system member functions.
from one function to
another.
5. Orientation It is structure/procedure- It is object-oriented.
oriented.
6. Access There are no access The access modifiers in OOP are
modifiers modifiers in procedural named as private, public, and
programming. protected.
7. Inheritance Procedural programming There is a feature of inheritance in
does not have the concept object-oriented programming.
of inheritance.
8. Code There is no code It offers code reusability by using
reusability reusability present in the feature of inheritance.
procedural programming.
9. Overloading Overloading is not In OOP, there is a concept of
possible in procedural function overloading and operator
programming. overloading.
10. Data hiding There is not any proper There is a possibility of data
way for data hiding. hiding.
A list of the most important features of the Java language is given below.
Simple
Java is very easy to learn, and its syntax is simple, clean and easy to understand. According to
Sun Microsystem, Java language is a simple programming language because:
2
o Java syntax is based on C++ (so easier for programmers to learn it after C++).
o Java has removed many complicated and rarely-used features, for example, explicit
pointers, operator overloading, etc.
o There is no need to remove unreferenced objects because there is an Automatic
Garbage Collection in Java.
Object-oriented
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
Platform Independent
Java is platform independent because it is different from other languages like C, C++, etc.
which are compiled into platform specific machines while Java is a write once, run anywhere
language. A platform is the hardware or software environment in which a program runs.
There are two types of platforms software-based and hardware-based. Java provides a
software-based platform.
The Java platform differs from most other platforms in the sense that it is a software-based
platform that runs on top of other hardware-based platforms. It has two components:
1. Runtime Environment
2. API(Application Programming Interface)
3
Secured
Java is best known for its security. With Java, we can develop virus-free systems. Java is
secured because:
o No explicit pointer
o Java Programs run inside a virtual machine sandbox
o Classloader: Classloader in Java is a part of the Java Runtime Environment (JRE)
which is used to load Java classes into the Java Virtual Machine dynamically. It adds
security by separating the package for the classes of the local file system from those
that are imported from network sources.
o Bytecode Verifier: It checks the code fragments for illegal code that can violate
access rights to objects.
o Security Manager: It determines what resources a class can access such as reading
and writing to the local disk.
Java language provides these securities by default. Some security can also be provided by an
application developer explicitly through SSL, JAAS, Cryptography, etc.
Robust
Architecture-neutral
Java is architecture neutral because there are no implementation dependent features, for
example, the size of primitive types is fixed.
In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4
bytes of memory for 64-bit architecture. However, it occupies 4 bytes of memory for both 32
and 64-bit architectures in Java.
4
Portable
Java is portable because it facilitates you to carry the Java bytecode to any platform. It doesn't
require any implementation.
High-performance
Java is faster than other traditional interpreted programming languages because Java
bytecode is "close" to native code. It is still a little bit slower than a compiled language (e.g.,
C++). Java is an interpreted language that is why it is slower than compiled languages, e.g.,
C, C++, etc.
Distributed
Java is distributed because it facilitates users to create distributed applications in Java. RMI
and EJB are used for creating distributed applications. This feature of Java makes us able to
access files by calling the methods from any machine on the internet.
Multi-threaded
A thread is like a separate program, executing concurrently. We can write Java programs that
deal with many tasks at once by defining multiple threads. The main advantage of multi-
threading is that it doesn't occupy memory for each thread. It shares a common memory area.
Threads are important for multi-media, Web applications, etc.
Dynamic
Java is a dynamic language. It supports the dynamic loading of classes. It means classes are
loaded on demand. It also supports functions from its native languages
Java supports dynamic compilation and automatic memory management (garbage collection).
5
Java Environment
JVM
JVM (Java Virtual Machine) is an abstract machine. It is called a virtual machine because it
doesn't physically exist. It is a specification that provides a runtime environment in which
Java bytecode can be executed. It can also run those programs which are written in other
languages and compiled to Java bytecode.
JVMs are available for many hardware and software platforms. JVM, JRE, and JDK are
platform dependent because the configuration of each OS is different from each other.
However, Java is platform independent. There are three notions of the
JVM: specification, implementation, and instance.
o Loads code
o Verifies code
o Executes code
o Provides runtime environment
JRE
JRE is an acronym for Java Runtime Environment. It is also written as Java RTE. The Java
Runtime Environment is a set of software tools which are used for developing Java
applications. It is used to provide the runtime environment. It is the implementation of JVM.
It physically exists. It contains a set of libraries + other files that JVM uses at runtime.
The implementation of JVM is also actively released by other companies besides Sun Micro
Systems.
6
JDK
JDK is an acronym for Java Development Kit. The Java Development Kit (JDK) is a software
development environment which is used to develop Java applications and applets. It
physically exists. It contains JRE + development tools.
JDK is an implementation of any one of the below given Java Platforms released by Oracle
Corporation:
The JDK contains a private Java Virtual Machine (JVM) and a few other resources such as an
interpreter/loader (java), a compiler (javac), an archiver (jar), a documentation generator
(Javadoc), etc. to complete the development of a Java Application.
7
JAVA SOURCE FILE
class Example
System.out.println(“hello”);
Main line:
main()-Starting point for the interpreter to start the execution of the program.
static: main must be declared as static; because the main interpreter uses this function
8
void-main :function does not return any value(but simply prints a few text to the screen).
String args[] declares a argument named args, which hold Array of objects of the type
string.
Output Line: println-function is a member of the out object,which is a static data field of
system class.
Println all the time appends a newline character to the close of the string.
This means that any following output will start on a new line.
1.3.3.JAVA COMPILATION
To write the program text we need to write a file containing code. For a Java program, The
ClassName.java
where ClassNameis the name of the class defined in the program. E.g.,Example.java
The program can be written by any program that allows one text file (editor). E.g., NotePad,
Emacs, ...
The compilation of the program is essential to convert the program into a sequence of
commands that can be openly executed by the computer. The standard Java compiler,
which is part of the Java Standard Development Kit (Java SDK), is javac. To make use of it,
javac ClassName.java
The compilation yields a file called ClassName.class, which contains the command that can
9
be straight executed by the system. For example:
javac Example.java
After compilation step, we have to execute the java program.In Java the execution of a
java ClassName
Public keyword is an access specifier. Static allows main() to be called without having
to instantiate a particular instance of class. Void does not return any value. Main() is
the method where java application begins.String args[] receives any command line
arguments during runtime.System is a predefined class that provides access to the
system. Out is output stream connected to console.println displays the output
Static Member
In Java, static members are those which belongs to the class and you can access these
members without instantiating the class.
The static keyword can be used with methods, fields, classes (inner/nested), blocks.
Static Methods
You can create a static method by using the keyword static. Static methods can access only
static fields, methods. To access static methods there is no need to instantiate the class, you
can do it just using the class name as
Static Blocks
10
These are a block of codes with a static keyword. In general, these are used to initialize the
static members. JVM executes static blocks before the main method at the time of class
loading.
final in Java
In the program, there can be variables of various types. If there is a variable as int x=1; later
in the program, that variable value can be changed to some other value. A variable that is
declared as final and initialized with a value cannot be changed later in the program.
Example:1
11
Example:2
Variables
A variable is a container which holds the value while the Java program is executed. A
variable is assigned with a data type.
Variable is a name of memory location. There are three types of variables in java: local,
instance and static.
Variable
A variable is the name of a reserved area allocated in memory. In other words, it is a name of
the memory location. It is a combination of "vary + able" which means its value can be
changed.
12
Types of Variables
o local variable
o instance variable
o static variable
13
1) Local Variable
A variable declared inside the body of the method is called local variable. You can use this
variable only within that method and the other methods in the class aren't even aware that the
variable exists.
2) 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.
3) 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.
14
Example:
Another Example:
Java Comments
15
The Java comments are the statements in a program that are not executed by the compiler and
interpreter.
16
1) Java Single Line Comment
The single-line comment is used to comment only one line of the code. It is the widely used
and easiest way of commenting the statements.
Single line comments starts with two forward slashes (//). Any text in front of // is not
executed by Java.
The multi-line comment is used to comment multiple lines of code. It can be used to explain a
complex code snippet or to comment multiple lines of code at a time (as it will be difficult to
use single-line comments there).
Multi-line comments are placed between /* and */. Any text between /* and */ is not
executed by Java.
17
Let's use multi-line comment in a Java program.
Documentation comments are usually used to write large programs for a project or software
application as it helps to create documentation API. These APIs are needed for reference, i.e.,
which classes, methods, arguments, etc., are used in the code.
To create documentation API, we need to use the javadoc tool. The documentation
comments are placed between /** and */.
18
Data Types
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.
allows us to store multiple values of similar type. This is a data type whose variable can
Example:
int a; // valid
a=10; // valid
19
o int data type
o long data type
o float data type
o double data type
constructors of the classes. They are used to contact objects. These variables are declared
to be of a particular type that cannot be changed. Class objects and various types of array
variables come below reference data type. Default value of any reference variable is null. A
reference variable can be used to refer any other object of the declared type or any
compatible type.
Objects and Arrays are the reference or non-primitive data types in Java. They are
so called since they are handled “by reference” i.e. variables of their kind store the address
For Ex:
char [] arr = { 'a', 'b', 'c', 'd' }; //'arr' stores the references for the 4 values
20
Boolean Data Type
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:
The byte data type is an example of primitive data type. It isan 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.
Example:
21
Short 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.
Example:
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,648and 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.
Example:
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
22
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.
Example:
float f1 = 234.5f
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 = 12.3
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.
Example:
byte b =100;
short s =123;
int v = 123543;
23
double sineVal = 12345.234d;
booleanval = false;
Output:
Operators
24
It is a symbol that is used to perform operations. For example: +, -, *, / etc.
There are many types of operators in Java which are given below:
• Unary Operator,
• Arithmetic Operator,
• Shift Operator,
• Relational Operator,
• Bitwise Operator,
• Logical Operator,
• Assignment Operator.
The Java unary operators require only one operand. Unary operators are used to perform
various operations i.e.:
25
Java Unary Operator Example: ++ and --
Java arithmetic operators are used to perform addition, subtraction, multiplication, and
division. They act as basic mathematical operations.
26
Java Arithmetic Operator Example
The Java left shift operator << is used to shift all of the bits in a value to the left side of a
specified number of times.
27
Java Left Shift Operator Example
The Java right shift operator >> is used to move the value of the left operand to right by the
number of bits specified by the right operand.
28
1. == is the equality operator. This returns true if both the operands are referring to the same
object, otherwise false.
2. != is for non-equality operator. It returns true if both the operands are referring to the
different objects, otherwise false.
3. < is less than operator.
4. > is greater than operator.
5. <= is less than or equal to operator.
6. >= is greater than or equal to operator.
Example:
Output:
29
Java AND Operator Example: Logical && and Bitwise &
The logical && operator doesn't check the second condition if the first condition is false. It
checks the second condition only if the first one is true.
The bitwise & operator always checks both conditions whether first condition is true or false.
30
Java OR Operator Example: Logical || and Bitwise |
The logical || operator doesn't check the second condition if the first condition is true. It
checks the second condition only if the first one is false.
The bitwise | operator always checks both conditions whether first condition is true or false.
31
Java Ternary Operator
Java Ternary operator is used as one line replacement for if-then-else statement and used a lot
in Java programming. It is the only conditional operator which takes three operands.
32
Java Assignment Operator
Java assignment operator is one of the most common operators. It is used to assign the value
on its right to the operand on its left.
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.
33
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:
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.
Example:
34
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.
Example:
35
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.
Example Program:
36
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.
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.
37
Syntax
Example program:
import java.util.*;
class Student
{ int num;
num=s.nextInt();
switch(num)
case 0: System.out.println("Hello");
break;
case 1: System.out.println("Welcome");
break;
38
}
Output:
Welcome
Another Example:
class Student
public static void main(String[] args) {
int num = 2;
switch (num){
case 0:
System.out.println("number is 0");
break;
case 1:
System.out.println("number is 1");
break;
default:
System.out.println(num);
}
}
}
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.
39
1. for loop
2. while loop
3. do-while loop
Syntax
Example:
40
Output:
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.
Syntax:
Example program:
41
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.
Syntax:
42
Example:
43
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.
Syntax
Flowchart:
44
public class Calculation {
public static void main(String[] args)
{
int i = 0;
System.out.println("Printing the list of first 10 even numbers \n");
do {
System.out.println(i);
i = i + 2;
}while(i<=10);
}
}
Output:
Jump Statements
Jump statements are used to transfer the control of the program to the specific statements.
45
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.
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.
Consider the following example in which we have used the break statement with the for loop.
46
for (int j = i; j<=5; j++)
{
if(j == 4)
{
continue;
}
System.out.println(j);
}
}
}
Output:
CONSTRUCTORS
DEFINITION:
47
Every time an object is created using the new() keyword, at least one constructor is
called.
The default constructor is used to provide the default values to the object like 0,
null, etc., depending on the type.
TYPES OF CONSTRUCTORS
no-arg constructor
parameterized constructor
48
1. Default constructor (no-arg constructor)
2. Parameterized constructor
Example Program:
class Student4
{
int id;
49
String name;
id = i;
name = n;
}
void display(){System.out.println(id+" "+name);
}
public static void main(String args[]){
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
s1.display();
s2.display();
}
}
50