0% found this document useful (0 votes)
70 views169 pages

Unit I

The document provides an overview of object-oriented programming paradigms and Java basics. It discusses imperative and declarative programming paradigms, and covers procedural, object-oriented, and parallel processing approaches. It also defines key object-oriented programming concepts like encapsulation, inheritance, and polymorphism. Additionally, it provides a brief history of the Java programming language, noting it was conceived in 1991 and originally called "Oak" before being renamed to Java in 1995.

Uploaded by

sindhura reddy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
70 views169 pages

Unit I

The document provides an overview of object-oriented programming paradigms and Java basics. It discusses imperative and declarative programming paradigms, and covers procedural, object-oriented, and parallel processing approaches. It also defines key object-oriented programming concepts like encapsulation, inheritance, and polymorphism. Additionally, it provides a brief history of the Java programming language, noting it was conceived in 1991 and originally called "Oak" before being renamed to Java in 1995.

Uploaded by

sindhura reddy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 169

UNIT-I 1

Unit I
Object Oriented
Thinking
&
Java Basics
UNIT-I 2
Programming Paradigms
• Paradigm can also be termed as method to solve some problem or
do some task.
• Programming paradigm is an approach to solve problem using
some programming language or it is a method to solve a problem
using tools and techniques that are available to us following some
approach.

3
Programming Paradigms
Imperative programming paradigm:
•Imperative (how to do) and declarative (what to do) programming
paradigms.
•It is one of the oldest programming paradigm. It features close relation to
machine architecture. Examples: C , Fortan
Imperative programming is divided into three broad categories.

These paradigms are as follows:


1. Procedural programming paradigm –
This paradigm emphasizes on procedure in terms of under lying machine
model.
Examples : C
2. Object oriented programming –
The program is written as a collection of classes and object which are
meant for communication. Examples: Simula : first OOP language,
Java , C++, Visual Basic .NET , Python, Ruby
3. Parallel processing approach –
Parallel processing is the processing of program instructions by dividing
them among multiple processors.
Examples: NESL (one of the oldest one) and C/C++ also supports
because of some library function.
4
Programming Paradigms
Declarative programming paradigm:
•It is divided as Logic, Functional, Database.

1. Logic programming paradigms –


•It can be termed as abstract model of computation. It would solve logical
problems like puzzles, series etc.
•The execution of the program is very much like proof of mathematical
statement.

2. Functional programming paradigms –


The functional programming paradigms has its roots in mathematics, and it is
language independent.
Examples : JavaScript , Haskwell , Lisp

3. Database/Data driven programming approach –


This programming methodology is based on data and its movement.
Example: SQL

5
Programming Paradigms
Object-Oriented Programming paradigm
•Object-oriented programming (OOP) is a programming paradigm
based upon objects (having both data and methods) that aims to
incorporate the advantages of modularity and reusability.

The important features of object–oriented programming are −


• Bottom–up approach in program design
• Programs organized around objects, grouped in classes
• Focus on data with methods to operate upon object’s data
• Interaction between objects through functions
• Reusability of design through creation of new classes by
adding features to existing classes

Some examples of object-oriented programming languages are C+


+, Java, Smalltalk, Delphi, C#, Perl, Python, Ruby, and PHP.

6
Programming Paradigms

Procedural Oriented Programming Object Oriented Programming

In procedural programming, program is divided into small In object-oriented programming, program is divided into
parts called functions. small parts called objects.

Procedural programming follows top-down approach. Object oriented programming follows bottom-up approach.

Object oriented programming have access specifiers like


There is no access specifier in procedural programming.
private, public, protected etc.

Adding new data and function is not easy. Adding new data and function is easy.

Procedural programming does not have any proper way for Object oriented programming provides data hiding so it is
hiding data, so it is less secure. more secure.

In procedural programming, overloading is not possible. Overloading is possible in object-oriented programming.

In procedural programming, function is more important than In object-oriented programming, data is more important
data. than function.

Procedural programming is based on unreal world. Object oriented programming is based on real world.

7
Examples: C, FORTRAN, Pascal, Basic etc. Examples: C++, Java, Python, C# etc.
A Way of Viewing The World

The community of agents helping to delivery flowers


A Way of Viewing The World
Agents and Communities

1st Principle of object-oriented problem solving

An object-oriented program is structured as a community of


interacting agents, called objects.

Each object has a role to play.

Each object provides a service, or performs an action, that


is used by other members of the community.

9
A Way of Viewing The World
Messages and Methods

2nd Principle of object-oriented problem solving

Action is initiated in object-oriented programming by the


transmission of a message to an agent (an object)
responsible for the action.

The message encodes the request for an action and is


accompanied by any additional information (arguments)
needed to carry out the request.

The receiver is the object to whom the message is sent.


If the receiver accepts the message, it accepts the
responsibility to carry out the indicated action.
In response to a message, the receiver will perform some
method to satisfy the request.
10
A Way of Viewing The World
Classes and Instances
Although I dealt with Flora a few times, I have a rough idea of the
transaction that will occur inside Flora’s flower shop.
I can make certain assumptions based on previous experience
with other florists, and hence I can expect that Flora, being an
instance of this category, will fit the general pattern.

The term Florist is used to represent the category (or class) of all
florists.
3rd principle of object-oriented programming:
All objects are instances of a class.

The method invoked by an object in response to a message is


determined by the class of the receiver.
All objects of a given class use the same method in response
to similar messages.
11
A Way of Viewing The World
Class Hierarchies-Inheritance

The categories surrounding Flora


A Way of Viewing The World
Class Hierarchies-Inheritance

A class hierarchy for various material objects


A Way of Viewing The World
Summary of Object-Oriented Concepts

