0% found this document useful (0 votes)
14 views

UNIT I Java Basics

Uploaded by

Md Anas
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

UNIT I Java Basics

Uploaded by

Md Anas
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 141

MLR INSTITUTE OF TECHNOLOGY

A6IT02 – Object Oriented


Programming using JAVA
Subject Handled To Subject Handled BY

Second Year Dr.P.Chinnasamy


(B.Tech-CSE) Associate Professor, MLRIT

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
UNIT – I Java Basics
✓ Review of Object oriented concepts, History of
Java, Java buzzwords
✓ JVM architecture, Data types, Variables, Scope
and life time of variables, arrays,
✓ operators, control statements, type
conversion and casting,
✓ simple java program, constructors, methods,
Static block, Static Data, Static Method ,
✓ String and String Buffer Classes, Using Java API
Document

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
2
2
Object Oriented Concepts
✓ Object-Oriented Programming is a paradigm that
provides many concepts, such as Abstraction,
Encapsulation, Inheritance, Polymorphism, etc.
✓ The programming paradigm where everything is
represented as an object is known as a truly
object-oriented programming language.
✓ Smalltalk is considered the first truly object-
oriented programming language.
✓ Popular object-oriented languages
are Java, C#, PHP, Python, C++, Kotlin etc..

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
3
3
Four Pillars of OOPS

Encapsulation Polymorphism
Wrapping up of ability to assume
Abstraction data (variables) Inheritance several different
and methods forms
into single unit Acquiring the
essential properties from one
features without class to another
its inner details class or producing
or hiding new class from
internal already existing class
implementation

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
4
4
Abstraction

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
5
5
Abstraction
✓ Providing the essential features without its inner
details is called abstraction (or) hiding internal
implementation is called Abstraction.
✓ We can enhance the internal implementation
without effecting outside world.
✓ Abstraction provides security.
✓ A class contains lot of data and the user does not
need the entire data.

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
6
6
Encapsulation

Object state Behaviour

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
7
7
Encapsulation
✓ Wrapping up of data (variables) and methods into
single unit is called Encapsulation.
✓ Class is an example for encapsulation.
✓ Encapsulation can be described as a protective
barrier that prevents the code and data being
randomly accessed by other code defined outside
the class.

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
8
8
Inheritance

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
9
9
Inheritance
✓ Acquiring the properties from one class to another
class is called inheritance (or) producing new class
from already existing class is called inheritance.
✓ Reusability of code is main advantage of
inheritance.
✓ In Java inheritance is achieved by using extends
keyword.
✓ The properties with access specifier private cannot
be inherited.

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
10
10
Polymorphism

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
11
11
Polymorphism
✓ Polymorphism in Java is a concept by which we
can perform a single action in different ways.
✓ Polymorphism is derived from 2 Greek words: poly
and morphs.
✓ The word "poly" means many and "morphs" means
forms.

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
12
12
Class & Objects

State
Address
Color
Area

Behaviour
Open door
Close door
Water Fill

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
13
13
Class & Objects
✓ In object-oriented programming, a class is a
programming language construct that is used as a
blueprint to create objects.
✓ This blueprint includes attributes and methods
that the created objects all share.
✓ Fundamentally, it encapsulates the state and
behavior of that which it conceptually represents.
✓ It encapsulates state through data placeholders
called member variables; it encapsulates behavior
through reusable code called methods

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
14
14
History of JAVA

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
15
15
Oak Tree

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
16
16
Symbols of JAVA

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
17
17
JAVA Buzzwords
Simple

Platform Independent

Secure

Portable Interpreted

Object- Oriented High Performance

Robust Distributed

Multi-threaded Dynamic

