Unit-1 - Introduction to JAVA
Unit-1 - Introduction to JAVA
● Class
● Objects
● Data Abstraction
● Encapsulation
● Inheritance
● Polymorphism
● Dynamic Binding
● Message Passing
1. Class:
● A class is a user-defined data type. It consists of data members and
member functions, which can be accessed and used by creating an
instance of that class.
● It represents the set of properties or methods that are common to all
objects of one type.
2. Object:
● An Object is an instance of a Class. When a class is defined, no memory is
allocated but when it is instantiated (i.e. an object is created) memory is
allocated.
● An object has an identity, state, and behavior. Each object contains
data and code to manipulate the data.
● Objects can interact without having to know details of each other’s data
or code, it is sufficient to know the type of message accepted and type of
response returned by the objects.
3. Data Abstraction:
● Data abstraction refers to providing only essential information about the data to the
outside world, hiding the background details or implementation.
● Consider a real-life example of a man driving a car. The man only knows that pressing the
accelerators will increase the speed of the car or applying brakes will stop the car, but he
does not know about how on pressing the accelerator the speed is increasing, he does
not know about the inner mechanism of the car or the implementation of the accelerator,
brakes, etc in the car. This is what abstraction is.
4. Encapsulation:
● Encapsulation is defined as the wrapping up of data under a single unit. It is the
mechanism that binds together code and the data it manipulates.
● In Encapsulation, the variables or data of a class are hidden from any other class
and can be accessed only through any member function of their class in which they
are declared. As in encapsulation, the data in a class is hidden from other classes,
so it is also known as data-hiding.
5. Inheritance:
Inheritance is an important pillar of OOP(Object-Oriented Programming). The capability of a
class to derive properties and characteristics from another class is called Inheritance. When we
write a class, we inherit properties from other classes. So when we create a class, we do not
need to write all the properties and functions again and again, as these can be inherited from
another class that possesses it. Inheritance allows the user to reuse the code whenever possible
and reduce its redundancy.
6. Polymorphism:
The word polymorphism means having many forms. In simple words, we can define
polymorphism as the ability of a message to be displayed in more than one form.
For example, A person at the same time can have different characteristics. Like a
man at the same time is a father, a husband, an employee. So the same person
posses different behavior in different situations. This is called polymorphism.
7. Dynamic Binding:
● In dynamic binding, the code to be executed in response to the function call is
decided at runtime. Dynamic binding means that the code associated with a given
procedure call is not known until the time of the call at run time.
● Dynamic Method Binding One of the main advantages of inheritance is that some
derived class D has all the members of its base class B. Once D is not hiding any of
the public members of B, then an object of D can represent B in any context where
a B could be used. This feature is known as subtype polymorphism.
8. Message Passing:
● It is a form of communication used in object-oriented programming as well as
parallel programming. Objects communicate with one another by sending and
receiving information to each other.
● A message for an object is a request for execution of a procedure and therefore will
invoke a function in the receiving object that generates the desired results.
● Message passing involves specifying the name of the object, the name of the
function, and the information to be sent.
Overview of JAVA
Java is guaranteed to be Write Once, Run Anywhere. Java is −
● Object-Oriented: In Java, everything is an object. Java can be easily extended
since it is based on the object model.
● Platform Independent: Unlike many other programming languages, including C
and C++, when Java is compiled, it is not compiled into a platform-specific
machine but rather into platform-independent byte code. This byte code is
distributed over the web and interpreted by the virtual machine (JVM) on
whichever platform it is being run on.
● Simple: Java is designed to be easy to learn. If you understand the basic
concept of OOP Java, it would be easy to master.
● Secure: With Java's secure feature, it enables the development of virus-free,
tamper-free systems. Authentication techniques are based on public-key
encryption.
● Architecture-neutral: The Java compiler generates an architecture-neutral object
file format, which makes the compiled code executable on many processors with
the presence of the Java runtime system.
● Portable: Being architecture-neutral and having no implementation-dependent
aspects of the specification makes Java portable. Compiler in Java is written in ANSI C
with a clean portability boundary, which is a POSIX subset.
● Robust: Java makes an effort to eliminate error-prone situations by emphasizing
mainly compile-time error checking and runtime checking.
Multithreaded: With Java's multithreaded feature, it is possible to write programs that
can perform many tasks simultaneously. This design feature allows the developers to
construct interactive applications that can run smoothly.
● Interpreted: Java byte code is translated on the fly to native machine instructions and
is not stored anywhere. The development process is more rapid and analytical since
the linking is an incremental and light-weight process.
● High Performance: With the use of just-in-Time compilers, Java enables high
performance.
Distributed: Java is designed for the distributed environment of the internet.
● Dynamic: Java is considered to be more dynamic than C or C++ since it is designed to
adapt to an evolving environment. Java programs can carry an extensive amount of
run-time information that can be used to verify and resolve accesses to objects in run-
time.
Overview of Java
Some of the important concepts of Java include:
● A Java virtual machine (JVM), which provides the fundamental basis for platform independence
● Automated storage management techniques, such as garbage collection
● Language syntax that is similar to that of the C language
The result is a language that is object-oriented and efficient for application programming.
● Classes
● Objects
● Interfaces
● Encapsulation
● Inheritance
● Polymorphism
Java is a popular, general-purpose, high-level programming language that is widely used for building a variety of applications. It was
created by Sun Microsystems (now owned by Oracle Corporation) in the mid-1990s and has since become one of the most
widely used programming languages in the world.
Few things must be clear before setting up the environment which can better be perceived from the below image provided as follows:
● JDK(Java Development Kit): JDK is intended for software developers and
includes development tools such as the Java compiler, Javadoc, Jar, and a
debugger.
● JRE(Java Runtime Environment): JRE contains the parts of the Java libraries
required to run Java programs and is intended for end-users. JRE can be
viewed as a subset of JDK.
● JVM: JVM (Java Virtual Machine) is an abstract machine. It is a specification
that provides a runtime environment in which java bytecode can be
executed. JVMs are available for many hardware and software platforms.
Command line arguments
● The java command-line argument is an argument i.e. passed at the time of running the java
program.
● The arguments passed from the console can be received in the java program and it can be used
as an input.
for(int i=0;i<args.length;i++)
System.out.println(args[i]);
}
}
Output: sonoo
jaiswal
abc
Java Data Types
Data types in Java are of different sizes and values that can be stored in the
variable that is made as per convenience and circumstances to cover up all
test cases. Java has two categories in which data types are segregated
1. Primitive Data Type: such as boolean, char, int, short, byte, long,
float, and double. The Boolean with uppercase B is a wrapper class for
the primitive data type boolean in Java.
2. Non-Primitive Data Type or Object Data type: such as String, Array,
etc.
Primitive Data Types 1.5. float
1.1. byte ● Size: 4 bytes (32 bits)
● Range: ±3.40282347E+38F (6-7 significant decimal digits)
● Size: 1 byte (8 bits) ● Description: The float type is used for single-precision floating-
● Range: -128 to 127 point numbers (decimals). It is less precise than double.
● Description: The byte type is used to save memory in large arrays
when the memory savings are crucial. It is the smallest data type.
1.6. double
1.2. short
● Size: 8 bytes (64 bits)
● Size: 2 bytes (16 bits) ● Range: ±1.7976931348623157E+308 (15 decimal digits of
● Range: -32,768 to 32,767 precision)
● Description: The short type is used when you need a larger range ● Description: The double type is used for double-precision
than byte but want to save memory compared to int. floating-point numbers (decimals). It provides more precision
than float and is the default choice for floating-point
1.3. int
calculations.
● Size: 4 bytes (32 bits) 1.7. char
● Range: -2^31 to 2^31 - 1 (-2,147,483,648 to 2,147,483,647) ● Size: 2 bytes (16 bits)
● Description: The int type is the default choice for integer values. It is ● Range: 0 to 65,535 (unsigned)
used when you need a larger range than byte and short. ● Description: The char type is used to represent a single
1.4. long character. It is based on Unicode, so it can store characters
from most languages and symbols.
● Size: 8 bytes (64 bits) 1.8. boolean
● Range: -2^63 to 2^63 - 1 (-9,223,372,036,854,775,808 to
● Size: 1 bit (but JVM optimizes memory)
9,223,372,036,854,775,807)
● Description: The long type is used when a wider range of values is ● Values: true or false
required than int. Typically used for large numbers or timestamps. ● Description: The boolean type is used for representing binary
Types of Operators in Java
1. Arithmetic Operators
2. Unary Operators
3. Assignment Operator
4. Relational Operators
5. Logical Operators
6. Ternary Operator
7. Bitwise Operators
8. Shift Operators
9. instance of operator
1. Arithmetic Operators
Arithmetic Operators are used to perform simple arithmetic operations on primitive and non-primitive
data types.
● * : Multiplication
● / : Division
● % : Modulo
● + : Addition
● – : Subtraction2. Unary Operators
Unary Operators need only one operand. They are used to increment, decrement, or negate
a value.
In many cases, the assignment operator can be combined with others to create
shorthand compound statements. For example, a += 5 replaces a = a + 5. Common
compound operators include:
Relational 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
● == , Equal to.
Logical Operators are used to perform “logical AND” and “logical OR” operations, similar to
AND gate and OR gate in digital electronics. They have a short-circuiting effect, meaning the
second condition is not evaluated if the first is false.
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
Bitwise Operators are used to perform the manipulation of individual bits of a number and with
any of the integer types. They are used when performing update and query operations of the
Binary indexed trees.
of two).
● >> (Signed right shift) – Shifts bits right, filling 0s (divides by
// Main class 8
0
class GFG {
16
// main driver method
public static void main(String[] args)
{ int number = 2;
// 2 bit left shift operation
int Ans = number << 2;
System.out.println(Ans);
Ans = number >> 2;
System.out.println(Ans);
number =64;
Ans = number >> 2;
System.out.println(Ans); } }
9. instanceof operator
2)
● The instance of operator is used for
class Animal{}
type checking. It can be used to test if
an object is an instance of a class, a class Dog1 extends
subclass, or an interface. The general Animal{//Dog inherits Animal
format ,
● object instance of
public static void main(String
class/subclass/interface
args[]){
1)
class Simple1{ Dog1 d=new Dog1();
public static void main(String args[]){ System.out.println(d instanceof
Simple1 s=new Simple1(); Animal);//true
System.out.println(s
}
instanceofSimple1);//true
} }
}
Output:true
Output:true
What is Expression in Java?
In Java, an expression is a combination of values, variables, operators, and method invocations that are
evaluated to produce a single value. An expression can be a single value or a combination of values that
produce a result. Expressions can be used in various contexts, such as in assignments, conditional
statements, and loops.
2. Loop statements
○ do while loop
○ while loop
○ for loop
○ for-each loop
3. Jump statements
○ break statement
○ 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.,
1. If statement and
2. switch statement.
If Statement:
1. Simple if statement
2. if-else statement
3. if-else-if ladder
4. Nested if-statement
Simple if statement:
if(condition) {
}
Student.java
public class Student
int x = 10;
int y = 12;
}
if-else statement
Syntax:
if(condition) {
else{
int x = 10;
int y = 12;
else {
}
if-else-if ladder:
The if-else-if statement contains the if-statement followed by multiple else-if statements.
if(condition 1)
else if(condition 2)
else
}
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.
if(condition 1)
if(condition 2)
else
}
Student.java
public class Student {
if(address.endsWith("India")) {
if(address.contains("Meerut"))
else if (address.contains("Noida"))
else
{ System.out.println(address.split(",")[0]); }
else
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.
● 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
for loop
● 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.
//block of statements
}
The flow chart for the for-loop is given below.
Calculation.java
class Calculation {
int sum = 0;
sum = sum + j;
}
Find a factorial using for loop
import java.util.Scanner; // Factorial using For Loop
public static void main(String[] args) { for (int i = 1; i <= num; i++) {
}
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.
● 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.
while(condition){
//looping statements
}
Calculation .java
public class Calculation {
int i = 0;
while(i<=10) {
System.out.println(i);
i = i + 2;
}
Find a factorial using for loop
import java.util.Scanner; int fact = 1;
}
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.
do
//statements
} while (condition);
The flow chart of the do-while loop is given in the following
image.
Calculation.java
class Calculation {
int i = 0;
do {
System.out.println(i);
i = i + 2;
}while(i<=10);
}
Find a factorial using for loop
int fact = 1;
import java.util.Scanner;
int j = 1;
class Factorial {
do {
public static void main(String[] args) {
fact*= j;
Scanner sc = new Scanner(System.in);
j++; }
// Ask for input
while (j <= num);
System.out.print("Enter a number :");
System.out.println("Factorial using Do-While Loop: " + fact);
int num = sc.nextInt();
sc.close(); } }
Jump Statements
System.out.println(i);
if(i==6) {
break;
}
Java continue statement
{ continue; }
System.out.println(i);
}
Java Arrays
● Java array is an object which contains elements of a similar data
type.
● 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.
Example of Java Array
class Testarray{
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
System.out.println(a[i]);
}}
Java String
InJava, string is basically an object that represents sequence of char
values. An array of characters works same as Java string. For example:
char[] ch={'j','a','v','a','t','p','o','i','n','t'};
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.
ArrayList in Java
● An iterator for lists that allows the programmer to traverse the list in either
direction, modify the list during iteration, and obtain the iterator's current
position in the list.
● A ListIterator has no current element; its cursor position always lies between the
element that would be returned by a call to previous() and the element that would be
returned by a call to next().
● An iterator for a list of length n has n+1 possible cursor positions, as illustrated by the
carets (^) below:
Element(0) Element(1) Element(2) ... Element(n-1)
cursor positions: ^ ^ ^ ^ ^
● Note that the remove() and set(Object) methods are not defined in terms of the cursor
position; they are defined to operate on the last element returned by a call to next() or
previous().
● This interface is a member of the Java Collections Framework.
Java ListIterator
Like Iterator, ListIterator is a Java Iterator, which is used to iterate elements one-by-one from a List
implemented object.
● It is available since Java 1.2.
● It extends Iterator interface.
● It is useful only for List implemented classes.
● Unlike Iterator, It supports all four operations: CRUD (CREATE, READ, UPDATE and DELETE).
● Unlike Iterator, It supports both Forward Direction and Backward Direction iterations.
● It is a Bi-directional Iterator.
● It has no current element; its cursor position always lies between the element that would be
returned by a call to previous() and the element that would be returned by a call to next().
● hasNext(): This method returns true when the list has more elements to traverse while
traversing in the forward direction
● next(): This method returns the next element of the list and advances the position of
the cursor.
● nextIndex(): This method returns the index of the element that would be returned on
calling the next() method.
● hasPrevious(): This method returns true when the list has more elements to traverse
while traversing in the reverse direction
● previous(): This method returns the previous element of the list and shifts the cursor
one position backward.
● previousIndex(): This method returns the index of the element that would be returned
import java.util.*;
// Traversing elements, the iterator is
at the end at this point
public class GFG { System.out.println("Backward Direction
Iteration:");
public static void main(String[] args) while (listIterator.hasPrevious())
{ {
// list of names
List<String> names = new System.out.println(listIterator.previous()
LinkedList<>(); );
names.add("learn"); }
names.add("from"); }
names.add("Geeksforgeeks"); }
// Getting ListIterator
ListIterator<String> listIterator
= names.listIterator();
// Traversing elements
System.out.println("Forward
Direction Iteration:");
while (listIterator.hasNext()) {
System.out.println(listIterator.next());
}
Java HashSet
Java HashSet class is used to create a collection that uses a hash table for storage. It inherits
the AbstractSet class and implements Set interface.
import java.util.*;
class HashSetExample1{
public static void main(String args[]){
set.add("Three");
set.add("Four");
set.add("Five");
Iterator<String> i=set.iterator();
while(i.hasNext())
{
System.out.println(i.next());
Ignoring Duplicate Elements
In this example, we see that HashSet does not allows duplicate elements.
import java.util.*;
class HashSetExample2{ Output:
public static void main(String args[]){
Ajay
//Creating HashSet and adding elements Vijay
HashSet<String> set=new HashSet<String>(); Ravi
set.add("Ravi");
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
//Traversing elements
Iterator<String> itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Removing Elements HashSet<String> set1=new
Here, we see different ways to remove an element. HashSet<String>();
set1.add("Ajay");
set1.add("Gaurav");
set.addAll(set1);
import java.util.*;
System.out.println("Updated List: "+set);
class HashSetExample3{
public static void main(String args[]){ //Removing all the new elements from
HashSet<String> set=new HashSet<String>(); HashSet
set.add("Ravi"); set.removeAll(set1);
set.add("Vijay"); System.out.println("After invoking
set.add("Arun"); removeAll() method: "+set);
//Removing elements on the basis of
set.add("Sumit");
specified condition
System.out.println("An initial list of set.removeIf(str->str.contains("Vijay"));
elements: "+set); System.out.println("After invoking
//Removing specific element from HashSet removeIf() method: "+set);
set.remove("Ravi"); //Removing all the elements available in
System.out.println("After invoking remove(object) the set
method: "+set); set.clear();
System.out.println("After invoking clear()
method: "+set);
}
An initial list of elements: [Vijay, Ravi, Arun, Sumit]
2) ArrayList increments 50% of current array Vector increments 100% means doubles the
size if the number of elements exceeds from array size if the total number of elements
its capacity. exceeds than its capacity.
5) ArrayList uses the Iterator interface to A Vector can use the Iterator interface or
traverse the elements. Enumeration interface to traverse the
elements.