1. Everything is an object.
2. Computation is performed by objects communicating with each other,
requesting that other objects perform actions. Objects communicate by
sending and receiving messages. A message is a request for action
bundled with whatever arguments may be necessary to complete the task.
3. Each object has its own memory, which consists of other objects.
4. Every object is an instance of a class. A class simply represents a
grouping of similar objects, such as integers or lists.
5. The class is the repository for behavior associated with an object.
That is, all objects that are instances of the same class can perform the
same actions.
6. Classes are organized into a singly rooted tree structure, called the
inheritance hierarchy. Memory and behavior associated with instances
of a class are automatically available to any class associated with a
descendant in this tree structure.
OOP Principles
Objects and Classes

Encapsulation:

Inheritance:

Polymorphism:

Message Communication
UNIT-I 15
OOP Principles
Encapsulation: Encapsulation is the mechanism that binds
together code and the data it manipulates.
In Java, the basis of encapsulation is the class.
A class defines the structure and behavior that
Inheritance: will be shared by a set of objects.

Polymorphism:

The data defined by the class are referred to as


member variables or instance variables.
The code that operates on that data is referred
to as member
UNIT-I
methods or just methods. 16
OOP Principles
Encapsulation:

Inheritance: Inheritance is the process by which one object


acquires the properties of another object.

Polymorphism:

UNIT-I 17
OOP Principles
Encapsulation:

Inheritance:

Polymorphism: Polymorphism is a feature that allows one interface


to be used for a general class of actions.
The specific action is determined by the exact nature
of the situation.

UNIT-I 18
Java’s History
• Java was conceived by James Gosling at Sun Microsystems
in 1991.
• It took 18 months to develop the first working version.
• This language was initially called “Oak”, but was renamed
“Java” in 1995.
• Java is the name of the island in Indonesia.
• The Java coffee is from the Java island.
• The name was chosen during one of several brainstorming
sessions held by the Java software team.
• "Java" was chosen from among many, many suggestions.
• The name is not an acronym, but rather a reminder of that
hot, aromatic stuff that many programmers like to drink lots of