Architectural Neutral
MLR INSTITUTE OF TECHNOLOGY
31-Oct-23
18
18
Simple
✓ Java is a small and simple language.
✓ Java does not use pointers, pre-processor header
files, goto statement and many other.
✓ It also eliminates operator overloading and
multiple inheritance.
✓ Java inherits the C/C++ syntax and many of the
object oriented features of C++.

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
19
19
Platform Independent
✓ Compile the Java program on one OS (operating
system) that compiled file can execute in any
OS(operating system) is called Platform
Independent Nature.
✓ The java is platform independent language.
✓ The java applications allows its applications
compilation one operating system that compiled
(.class) files can be executed in any operating system

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
20
20
Secure
✓ Java is best known for its security. With Java, we
can develop virus-free systems
✓ No explicit pointer
✓ Java Programs run inside a virtual machine
sandbox.

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
21
21
Portable
✓ Java programs can be easily moved from one
computer system to another, anywhere and
anytime.

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
22
22
Object- Oriented
✓ Java is a true object oriented language.
✓ Almost everything in java is an object.
✓ All program code and data reside within objects
and classes Java comes with an extensive set of
classes, arranged in packages, that we can use in
our programs by inheritance.
✓ The object model in java is simple and easy to
extend.

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
23
23
Robust
✓ It uses strong memory management.
✓ There is a lack of pointers that avoids security
problems.
✓ Java provides automatic garbage collection which
runs on the Java Virtual Machine to get rid of
objects which are not being used by a Java
application anymore.
✓ There are exception handling and the type
checking mechanism in Java.

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
24
24
Robust
✓ Multithreaded means handling multiple tasks
simultaneously.
✓ This means that we need not wait for the
application to finish one task before beginning
another.
✓ To accomplish this, java supports multithreaded
programming which allows to write programs that
do many things simultaneously.

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
25
25
Interpreted & High Performance

✓ Java performance is impressive for an interpreted


language, mainly due to the use of byte code.
✓ This code can be interpreted on any system that
provides a JVM.
✓ Java was designed to perform well on very low
power CPUs.

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
26
26
Distributed
✓ Java is designed for the distributed environment of
the Internet, because it handles TCP/IP
protocols.
✓ In fact, accessing a resource using a URL is not
much different from accessing a file.
✓ The original version of Java (Oak) included features
for intra address- space messaging.
✓ Java revived these interfaces in a package called
Remote Method Invocation (RMI).
✓ This feature brings an unparalleled level of
abstraction to client/ server programming.

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
27
27
Dynamic
✓ Java is a dynamic language.
✓ It supports the dynamic loading of classes.
✓ It means classes are loaded on demand

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
28
28
Architectural- Neutral
✓ A central issue for the Java designers was that of
code longevity and portability.
✓ One of the main problems facing programmers is
that no guarantee exists that if you write a
program today, it will run tomorrow—even on the
same machine.
✓ Operating system upgrades, processor upgrades,
and changes in core system resources can all
combine to make a program malfunction.

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
29
29
Architectural- Neutral
✓ In C programming, int data type occupies 2 bytes of
memory for 32-bit architecture and 4 bytes of
memory for 64-bit architecture.
✓ But in java, int occupies 4 bytes of memory for both
32 and 64 bit architectures.
✓ Java Virtual Machine solves this problem. The goal
is “write once; run anywhere, any time, forever.
(WORA)”

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
30
30
Class & Objects
✓ In object-oriented programming, a class is a
programming language construct that is used as a
blueprint to create objects.
✓ This blueprint includes attributes and methods
that the created objects all share.
✓ Fundamentally, it encapsulates the state and
behavior of that which it conceptually represents.
✓ It encapsulates state through data placeholders
called member variables; it encapsulates behavior
through reusable code called methods

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
31
31
Naming Conversion

✓ All Identifiers must start with alphabet (A to Z ,a-z)


or underscore( _ ) or Currency Character()
✓ Keywords cannot be an identifiers
✓ Identifiers are highly Case-Sensitive
✓ Examples:
Valid Invalid
Age 1abc
rupee -salary
_num
Num_1

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
32
32
Object
✓ An entity that has state and behavior is known as
an object
✓ Examples:

PEN BAG CAR BIKE BOOK APPLE

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
33
33
Explanation of Example

Try to find state