UNIT-I 19
JDK Versions
• JDK Alpha and Beta (1995)
• JDK 1.0 (23rd Jan 1996)
• JDK 1.1 (19th Feb 1997)
• J2SE 1.2 (8th Dec 1998)
• J2SE 1.3 (8th May 2000)
• J2SE 1.4 (6th Feb 2002)
• J2SE 5.0 (30th Sep 2004)
• Java SE 6 (11th Dec 2006)
• Java SE 7 (28th July 2011)
• Java SE 8 (18th Mar 2014)
• Java SE 9 (21st Sep 2017)
• Java SE 10 (20th Mar 2018)
• Java SE 11-19 (25th September 2018- 20th September 2022
• Java SE 20 (March 2023)
• Java SE 21 (September 2023)
UNIT-I 20
JDK Editions
• Java Standard Edition (J2SE)
– J2SE can be used to develop client-side standalone
applications or applets.
• Java Enterprise Edition (J2EE)
– J2EE can be used to develop server-side applications
such as Java servlets and Java ServerPages.
• Java Micro Edition (J2ME).
– J2ME can be used to develop applications for mobile
devices such as cell phones.

UNIT-I 21
UNIT-I 22
Characteristics of Java
• Java Is Simple
• Java Is Object-Oriented
• Java Is Distributed
• Java Is Interpreted
• Java Is Robust
• Java Is Secure
• Java Is Architecture-Neutral
• Java Is Portable
• Java's Performance
• Java Is Multithreaded
• Java Is Dynamic
UNIT-I 23
Characteristics of Java
• Java Is Simple Because Java inherits the
• Java Is Object-Oriented C/C++ syntax and many of
• Java Is Distributed the object-oriented features
of C++, learning Java will be
• Java Is Interpreted easier.
• Java Is Robust
• Java Is Secure
• Java Is Architecture-Neutral
• Java Is Portable
• Java's Performance
• Java Is Multithreaded
• Java Is Dynamic
UNIT-I 24
Characteristics of Java
• Java Is Simple Java is inherently object-oriented.
• Java Is Object-Oriented Although many object-oriented languages
began strictly as procedural languages,
• Java Is Distributed Java was designed from the start to be
• Java Is Interpreted object-oriented. Object-oriented
programming (OOP) is a popular
• Java Is Robust programming approach that is replacing
traditional procedural programming
• Java Is Secure techniques.
• Java Is Architecture-Neutral
One of the central issues in software
• Java Is Portable development is how to reuse code. Object-
• Java's Performance oriented programming provides great
flexibility, modularity, clarity, and
• Java Is Multithreaded reusability through encapsulation,
• Java Is Dynamic inheritance, and polymorphism.

UNIT-I 25
Characteristics of Java
• Java Is Simple
• Java Is Object-Oriented Distributed computing involves
several computers working
• Java Is Distributed together on a network. Java is
• Java Is Interpreted designed to make distributed
computing easy.
• Java Is Robust Java also supports Remote
Method Invocation(RMI)
• Java Is Secure
• Java Is Architecture-Neutral
• Java Is Portable
• Java's Performance
• Java Is Multithreaded
• Java Is Dynamic
UNIT-I 26
Characteristics of Java
• Java Is Simple Java enables the creation of cross-
platform programs by compiling into
• Java Is Object-Oriented an intermediate representation called
• Java Is Distributed Java bytecode. This code can be
executed on any system that
• Java Is Interpreted implements the Java Virtual Machine
• Java Is Robust
• Java Is Secure
• Java Is Architecture-Neutral
• Java Is Portable
• Java's Performance
• Java Is Multithreaded
• Java Is Dynamic
UNIT-I 27
Characteristics of Java
• Java Is Simple
• Java Is Object-Oriented
Java compilers can detect many
• Java Is Distributed problems that would first show up at
• Java Is Interpreted execution time in other languages.

• Java Is Robust Java has eliminated certain types of


error-prone programming constructs
• Java Is Secure found in other languages.
• Java Is Architecture-Neutral
Java has a runtime exception-handling
• Java Is Portable feature to provide programming
• Java's Performance support for robustness.
• Java Is Multithreaded
• Java Is Dynamic
UNIT-I 28
Characteristics of Java
• Java Is Simple By using a Java-compatible web
browser, we can safely download Java
• Java Is Object-Oriented applets without fear of viral infection or
• Java Is Distributed malicious intent.

• Java Is Interpreted Java achieves this protection by


confining a Java program to the Java
• Java Is Robust execution environment and not
• Java Is Secure allowing it access to other parts of the
computer.
• Java Is Architecture-Neutral
• Java Is Portable
• Java's Performance
• Java Is Multithreaded
• Java Is Dynamic
UNIT-I 29
Characteristics of Java
• Java Is Simple
• Java Is Object-Oriented
• Java Is Distributed
Write once, run anywhere
• Java Is Interpreted With a Java Virtual Machine (JVM),
• Java Is Robust you can write one program that will run
on any platform.
• Java Is Secure
• Java Is Architecture-Neutral
• Java Is Portable
• Java's Performance
• Java Is Multithreaded
• Java Is Dynamic
UNIT-I 30
Characteristics of Java
• Java Is Simple
• Java Is Object-Oriented
• Java Is Distributed
Because Java is architecture neutral, Java
• Java Is Interpreted programs are portable.
• Java Is Robust They can be run on any platform without
being recompiled.
• Java Is Secure
• Java Is Architecture-Neutral
• Java Is Portable
• Java's Performance
• Java Is Multithreaded
• Java Is Dynamic
UNIT-I 31
Characteristics of Java
• Java Is Simple
• Java Is Object-Oriented
• Java Is Distributed The Just-in-time compilers allow the
• Java Is Interpreted platform-independent Java programs to
be executed with nearly the same run-
• Java Is Robust time performance as conventional
• Java Is Secure compiled programs

• Java Is Architecture-Neutral
• Java Is Portable
• Java's Performance
• Java Is Multithreaded
• Java Is Dynamic
UNIT-I 32
Characteristics of Java
• Java Is Simple
• Java Is Object-Oriented
Multithread programming is smoothly
• Java Is Distributed integrated in Java, which allows you to write
• Java Is Interpreted programs that do many things
simultaneously. Whereas in other languages
• Java Is Robust you have to call procedures specific to the
• operating system to enable multithreading.
Java Is Secure
• Java Is Architecture-Neutral
• Java Is Portable
• Java's Performance
• Java Is Multithreaded
• Java Is Dynamic
UNIT-I 33
Characteristics of Java
• Java Is Simple
• Java Is Object-Oriented
• Java Is Distributed Java programs carry with them substantial
amounts of run-time type information that is
• Java Is Interpreted used to verify and resolve accesses to
• Java Is Robust objects at run time. This makes it possible
to dynamically link code in a safe and
• Java Is Secure expedient manner.
• Java Is Architecture-Neutral
• Java Is Portable
• Java's Performance
• Java Is Multithreaded
• Java Is Dynamic
UNIT-I 34
First Java Program

35
JVM(Java Virtual Machine)

36
37
Compiling Java Source Code
• Java was designed to run object programs on any
platform.
• With Java, you write the program once, and compile the
source program into a special type of object code, known as
bytecode.
• The bytecode can then run on any computer with a Java
Virtual Machine.
• Java Virtual Machine is a software that interprets Java
bytecode.

Java Bytecode

Java Virtual
Machine

Any
Computer

38
Java Translation and Execution
Java source code

Java compiler

Java bytecode

Java interpreter Java interpreter Java interpreter Java interpreter


for Windows for Mac for Razr v2 for Linux

39

39
Java is Compiled and Interpreted

Hardware and
Programmer
Operating System

Source Code Byte


Code
Text Editor Compiler Interpreter
.java file .class
file java
Notepad, java
editplus, c appletviewer
Edit etc netscape

40
41
42
Java Installation

43
Java Installation

44
Java Installation

45
Setting Path for Java

46
Setting Path for Java

47
Setting Path for Java

48
Setting Path for Java

49
Setting Path for Java

50
Setting Path for Java

51
Check in Command Prompt

52
Check in Command Prompt

53
Check in Command Prompt

54
First Java Program

55
First Java Program

public class Hello {


......
}

The basic unit of a Java program is a class.

A class called "Hello" is defined via the keyword "class".

The braces {......} encloses the body of the class.

In Java, the name of the source file must be the same as the
name of the class with a mandatory file extension of ".java".

Hence, this file MUST be saved as "Hello.java" - case-sensitive.


56
First Java Program

main() method, is the entry point for program execution.

Again, the braces {......} encloses the body of the method,


which contains programming statements.
57
First Java Program

Method in Java

58
59
Program Execution

60
61
62
63
//Example for printf

public class Hello


{
public static void main(String[] args)
{
int a=10;
float b=123.543f;
System.out.printf("%d",a);
System.out.printf("\n%3.2f",b);
System.out.printf("\n%3.5f",b);
}
}

64
//Example

public class Hello


{
public static void main(String[] args)
{
float pi=3.14f;
System.out.println("PI Value " + pi);
System.out.print("PI Value " + pi);
}
}

65
Naming Conventions
• Variables and method names:
– Use lowercase. If the name consists of several words,
concatenate all in one, use lowercase for the first word,
and capitalize the first letter of each subsequent word in
the name.
For example:- radius, area, computeArea.
• Class names:
– Capitalize the first letter of each word in the name.
Example:- FirstProgram, Sample, DemoBoxWeight.
• Constants:
– Capitalize all letters in constants, and use underscores
to connect words.
Example:- PI, MAX_VALUE.
UNIT-I 66
Identifiers
• An identifier is a sequence of characters that consist of
uppercase and lowercase letters, digits, underscores ( _ ),
and dollar signs ($).
• An identifier must start with a letter, an underscore (_), or a
dollar sign ($). It cannot start with a digit.
• An identifier cannot be a reserved word.
• An identifier cannot be true, false, or null.
• An identifier can be of any length.

UNIT-I 67
Comments

Three types of comments

• Single-line //
• Multi-line /* */
• Documentation comment /** */
This type of comment is used to produce an HTML file that
documents your program.

UNIT-I 68
Separators
( ) Method definition and invocation, defining precedence in

expressions, in control statements and type casting.


{} Initializing arrays, define blocks of code for classes,

methods and local scopes.


[] Declare array types, dereference array types.
; Terminates statements.
, In variable declaration, in for statement.
. To separate package names from sub packages and
classes and to separate a variable or method from a
UNIT-I 69
Keywords
Keywords are reserved words recognized by Java that
cannot be used as identifiers.
Java defines 50 keywords as follows:

enum

UNIT-I 70
Data Types
Java defines eight primitive data types:
byte, short, int, long, char, float, double and boolean.
These are put into four groups:
→ Integers
→ Floating-point numbers
→ Characters
→ Boolean

UNIT-I 71
Data Types

72
Integers:

Name Width Range

long 64 -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

int 32 -2,147,483,648 to 2,147,483,647

short 16 -32,768 to 32,767

byte 8 -128 to 127

UNIT-I 73
Floating-Point Types:

Name Width Range

double 64 4.9e-324 to 1.8e+308

float 32 1.4e-045 to 3.4e+038

UNIT-I 74
Characters:
► In Java, the data type used to store characters is char.
► Java uses Unicode to represent characters.
► Unicode defines a fully international character set that can
represent all the characters found in all human languages.
Such as Latin, Greek, Arabic, Cyrillic, Hebrew, Katakana,
Hangul and many more.
► For this purpose char is 16 bits width.
► The range of char is 65,536.
► The standard set of characters known as ASCII in Unicode
ranges from 0 to 255.
UNIT-I 75
Booleans:
► Java has a primitive type called boolean for logical values.
► It can have only one of two possible values, true or false.
► It requires one bit.
► When a boolean value is output by println( ), “true” or “false
is displayed.
► If b is boolean variable, then there is no need to write an if
statement like this:
if(b==true) …
► The outcome of a relational operator is boolean value.

UNIT-I 76
Literals
Integer Literals:
► Integer literals can be represented using any of the three
bases decimal, octal and hexadecimal.
► Any whole number is a decimal(base 10) number.
► Octal(base 8) values are denoted in Java by a leading zero.
Ex: 05, 012,0734
► Hexadecimal(base 16) values are denoted in Java by a
leading zero-x(0x or 0X). The range of hexadecimal digits is 0

to 9 and A to F (a to f) for 10 to 15.


Ex: 0x12, 0X45, 0X1B UNIT-I 77
Integer Literals:

► Integer literals create an int value which is a 32-bit integer


value and can be assigned even to byte and short if it is
in the range.

► Integerliterals can also be used for long, however we can


specify long literals explicitly by appending an upper or
lower case L to integer literal.

Ex: 1234L,0x52dfL

UNIT-I 78
Floating-Point Literals:

► Floating-point numbers represent decimal values with a


fractional component. They can be expressed in either
standard or scientific notation.
Standard notation: 2.34, 3.14159
Scientific notation: 6.022E23, 314159e-5

► Floating-point literals in Java default to double precision.


► To specify a float literal, append an F or f to the constant.
Ex:- 24.89f, 10076.45F
► double literal can also be specified explicitly by appending a
D or d.
Ex:- 24.89, 24.89d, 12.0056D

UNIT-I 79
Boolean Literals:

► There are only two logical values that boolean can have, true

and false.
► The true literal in Java does not equal 1 nor does the false
literal equal 0.

UNIT-I 80
Character Literals:
A character literal is represented inside a pair of single
quotes.
All the visible ASCII characters can be directly entered
inside the quotes, such as ‘a’, ‘z’, ‘@’.
For characters that are impossible to enter directly, there are
several escape sequences to enter the character.

UNIT-I 81
82
Character Escape Sequence

Escape Sequence Description


\ddd Octal character (ddd)
\uxxxx Hexadecimal Unicode character(xxxx)
\’ Single quote
\” Double quote
\\ Blackslash
\r Carriage return
\n New line
\f Form feed
\t Tab
\b Backspace
UNIT-I 83
Variables
Declaring a Variable:
In Java, all variables must be declared before they can be used.

type identifier [ =value][, identifier [=value] …];

UNIT-I 84
The Scope and Lifetime of Variables
►A scope determines what objects are visible to other parts of
your program.
► It also determines the lifetime of those objects.
► In Java, the two major scopes are those defined by a class
and those defined by a method.

UNIT-I 85
UNIT-I 86
Type Conversion and Casting
Java supports both automatic type conversion and casting.

Java’s Automatic Conversions:


When one type of data is assigned to another type of variable,
an automatic type conversion will take place if the following two
conditions are met:
• The two types are compatible.
• The destination type is larger than the source type.
When these two conditions are met, a widening conversion
takes place.
Ex:- int to long, byte to int, float to double …

UNIT-I 87
//Example
class Hello
{
public static void main(String[] args)
{
int i = 100;
// automatic type conversion
long l = i;
// automatic type conversion
float f = l;
System.out.println("Int value "+i);
System.out.println("Long value "+l);
System.out.println("Float value "+f);
}
}

88
Casting Incompatible Types:
To create a conversion between two incompatible types, use
a cast. A cast is an explicit type conversion. The general
form is:
(target-type) value
This type of conversion is sometimes called a narrowing
conversion.
A different type of conversion will occur when a floating-point
value is assigned to an integer type: truncation.
Ex:- int i=257; b=(byte)i;
byte b;
double d=456.132; i=(int)d;

UNIT-I 89
Automatic Type Promotion in Expressions:
Java automatically promotes each byte or short operand to int
when evaluating an expression.
Ex:- byte a=5, b=10;
a=a*b; //error
int c=a*b;
a=(byte)(a*b);
In addition to the above, Java automatic type promotion rules
are:
1. If one of the operands is double, the whole expression is
promoted to double.
2. Otherwise, if one of the operands is float, the whole
expression is promoted to float.
3. Otherwise, if one of the operands is long, the whole
expression is promoted to long.
UNIT-I 90
//Java program to illustrate
explicit //type conversion
class Hello
//Java program to illustrate {
//incompatible data type for public static void main(String[] a)
explicit //type conversion {
class Hello double d = 100.04;
{ //explicit type casting
public static void main(String[] args) long l = (long)d;
{ //explicit type casting
double d = 100.04; int i = (int)l;
long l = d; System.out.println("Double value
int i = l; "+d);
} System.out.println("Long value
} "+l);
System.out.println("Int value "+i);
}
}

91
Operators

Arithmetic Operators

Bitwise Operators

Relational Operators

Boolean Logical Operators

UNIT-I 92
Arithmetic Operators:
The operands of the arithmetic operators must be of a numeric
type. These can also be used on char types.
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
++ Increment
-- Decrement
+= Addition assignment
-= Subtraction assignment
*= Multiplication assignment
/= Division assignment
%= Modulus assignment
UNIT-I 93
Bitwise Operators:
Java defines several bitwise operators which can be applied to the types,
long, int, short, char and byte. These operators act upon the individual bits
of their operands. Operator Description
~ Bitwise unary NOT
& Bitwise AND
| Bitwise OR
^ Bitwise exclisive OR
>> Shift right
>>> Shift right zero fill
<< Shift left
&= Bitwise AND assignment
|= Bitwise OR assignment
^= Bitwise exclisive OR assignment
>>= Shift right assignment
>>>= Shift right zero fill assignment
<<= Shift left assignment
UNIT-I 94
Relational Operators:
The relational operators determine the relationship that one operand
has to the other. The outcome of these operations is a boolean value.

Operator Description
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to

UNIT-I 95
Boolean Logical Operators:
These operators operate only on boolean operands and result
a boolean value.
Operator Description
& Logical AND
| Logical OR
^ Logical XOR
|| Short-circuit OR
&& Short-circuit AND
! Logical unary NOT
&= AND assignment
|= OR assignment
^= XOR assignment
== Equal to
!= Not equal to
?: Ternary if-then-else
UNIT-I 96
Operator Precedence:

() [] .
High
++ -- ~ !
* / %
+ -
>> >>> <<
> >= < <=
== !=
&
^
|
&&
||
Low ?:
= Op=
UNIT-I 97
UNIT-I 98
Control Statements
Java’s control statements are put into three categories:
• Selection statements: if and switch.
• Iteration statements: for, while and do-while.
• Jump statements: break, continue and return.

UNIT-I 99
Selection statements

if
if-else
Nested ifs
The if-else-if ladder
switch
Nested switch Statements.

UNIT-I 100
Selection statements:
if The if-else-if ladder
Syntax Syntax:
if (condition) {
// block of code to be executed if if(condition1){
the condition is true }
//code to be executed if condition1 is
if-else
true
Syntax }else if(condition2){
if (condition) {
// block of code to be executed if //code to be executed if condition2 is
the condition is true } true
else {
}
// block of code to be executed if
the condition is false } else if(condition3){

Nested ifs //code to be executed if condition3 is


Syntax: true
if(condition){ } ... else{
//code to be executed
if(condition){ //code to be executed if all the
//code to be executed conditions are false
} } 101
}
Selection statements:
Switch Nested switch Statements
Syntax:
Syntax switch(n)
{
switch(expression) { // code to be executed if n = 1;
case 1:
case x:
// Nested switch
// code block switch(num)
{ // code to be executed if num = 10
break; case 10:
statement 1;
case y: break;
------------
// code block default:
} break;
break;
// code to be executed if n = 2;
default: case 2:
statement 2;
// code block break;
// code to be executed if n doesn't match any
} cases
default: }
102
Example of Nested switch
public class Hello {
public static void main(String[] args) {
int day = 1, d=8;
switch (day) {
case 1:
switch(d)
{
case 8:
System.out.println("Monday");
break;
}
break;
case 6:
System.out.println("Saturday");
break;
default:
System.out.println("Holiday");
break;
} } }
103
Iteration statements
while
do-while
for
In J2SE 5 a new version of for loop known as for-each loop
was introduced.
Its general form is:
for( type itr-var : collection) statement-block

Collection is of any type of collection or array.

int nums[ ]={10,20,30,40,50};


int sum=0;
for(int x : nums) sum+=x;

UNIT-I 104
Iteration statements:
While
Syntax
while (condition) {
// code block to be for
executed Syntax
for (statement 1; statement 2; statement 3)
} {
do-while // code block to be executed
}
Syntax
Example
do {
for (int i = 0; i < 5; i++) {
// code block to be System.out.println(i);
executed }
}
while (condition);
105
Iteration statements:
For-Each Loop
"for-each" loop, is used exclusively to loop through elements in an array:

Syntax
for (type variableName : arrayName) {
// code block to be executed
}

Example
public class Hello {
public static void main(String[] args) {
String[] branch = {"CSE", "ECE", "EEE", "IT"};
for (String i : branch) {
System.out.println(i);
}
}
}

106
Jump Statements
break:
In java, the break statement has three uses,
• In a switch statement.
• To exit a loop.
• Can be used as a form of goto.
The general form of the third type of break is:
break label;
Label is the name of a label that identifies a block of code.
When this form of break executes control is transferred out of
the named block of code.
Java label is a valid identifier followed by a colon.
UNIT-I 107
Jump Statements
Example

public class Hello {


public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
if (i == 4) {
break;
}
System.out.println(i);
}
}
}