and behavior for
other object

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
34
34
Class
✓ A class is a group of objects which have common
properties.
✓ It is a template or blueprint from which objects are
created.
✓ Example:
✓ Declaring Objects (Also called instantiating a class)
✓ When an object of a class is created, the class is said to
be instantiated.
✓ A Single class may have any number of instance

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
35
35
Syntax for Class
✓ class <classname>
{
fields; methods
}
✓ Example
✓ class Student{
int id; //field or data member or instance
variable
String name; //field or data member or
instance variable
}
MLR INSTITUTE OF TECHNOLOGY
31-Oct-23
36
36
Class and Object Example
//Filename:Student.java
Output:
class Student
0
{ null
int id; //field or data member or instance variable
String name;
public static void main(String args[])
{
Student s1=new Student();
System.out.println(s1.id);
System.out.println(s1.name);
}
}

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
37
37
Class and Object Example
//Filename: TestStudent1.java
class Student
{
int id;
String name;
}

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
38
38
Class and Object Example
//Creating another class TestStudent1 which
Output:
contains the main method
0
class TestStudent1
null
{
public static void main(String
args[])
{
Student s1=new Student();
System.out.println(s1.id);
System.out.println(s1.name);
}
}
MLR INSTITUTE OF TECHNOLOGY
31-Oct-23
39
39
Java Virtual Machine
(JVM)
✓ A Virtual Machine is a software implementation of a
physical machine.
✓ Java was developed with the concept of WORA
(Write Once Run Anywhere), which runs on a VM.
✓ The compiler compiles the Java file into a
Java .class file, then that .class file is input into the
JVM, which loads and executes the class file.

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
40
40
JVM Architecture

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
41
41
JVM Sub System

JVM Sub System

Loads
Code
Verifies
Code Execute
Code
Provides Run
Time
Environment

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
42
42
Class Loader
✓ Classloader is a subsystem of JVM which is used to
load class files.
✓ Bootstrap ClassLoader: This is the first classloader
which is the super class of Extension classloader. It
loads the rt.jar file.
✓ Extension ClassLoader: This is the child
classloader of Bootstrap and parent classloader of
System classloader. It loads the jar files located
inside JAVA_HOME/jre/lib/ext directory.
✓ System/Application ClassLoader: This is the child
classloader of Extension classloader. It loads the
classfiles from classpath.

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
43
43
Class, Heap & Stack
✓ Area stores per-class structures such as the runtime
constant pool, field and method data, the code for
methods.
✓ Heap is the runtime data area in which objects are
allocated.
✓ Java Stack stores frames. It holds local variables
and partial results, and plays a part in method
invocation and return.
✓ Each thread has a private JVM stack, created at the
same time as thread.
✓ A new frame is created each time a method is invoked.
A frame is destroyed when its method invocation
completes.

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
44
44
Registers & Native
Methods
✓ PC Registers :Each thread will have separate PC
Registers, to hold the address of current executing
instruction once the instruction is executed the PC
register will be updated with the next instruction.
✓ Native Method stacks : Native Method Stack holds
native method information. For every thread, a
separate native method stack will be created.

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
45
45
Execution Engine
✓ A virtual processor
✓ Interpreter: Read bytecode stream then execute
the instructions.
✓ Just-In-Time(JIT) compiler: It is used to improve
the performance. JIT compiles parts of the byte
code that have similar functionality at the same
time, and hence reduces the amount of time
needed for compilation.

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
46
46
Java Native Interface (JNI)
✓ Java Native Interface (JNI) is a framework which
provides an interface to communicate with
another application written in another language
like C, C++, Assembly etc.
✓ Java uses JNI framework to send output to the
Console or interact with OS libraries.

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
47
47
Data Types
✓ Data types are used to represent the type of the
variable and type of the expression.
✓ Java is Strictly typed / Strongly typed /
Statically typed
✓ Every variable has a type
✓ Every expression is a type
✓ All assignments are checked for type
compatibility at compile time

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
48
48
Types of Data Types

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
49
49
Integer - Byte
✓ A byte is composed of 8 consecutive bits in the
memory of computer. Each bit is a binary number of
0 or 1.

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
50
50
Byte - Range
✓ Max value=127

✓ MSB=0----> +ve value


✓ Value-→ 1+2+4+8+16+32+64=127

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
51
51
Byte - Range
✓ Min value=-128

✓ MSB=1----> -ve value