108
Jump Statements

continue:
Used in loops.
Also used with label.
The general form of continue with label is:
continue label;
return:
The return statement is used to explicitly return from a
method.

UNIT-I 109
continue

Example

public class Hello {


public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
if (i == 4) {
continue;
}
System.out.println(i);
}
}
}

110
UNIT-I 111
Arrays
An array is a group of like-typed variables that are referred to
by a common name.

One-Dimensional Arrays

Multidimensional Arrays

UNIT-I 112
One-Dimensional Arrays:
The general form of a one-dimensional array declaration is:
type array-var[ ];
type[ ] array-var;
To allocate memory to an array new operator is used.
array-var=new type[size];

Ex:- int nums[ ]; int[ ] vals;


nums= new int[10]; vals=new int[20];

Array initializer will not use new operator.


Ex:- int days[ ]={ 1,2,3,4,5,6,7 };

UNIT-I 113
Multidimensional Arrays:
Multidimensional arrays are arrays of arrays.
Ex:- int twoDim1[ ][ ]=new int[4][5];

int twoDim2[ ][ ]=new int[4][ ];


twoDim2[0]=new int[1];
twoDim2[1]=new int[2];
twoDim2[2]=new int[3];
twoDim2[3]=new int[4];

UNIT-I 114
115
Example of Java Array

class Hello{
public static void main(String args[]){

int a[]=new int[3]; //declaration and instantiation

a[0]=10; //initialization
a[1]=20;
a[2]=30;

//traversing array

for(int i=0;i<a.length;i++) //length is the property of array


System.out.println(a[i]);
}}

116
UNIT-I 117
Class Fundamentals
• A class defines a new data type.

• Once defined can be used to create objects of that type.

• A class is a template for an object.

• An object is an instance of a class.

UNIT-I 118
The general form of a class definition is:
class classname {
type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;
type methodname1(parameter-list){
// body of method
}
type methodname2(parameter-list){
// body of method
}
// . . .
type methodnameM(parameter-list){
// body of method
}
} UNIT-I 119
Class Fundamentals
• The data (or) variables defined within a class are called instance

variables because each instance (object) of the class contains its

own copy of these variables.

• The code is contained within methods.


• Collectively, the methods and variables defined within a class are

called members of the class.

UNIT-I 120
Declaring Objects:
The object is defined in two-steps:
1. Declare a variable of the class type.
classname class-var;
2. Acquire an actual, physical copy of the object and assign it to that
variable using a new operator.
class-var=new classname( );

Ex:- Box mybox; null


class Box
mybox
{
double width;
double height; mybox=new Box( ); width
double depth;
} height
mybox
depth
UNIT-I 121
Assigning Object Reference Variables:
Box b1=new Box();
Box b2;
b2=b1;
After these above statements b1 b2 refer to the same object.
In the first statement object b1 is created and memory is allocated to it.
After the 3rd statement b2 refers to the same object as b1 refer to.
Any changes made to object through b2 will affect to b1.

width
b1
height Box object
depth
null
b2
UNIT-I 122
The Scope and Lifetime of Variables

There are three kinds of variables in Java −

•Local variables
•Instance variables
•Class/Static variables
Local Variables

•A variable defined within a block or method, or constructor is called


local variable.

•These variable are created when the block in entered, or the function
is called and destroyed after exiting from the block or when the call
returns from the function.

•The scope of these variables exists only within the block in which the
variable is declared. i.e., we can access these variable only within that
block.

•Initialization of Local Variable is Mandatory.


//Example //Example
public class Hello { public class Hello {
public void aValue() public void aValue()
{ {
// local variable a // local variable a
int a = 0; int a = 0;
a = a + 10; a = a + 10;
System.out.println("a = " + a);
} }

public static void main(String args[]) public static void main(String args[])
{ {
Hello obj = new Hello(); System.out.println("a = " + a);
obj.aValue(); }
} }
}
Instance Variables

•Instance variables are non-static variables and are declared in a


class outside any method, constructor or block.

•As instance variables are declared in a class, these variables are


created when an object of the class is created and destroyed when
the object is destroyed.

•Unlike local variables, we may use access specifiers for instance


variables. If we do not specify any access specifier, then the default
access specifier will be used.

•Initialization of Instance Variable is not Mandatory. Its default value


is 0

•Instance Variable can be accessed only by creating objects.


//Example
class Marks {
// These variables are instance variables.
// These variables are in a class
// and are not inside any function
int engMarks;
}
class Hello {
public static void main(String args[])
{
Marks obj1 = new Marks();
obj1.engMarks = 50;

// displaying marks
System.out.println("Marks :");
System.out.println(obj1.engMarks);
}
}
Static Variables:

•Static variables are also known as Class variables.


•These variables are declared similarly as instance variables, the
difference is that static variables are declared using the static keyword
within a class outside any method constructor or block.
•Unlike instance variables, we can only have one copy of a static
variable per class irrespective of how many objects we create.
•Static variables are created at the start of program execution and
destroyed automatically when execution ends.
•Initialization of Static Variable is not Mandatory. Its default value is 0
•If we access the static variable like Instance variable (through an
object), the compiler will show the warning message and it won’t halt
the program. The compiler will replace the object name to class name
automatically.
•If we access the static variable without the class name, Compiler will
automatically append the class name.
Static variables are accessed as

class_name.variable_name;
//Example