✓ Value→ All negative values will be calculated in 2’s
complement form
✓ 0000000--->1111111
✓ +1
✓ ------------------
✓ 10000000 ===>-128

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
52
52
Application
✓ Used to store data into Files
✓ Network

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
53
53
Integer - Short
✓ The short data type is a 16-bit signed two's
complement integer.
✓ Rarely used data type.
✓ Size: 2 bytes
✓ Range:-32,768 to 32767.
✓ Default value: 0

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
54
54
Integer - int
✓ int data type is the preferred data type when we create
variables with a numeric value.
✓ It will take 32 bits or 4bytes of memory.
✓ Range:-2147483648 to 2147483647
✓ Default value: 0

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
55
55
Integer - long
✓ Used when int is not large enough to hold the value, it
has wider range than int data type.
✓ Size :8 bytes or 64 bits
✓ Range:-9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
✓ Default value: 0

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
56
56
Float
✓ A float data type is a single precision number format
that occupies 4 bytes or 32 bits of memory.
✓ A float data type in java stores a decimal value with 6-
7 total digits of precision.
✓ Ex: float f=10.25212121212f
✓ But it will take only 10.252121.
✓ Range: 3.4e-038 to 3.4e+038
✓ Default value: 0.0

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
57
57
Double
✓ The double data type is a double-precision 64-bit
IEEE 754 floating points.
✓ In Java any floating value by default it’s a double type
✓ 12-13 digits precisions it will take.
✓ EX: double d=10.2521212121213434332222;
✓ Output: 10.252121212121343

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
58
58
Char
✓ The char data type is a single 16-bit Unicode
character.
✓ Ex: char c=‘A’;
✓ Unsigned data type.
✓ Range: 0 to 65535
✓ Default value: \u0000

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
59
59
Why 16 bits for char type?
✓ In C/C++ uses only ASCII characters and to
represent all ASCII characters 8-bits is enough.
✓ Java uses Unicode system, to represent Unicode
system 8 bit is not enough.
✓ Unicode=ASCII + Other language symbols.

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
60
60
Boolean
✓ The Boolean data type has only two possible values:
true and false.
✓ Use this data type for simple flags that track
true/false conditions.
✓ This data type represents one bit of information, but
its “size” isn’t something that’s precisely defined.
✓ Default value is false
✓ EX:
✓ boolean b=true;
✓ boolean b=0; ➔Not allowed

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
61
61
Identifiers
✓ An identifier is a name used to identify entities like a variable,
methods, classes and interfaces etc.
✓ (Or)
✓ Any name in the java program like variable name, class name,
method name, interface name is called identifier.
✓ Ex:
class Test → Test identifier
{
void add() → add identifier
{
int a=10; → a identifier
int b=20; → b identifier
}
}

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
62
62
Identifiers
✓ Java identifiers should not start with numbers, it may start with
alphabet symbol and underscore symbol and dollar symbol.
✓ An identifier should not contains symbols like + , - , . , @ , # .
Only allowed special symbols are _ and
✓ Duplicate identifiers are not allowed.
Ex:
class Test
{
void add()
{
int a=10;
int a=20; → An identifier should not be duplicated.
}
}

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
63
63
Variables
✓ Variables are containers for storing data values.
✓ datatype variable_name= value;
✓ String - stores text, such as "Hello". String values are
surrounded by double quotes
✓ int - stores integers (whole numbers), without
decimals, such as 123 or -123
✓ float - stores floating point numbers, with decimals,
such as 19.99 or -19.99
✓ char - stores single characters, such as 'a' or 'B'. Char
values are surrounded by single quotes
✓ boolean - stores values with two states: true or false

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
64
64
Types of Variables

Variables Types

Local
Instance
Static

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
65
65
Local Variables
✓ The variables which are declare inside a method or
inside a block or inside a constructor is called local
variables.
Ex: class Student
{
public void studentInfo()
{
// local variables
String name=“Chinna”;
int age = 33;
System.out.println("Student name : " + name);
}
}

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
66
66
Local Variables
✓ These variables are created when the block is entered
or the function is called and destroyed after exiting
from the block or when the call returns from the
function.
✓ Hence The scope of local variables are inside a method
or inside a constructor or inside a block.
✓ JVM wont provide any initial values for local variables.
So initialization of Local Variable is Mandatory. If not
it will generate compile time error.
✓ Access modifiers (public , private , protected , default)
are not allowed for local variables.
✓ Local variables will be stored in stack area

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
67
67
Local Variables- Example
Example:

public class Test