class Emp {
// static variable name
public static String name = "Java";
}
public class Hello {
public static void main(String args[])
{
// accessing static variable without object
System.out.println(Emp.name + " is based on OOPS
Concepts");
}
}
UNIT-I 132
Constructors:
• A constructor initializes an object immediately upon creation.
• It has the same name as the class in which it resides.
• Similar to a method but does not have a return type.
• Automatically called immediately after the object creation, before new
operator completes.
• The constructor’s job is to initialize the internal state of an object.
• Constructors can be with no parameters (default) as well as with
parameters.

Ex:-
Box( ) { Box(double w, double h, double d) Box b1=new Box( );
width=10; {
height=20; width=w;
depth=30; height=h; Box b2=new Box(40,50,60);
} depth=d;
} UNIT-I 133
UNIT-I 134
Methods:
The general form of a method:
type name(parameter-list){
// body of method
}

Overloading Methods:
• In a class, if two or more methods are defined with the same name and
different parameter declarations, then the methods are said to be overloaded
and the process is referred to as method overloading.
• Method overloading is one of the ways that Java supports polymorphism.
• Variable-Length Arguments

UNIT-I 135
Variable-Length Arguments(Varargs):

A method that takes a variable number of arguments is called a variable-arity


method (or) a varargs method.

A variable length argument is specified by three periods (…).


Ex:- void add(int … v)

A method can have normal parameters along with a variable-length parameter.


The variable-length parameter must be the last parameter declared by the
method.
Ex:- void display(int a, int … p)
void test(boolean a, boolean b, double c, char … d)

There must be only one variable-length parameter

UNIT-I 136
Overloading Varargs Methods:

Varargs methods can be overloaded in two ways:

1) The types of vararg parameter can differ.

2) To add a normal parameter.

UNIT-I 137
Varargs and Ambiguity:
void display(int ... a) void display(int a, int ... v)
{ {
System.out.print("Parameters:"); System.out.print("Parameters:"+a);
for(int x:a) for(int x:v)
System.out.print(" "+x); System.out.print(" "+x);
System.out.println(); System.out.println();
} }
void display(char ... ch) void display(int ... w)
{ {
System.out.print("Parameters:"); System.out.print("Parameters2:");
for(char x:ch) for(int x:w)
System.out.print(" "+x); System.out.print(" "+x);
System.out.println(); System.out.println();
} }

s1.display( ); s1.display(10);

UNIT-I 138
This Keyword:
‘this’ keyword can be used inside any method to refer to the current object.
class Rect { class Rect { class Rect {
int length,breadth; int length,breadth; int length,breadth;
void init(int a, int b){ void init(int length, void init(int length,
length=a; int breadth){
int breadth){
breadth=b; this.length=length;
length=length;
} this.breadth=breadth;
breadth=breadth;
} }
}
}
}

Rect r1=new Rect( ); Rect r1=new Rect( );


Rect r1=new Rect( );
r1.init(10,20); r1.init(10,20);
r1.init(10,20);UNIT-I 139
static keyword:
Normally, a class member must be accessed only with an object of its class.

It is possible to create a member that can be accessed before any objects of


its class are created and without reference to an object.

To create such a member, precede its declaration with the keyword static.

Such members can be accessed with the class name by the dot operator.
class Sample {
static int a=10; int c=Sample.a+Sample.b;
static int b; Sample.methodOne(5,6);
static void methodOne(int p, int q) {
System.out.println(“p=“+p+”q=“+q);
}
} UNIT-I 140
static variables:

Instance variables declared as static are essentially global variables.

When objects of a class are declared, no copy of a static variable is made.

All instances of the class share the same static variable.

To initialize static variables, declare a static block which get executed exactly
once, when the class is first loaded.

UNIT-I 141
static methods:

Methods declared as static have several restrictions:

• They can only call other static methods.

• They must only access static data.

• They cannot refer to this and super in any way.

UNIT-I 142
final keyword:
final can be applied for variables, methods and classes.

final variable contents cannot be modified.

final variable must be initialized when it is declared.

Variables declared as final do not occupy memory on a per-instance basis.


A final variable is a constant.

Ex:- final int FILE_NEW=1;


final int FILE_OPEN=2;

UNIT-I 143
UNIT-I 144
Garbage Collection:
In java, objects are dynamically allocated by using the new operator.
Such objects are automatically destroyed, and their memory is released when
no references to the objects exists.
The technique that accomplishes this is called garbage collection.
Sometimes an object will need to perform some action when it is destroyed.
Java provides a mechanism called finalization using which we can define
specific actions that will occur when an object is just about to be reclaimed
by the garbage collector.
To add a finalizer to a class, simply define the finalize() method, which the
Java runtime calls this method whenever it is about to recycle an object.
protected void finalize( ) {
// finalization code
}
UNIT-I 145
UNIT-I 146
Nested and Inner Classes:
A class can be defined within another classes. Such classes are known as
nested classes.
The scope of a nested class is bounded by the scope of its enclosing class.
A nested class has access to the members, including private members, of
the class in which it is nested.
The enclosing class does not have access to the members of the nested class.

class A {
// members
class B {
//class B members
}
// members
}
UNIT-I 147
Nested and Inner Classes:

There are two types of nested classes:


► static nested classes
► non-static nested classes.

UNIT-I 148
static Nested Classes:
A static nested class is one which has the static modifier applied.
It must access the members of its enclosing class through an object.

class A {
// members
static class B {
//class B members
}
// members
}

UNIT-I 149
Non-static Nested Classes:
A non-static nested class is also known as inner class.
It has access to all the variables and methods of its outer class.

class A {
// members
class B {
//class B members
}
// members
}

UNIT-I 150
UNIT-I 151
Strings in Java:
A string is a sequence of characters.

Java implements strings as objects of type String class.

When a String object is created, a string is created that cannot be changed.

We can still perform all types of string operations, but each time an existing
string is altered a new String object is created that contains the modifications.

Java provide two classes to create modifiable strings.


They are StringBuffer and StringBuilder.

The classes String, StringBuffer and StringBuilder are defined in java.lang


package. All are final.

UNIT-I 152
Constructors of String class:
String( )
String(char chars[ ])
String(char chars[ ], int startIndex, int numChars)
String(String strObj)
String(byte asciiChars[ ])
String(byte asciiChars[ ],int startIndex,int numChars)
String(StringBuffer strBufObj)
String(int codePoints[ ],int startIndex, int numChars) Added in J2SE 5
String(StringBuilder strBuildObj) Added in J2SE 5