{
public static void main(String[] args)
{
Test t=new Test();
t.m1();
}
public void m1()
{
//Declaring variable inside method..
int i=10;
System.out.println(i);
}
public Test()
{
//Declaring variable inside constructor..
int j=20;
System.out.println(j);
}
{
//Declaring variable inside block..
int k=30;
System.out.println(k);
}
}

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
68
68
Instance Variables
✓ Instance variables are declared inside class and
outside of methods or constructor or block.
Ex: class A
{
int a; //instance variable
public static void main(String[] args)
{
}
}

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
69
69
Instance Variables
✓ Instance variables are created when an object of the
class is created and destroyed when the object is
destroyed.
✓ We are able to access instance variables only inside
the class any number of methods.
✓ Initialization of Instance Variable is not mandatory
JVM automatically allocates default values.
✓ Unlike static variable, instance variables have their own
separate copy i.e, if any changes done in instance
variable that will not reflect on other objects.
✓ Instance variables are not allowed inside static area
directly. But using object it will allow

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
70
70
Static Variables
✓ If any variable declared inside class and out side
methods with “static” key word is called static variable.
Ex: public class Test
{
static int a=10;
public static void main(String[] args)
{
}
}
✓ Static variables are also called as class variable
because they are associated with the class and common
for all the instances of the class.

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
71
71
Arrays

Collection of
Elements

1 2 3 4 5 6 Integer

A B C D E F String

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
72
72
Quiz
1. Which of these best describes an array?

A) A data structure that shows a


hierarchical behaviour
B) Container of objects of similar
types
C) Arrays are immutable once
initialised
D) Arrays are mutable once
initialised
MLR INSTITUTE OF TECHNOLOGY
31-Oct-23
73
73
Real Time Example

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
74
74
Real Time Example

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
75
75
Array Declaration &
Initialization

Declare an array , define


the variable type with String[ ] cars;
square brackets

Create array of
strings

String[ ] cars = {“Volvo”, “BMW”,


“MG”, ”Ford”};

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
76
76
Creating an Array

new

int myArray = new int[7];

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
77
77
Creation of Array

✓ Type[] arrayName;
✓ Data type can be primitive types like int,
char, float,..(or) class type.
✓ Array name can be any valid identifier.
✓ Ex: int a[];
✓ String s[];
✓ Student student[];

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
78
78
Array Creation: Anonymously

Create an array
without specifying
any name

new int[ ] { 123, 234, 435}; // int array


new String[ ] {“java”, “c”, “python”}; //
String array

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
79
79
Array Initialization
✓ Approach 1:-
✓ Syntax:
✓ Type variable_name[] = {element1, elem2,
element3, lement4,..etc};
✓ Ex: int a[] = {10,20,30,40};
✓ Type Variable_name[]=new Type[Initialization
✓ Ex: int[] a=new int[4];
✓ a[0]=10;
✓ a[1]=20;
✓ a[2]=30;
✓ a[3]=40;

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
80
80
Quiz
Create array of Integer

int[ ] myNum= {“1”, “2”, “3”}

int[ ] myNum= {1, 2, 3}

int[ ] myNum= {1, 2, 3};

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
81
81
Accessing Array

0 1 2 3 4 5

A B C D E F

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
82
82
Array Accessing Example

String[ ] cars = {“Volvo”, “MG”, “BMW”};


System.out.println(cars[1]);

Output: MG

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
83
83
public class array
{
public static void main(String args[])
{
int []arr = {1,2,3,4,5};
System.out.println(arr[2]);
System.out.println(arr[4]); } }

a) 3 and 5 b) 5 and 3

c) 2 and 4 d) 4 and 2

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
84
84
Array Operations

How to change the


1 values in array

2 Find the length of array

Print all the elements


3 in array

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
85
85
Array Operations using ForEach

Syntax:
for(type variable : arrayname)
{
….
}

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};


for (String i : cars)
{
System.out.println(i);
}

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
86
86
Operators
✓ JAVA Operator is a symbol i.e used to perform
operations on operands.
✓ Arithmetic Operators
✓ Assignment Operators
✓ Bitwise Operators
✓ Comparison Operators
✓ Unary Operators
✓ Logical Operators
✓ Ternary Operators
✓ Left Shift Operators
✓ Right Shift Operators

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
87
87
Arithmetic Operators

Operator Name Example Explanation


+ Addition a+b Sum of operands

- Subtraction a-b Difference of operands

* Multiplication a*b Product of operands