UNIT-I 153
String Literals:

String s = ”abcdefghij”;

String Length:

int length( )

UNIT-I 154
String Concatenation:
The + operator concatenates two strings, producing a String object as the result.

Example1:
String age = “9”;
String s = “He is “ + age + “ years old. “;
System.out.println( s );
The O/P here is “He is 9 years old.”

Example2:
int age = 9;
String s = “He is “ + age + “ years old. “;
System.out.println( s );

The O/P here is also “He is 9 years old.”

UNIT-I 155
String Concatenation:
Example3:
String s = “abcdefghij “ + 20 + 30;
System.out.println( s );
The O/P here is “abcdefghij 2030”

This is because the compiler automatically converts an operand to its string


equivalent whenever the other operand of the + operator is an instance of
String.

Example4:
String s = “abcdefghij “ + (20 + 30);
System.out.println( s );
The O/P here is “abcdefghij 50”

UNIT-I 156
String Conversion and toString( ):
Java converts data into its string representation during concatenation by
calling one of the overloaded versions of the string conversion method
valueOf( ) defined by String class.
valueOf( ) is overloaded for all simple types and for type Object.
static String valueOf(int num)

static String valueOf(byte num)

static String valueOf(double num)

static String valueOf(long num)

static String valueOf(char chars[ ])

static String valueOf(Object ob)

static String valueOf(char chars[ ],int startIndex, int numChars)


UNIT-I 157
String Conversion and toString( ):
For objects, valueOf( ) calls the toString( ) method on the object.

Every class implements toString( ) because it is defined by Object.

The default implementation of toString( ) is sufficient.

We can override toString( ) and provide our own string representations for
objects.

The syntax is:


String toString( )

UNIT-I 158
Example:
class String1
class Rect{ {
int length,breadth; public static void main(String args[])
Rect(int x,int y) { {
length=x; Rect r1=new Rect(10,20);
breadth=y; String s1=“Rect:”+r1;
} System.out.println(s1);
} Cube b1=new Cube(10,20,30);
class Cube { String s2=“Cube:”+b1;
int length,width,height; System.out.println(s2);
Cube(int x,int y,int z) { }
length=x; }
width=y; O/P :
height=z; Rect:Rect@82ba41
} Cube:Hai I am instance of Cube class
public String toString( ) {
return "Hai I am instance of Cube class";
}
}
UNIT-I 159
Character Extraction:

String object cannot be indexed as if they were a character array.


Many of the String methods employ an index into the string for their operation
beginning at zero.

char charAt(int where)


void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart)
byte[ ] getBytes( )
char[ ] toCharArray( )

UNIT-I 160
String Comparision:

boolean equals(String str)


boolean equalsIgnoreCase(String str)

boolean regionMatches(int startIndex,String str2, int str2StartIndex,


int numChars)
boolean regionMatches(boolean ignoreCase, int startIndex,String str2,
int str2StartIndex, int numChars)
boolean startsWith(String str)
boolean endsWith(String str)
int compareTo(String str) <0 if invoking string<str
>0 if invoking string>str
0 if two strings are equal

UNIT-I 161
Searching Strings:
int indexOf(int ch) for first occurrence
int lastIndexOf(int ch) for last occurrence
int indexOf(String str)
int lastIndexOf(String str)
int indexOf(int ch, int startIndex)
int lastIndexOf(int ch, int startIndex)
int indexOf(String str, int startIndex)
int lastIndexOf(String str, int startIndex)

startIndex specifies the index at which point the search begins.

UNIT-I 162
Modifying a String:
String substring(int startIndex)
String substring(int startIndex, int endIndex)

String concat(String str)


String replace(char original, char replacement)
String replace(CharSequence original, CharSequence replacement)
Added in J2SE 5

String trim( )

UNIT-I 163
Changing the Case of Characters within a String:

String toLowerCase( )

String toUpperCase( )

Joining Strings:

static String join(CharSequence delim, CharSequence …. strs)

UNIT-I 164
Some other String Methods:
int codePointAt(int i) Added by J2SE 5
int codePointBefore(int i) “
int codePointCount(int start,int end) “
boolean contains(CharSequence str) “
boolean contentEquals(CharSequence str) “
boolean contentEquals(StringBuffer str)
static String format(String fmtstr,Object … args) “
static String format(Locale loc, String fmtstr, Object … args) “
boolean matches(String regExp)
int offsetByCodePoints(int start, int num) “
String replaceFirst(String regExp,String newStr)
String replaceAll(String regExp,String newStr)
String[ ] split(String regExp)
String[ ] split(String regExp, int max)
CharSequence subSequence(int startIndex, int stopIndex)
UNIT-I 165
UNIT-I 166
StringBuffer Constructors:

StringBuffer( ) 16 characters
StringBuffer(int size)
StringBuffer(String str) str+16 characters
StringBuffer(CharSequence chars)

UNIT-I 167
Methods:
int length( ) string length
int capacity( ) total allocated capacity
void ensureCapacity(int capacity) preallocate
void setLength(int len)
char charAt(int where)
void setChatAt(int where, char ch)
void getChars(int sourceStart,int sourceEnd,char target[ ],int
targetStart)

Ensures that the capacity of the buffer is at least equal to the


specified minimum.
The new capacity is the larger of:
a. The minimumCapacity argument.
b. Twice the old capacity, plus 2.

UNIT-I 168
Methods:
StringBuffer append(String str)
StringBuffer append(int num)
StringBuffer append(Object obj)

StringBuffer insert(int index, String str)


StringBuffer insert(int index, char ch)
StringBuffer insert(int index, Object obj)

StringBuffer reverse( )

StringBuffer delete(int startIndex, int endIndex)


StringBuffer deleteCharAt(int loc)

StringBuffer replace(int startIndex,int endIndex,String str)

String substring(int startIndex)


String substring(int startIndex, int endIndex)
UNIT-I 169

You might also like