/ Division a/b Quotient of operands

% Modulus a%b Remainder of operands

** Exponentiation a ** b a raised to the power b

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
88
88
Assignment Operators
Operator Name Example Explanation

= Assign a=b The value of right operand is


assigned to the left operand.
+= Add then Assign a += b Addition same as a = a + b

-= Subtract then Assign a -= b Subtraction same as a = a - b

*= Multiply then Assign a *= b Multiplication same as a = a * b

/= Divide then Assign a /= b Find quotient same as a = a / b


(quotient)
%= Divide then Assign a %= b Find remainder same as a = a %
(remainder) b

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
89
89
Bitwise Operators
Operator Name Example Explanation

& And a&b Bits that are 1 in both a and b are


set to 1, otherwise 0.
| Or (Inclusive or) a|b Bits that are 1 in either a or b are
set to 1
^ Xor (Exclusive or) a^b Bits that are 1 in either a or b are
set to 0.
~ Not ~a Bits that are 1 set to 0 and bits
that are 0 are set to 1
<< Shift left a << b Left shift the bits of operand a b
steps
>> Shift right a >> b Right shift the bits of a operand
by b number of places

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
90
90
Comparison Operators
Operator Name Example Explanation

== Equal a == b Return TRUE if a is equal to b

=== Identical a === b Return TRUE if a is equal to b,


and they are of same data type
!== Not identical a !== b Return TRUE if a is not equal to
b, and they are not of same data
type
<> Not equal a <> b Return TRUE if a is not equal to
b
< Less than a<b Return TRUE if a is less than b

> Greater than a>b Return TRUE if a is greater than


b

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
91
91
Unary Operators
Operator Name Example Explanation

++ Increment ++a Increment the value of a by


one, then return a
a++ Return a, then increment the
value of a by one
-- decrement --a Decrement the value of a by
one, then return a
a-- Return a, then decrement the
value of a by one

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
92
92
Logical Operators
Operator Name Example Explanation

and And a and b Return TRUE if both a and b are


true
Or Or a or b Return TRUE if either a or b is
true
xor Xor a xor b Return TRUE if either or b is
true but not both
! Not !a Return TRUE if a is not true

&& And a && b Return TRUE if either a and b


are true
|| Or a || b Return TRUE if either a or b is
true

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
93
93
Ternary Operators

(Condition) ? (Statement1) : (Statement2);

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
94
94
Control Statement

✓ statement is used to test condition

If Statement
if

If-else
If-else-if Nested if

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
95
95
if Statement

✓ If statement is used to executes the block of code exist


inside the if statement only if the specified condition is
true.
✓ Syntax
if(condition)
{
//code to be executed
}

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
96
96
If-else Statement

if(condition)
{
//code to be executed if true
}
else
{
//code to be executed if false
}

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
97
97
Activities

✓ Write a JAVA program to find given number is even or


odd

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
98
98
If-else-if Statement
if (condition1)
{
//code to be executed if condition1 is true
}
elseif (condition2){
//code to be executed if condition2 is true
}
elseif (condition3){
//code to be executed if condition3 is true
....
}
else{
//code to be executed if all given conditions are false
}

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
99
99
Activities

✓ Write a JAVA program to find biggest of three number


✓ Write a JAVA program to find the students marks grade

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
100
100
Nested if Statement
if (condition)
{
//code to be executed if condition is true
if (condition)
{
//code to be executed if condition is true
}
}

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
101
101
Nested if - Example
age = 23;
nationality = "Indian";
//applying conditions on nationality and age
if (nationality == "Indian")
{
if (age >= 18) {
echo "Eligible to give vote";
}
else {
echo "Not eligible to give vote";
}
}

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
102
102
Switch Case Statement
switch(expression)
{
case value1:
//code to be executed
break;
case value2:
//code to be executed
break;
......
default:
code to be executed if all cases are not matched;
}

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
103
103
Activities

✓ Write a JAVA program to find given character is Vowel


or not

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
104
104
Looping

JAVA Looping
for

while
Do while foreach

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
105
105
For Loop

✓ PHP for loop can be used to traverse set of code for the
specified number of times.
for(initialization; condition; increment/decrement)
{
//code to be executed
}

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
106
106
Activities

✓ Write a JAVA program to print the n real numbers


using for loop

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
107
107
Foreach Loop

✓ The foreach loop is used to traverse the array elements.


✓ It works only on array and object.
✓ The foreach loop works on elements basis rather than
index.
✓ we don't need to increment the value.
✓ for (type var : array)
✓{
statements using var;
✓}

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
108
108
Activities

✓ Write a JAVA program to display the vehicle


array(‘Cycle’, ‘Royal Enfield’, ‘Pulsar’, ‘Apache’,
‘Hyundai’, ‘Maruti’, ‘Benz’) using foreach loop

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
109
109
While Loop

✓ The while loop executes a block of code repeatedly until


the condition is FALSE.
✓ Once the condition gets FALSE, it exits from the body of
loop.
✓ while(condition)
{
//code to be executed
}

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
110
110
Activities

✓ Write a JAVA program to display the first 10 real


numbers using while loop.

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
111
111
do while Loop

✓ The JAVA do-while loop is guaranteed to run at least


once.
✓ The JAVA do-while loop is used to execute a set of code
of the program several times.
✓ do
{
//code to be executed
} while(condition);

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
112
112
Activities

✓ Write a JAVA program to display the first 10 real


numbers using do while loop.

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
113
113
Strings
✓ String is basically an object that represents
sequence of char values.
✓ An array of characters works same as Java string
✓ char[] ch={‘C',’h',’i',’n',’n',’a'};
String s=new String(ch);
✓ String s=“Chinna";
✓ The java.lang.String class
implements Serializable, Comparable and CharSequ
ence interfaces
✓ compare(), concat(), equals(), split(), length(),
replace(), compareTo(), intern(), substring() etc.

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
114
114
Creation of Strings
✓ By String literal
✓ By new keyword

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
115
115
String Literal
✓ Java String literal is created by using double
quotes
✓ String s="welcome";

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
116
116
New keyword
✓ String s=new String("Welcome");

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
117
117
Strings Methods
S.No Method Description
1 char charAt(int index) It returns char value for
the particular index
2 int length() It returns string length
3 static String It returns a formatted
format(String format, string.
Object... args)
4 static String It returns formatted string
format(Locale l, with given locale.
String format,
Object... args)

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
118
118
Strings Methods
S.No Method Description
5 String substring(int It returns substring for
beginIndex) given begin index.
6 String substring(int It returns substring for
beginIndex, int given begin index and end
endIndex) index.
7 boolean It returns true or false
contains(CharSequen after matching the
ce s) sequence of char value.
8 static String It returns a joined string.
join(CharSequence
delimiter,
CharSequence...
MLR INSTITUTE OF TECHNOLOGY
31-Oct-23
119
119
Strings Methods
S.No Method Description
9 boolean equals(Object It checks the equality of
another) string with the given
object.
10 boolean isEmpty() It checks if string is
empty.
11 String concat(String It concatenates the
str) specified string.
12 String replace(char It replaces all occurrences
old, char new) of the specified char value.

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
120
120
Strings Methods
S.No Method Description
13 static String It compares another
equalsIgnoreCase(Stri string. It doesn't check
ng another) case.
14 String[] split(String It returns a split string
regex) matching regex.
15 String[] split(String It returns a split string
regex, int limit) matching regex and limit.
16 int indexOf(int ch) It returns the specified
char value index.

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
121
121
Strings Methods
S.No Method Description
17 String toLowerCase() It returns a string in
lowercase.
18 String It returns a string in
toLowerCase(Locale l) lowercase using specified
locale.
19 String toUpperCase() It returns a string in
uppercase.
20 String It returns a string in
toUpperCase(Locale l) uppercase using specified
locale.
21 String trim() It removes beginning and
MLR
31-Oct-23
ending spaces 122
INSTITUTE OF TECHNOLOGY
of this
122
StringBuffer
✓ Java StringBuffer class is used to create mutable
(modifiable) String objects.
✓ The StringBuffer class in Java is the same as String
class except it is mutable i.e. it can be changed.

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
123
123
StringBuffer Class
Constructor
Constructor Description
StringBuffer() It creates an empty String
buffer with the initial
capacity of 16.
StringBuffer(String str) It creates a String buffer
with the specified string..
StringBuffer(int capacity) It creates an empty String
buffer with the specified
capacity as length.

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
124
124
StringBuffer Methods

StringBuffer Methods

append reverse
insert delete
replace

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
125
125
StringBuffer Methods
Method Description
append(String s) It is used to append the specified
string with this string.
insert(int offset, String s) It is used to insert the specified
string with this string at the
specified position.
replace(int startIndex, int It is used to replace the string
endIndex, String str) from specified startIndex and
endIndex.
delete(int startIndex, int It is used to delete the string from
endIndex) specified startIndex and endIndex.
reverse() is used to reverse the string.

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
126
126
String vs StringBuffer
String StringBuffer
The String class is immutable. The StringBuffer class is
mutable.
String is slow and consumes more StringBuffer is fast and
memory. consumes less memory
String class overrides the equals() StringBuffer class doesn't
method of Object class. override the equals() method of
Object class.
String class is slower while StringBuffer class is faster while
performing concatenation performing concatenation
operation. operation.
String class uses String constant StringBuffer uses Heap memory
pool.

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
127
127
Type Casting
✓ In Java, type casting is a method or process that
converts a data type into another data type in
both ways manually and automatically.
✓ The automatic conversion is done by the compiler
and manual conversion performed by the
programmer

Type Casting

Narrowing
Widening
MLR INSTITUTE OF TECHNOLOGY
31-Oct-23
128
128
Widening Type Casting
✓ Converting a lower data type into a higher one is
called widening type casting.
✓ It is also known as implicit conversion or casting
down.
✓ byte -> short -> char -> int -> long -> float -
> double

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
129
129
Narrowing Type Casting
✓ Converting a higher data type into a lower one is
called narrowing type casting.
✓ It is also known as explicit conversion or casting
up.
✓ double -> float -> long -> int -> char -> short -
> byte

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
130
130
Type Casting Vs Type Conversion
Type Casting Type Conversion
Type casting is a Type conversion allows a
mechanism in which one compiler to convert one data
data type is converted to type to another data type at
another data type using a the compile time of a
casting () operator by a program or code.
programmer.
It can be used both Type conversion is only
compatible data type and used with compatible data
incompatible data type. types.
It requires a programmer It does not require any
to manually casting one programmer intervention
data into another type. to convert one data.
MLR INSTITUTE OF TECHNOLOGY
31-Oct-23
131
131
Type Casting Vs Type Conversion

Type Casting Type Conversion


It is also known as It is also known as
narrowing conversion widening conversion
because one larger data type because one smaller data
converts to a smaller data type converts to a larger
type. data type.
It is more reliable and It is less efficient and less
efficient. reliable.

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
132
132
Why Constructor?

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
133
133
Why Constructor?

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
134
134
Constructor
✓ It works similar to methods.
✓ Unlike methods it automatically performs itsConstructor
job.
✓ i.e It calls implicitly.
✓It is a special type of method in java.
✓Like methods it also contain collection of
statements

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
135
135
Constructor
✓ How to use Constructor in java:
✓ Class name and constructor name must be
same.
✓ It automatically calls when object is created.
✓ It doesn’t return anything.

Example:
class Hacker{
Hacker(){ } Constructor
}

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
136
136
Constructor

How it
works? Object

Hacker obj = new Hacker()

Example: Class Hacker()


{
Hacker(){}
public static void main(String args[])
{
Hacker obj=new Hacker();
}
}

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
137
137
Types of Constructor

Constructor

Default
Parameterized

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
138
138
Default vs Parameterized
DEFAULT CONSTRUCTOR PARAMETERIZED CONSTRUCTOR

Constructor without argument Constructor with argument

Example: Example:

Class Hacker() Class Hacker()


{ {
Hacker(){} Hacker(datatype arg ,datatype arg){
public static void main(String }
args[]) public static void main(String args[])
{ {
Hacker obj=new Hacker(); Hacker obj=new Hacker(arg , arg);
} }
} }

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
139
139
Default Constructor
✓ A constructor is called "Default Constructor"
when it doesn't have any parameter.
Example 1:
class Code
{
Code()
{
System.out.println(“Done my code");
}
public static void main(String args[]){
Code c=new Code(); //calling a default constructor
}
}

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
140
140
Thank You

MLR INSTITUTE OF TECHNOLOGY


31-Oct-23
141
141

You might also like