Uni1 PPT-1

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 123

OBJECT ORIENTED

PROGRAMMING THROUGH
JAVA
Course Outcomes
Understand the syntax and semantics of
JAVA programming language to solve a
given problem.
Apply the knowledge of Object Oriented
Programming principles to develop
applications.
Apply the concepts of packages, I/O and
Exception handling mechanisms to develop
efficient programming.
Analyze the concepts of Multithreading and
Collection Framework to develop
applications which mimic the real-world
scenarios.
UNIT1
 Object Oriented Programming: Basic concepts, Principles,
 Program Structure in JAVA: Introduction, Writing Simple JAVA Programs,
Elements or Tokens in JAVA Programs, JAVA Statements, Command Line
Arguments, User Input to Programs, Escape Sequences, Comments,
Programming Style.
 Data Types, Variables, and Operators :Introduction, Declaration of
Variables, Data Types, Type Casting, Scope of Variable, Identifier, Literal
Constants, Symbolic Constants, Formatted Output with printf() Method,
Static Variables and Methods, Attribute Final,
 Introduction to Operators, Precedence and Associativity of
Operators, Assignment Operator ( = ), Basic Arithmetic Operators,
Increment (++) and Decrement (- -) Operators, Ternary Operator,
Relational Operators, Boolean Logical Operators, Bitwise Logical
Operators.
 Control Statements :Introduction, if Expression, Nested if
Expressions, if–else Expressions, Ternary Operator?:, Switch Statement,
Iteration Statements, while Expression, do–while Loop, for Loop, Nested
for Loop, For–Each for Loop, Break Statement, Continue Statement.
UNIT 2
 Classes and Objects: Introduction, Class Declaration
and Modifiers, Class Members, Declaration of Class
Objects, Assigning One Object to Another.
 Constructor and Methods: Introduction, Defining
Methods, Overloaded Methods, Constructors,
Overloaded Constructor Methods , Class Objects as
Parameters in Methods, Access Control, Accessing
Private Members of Class, Recursive Methods, final
method, Passing Arguments by Value and by Reference,
Keyword this, final and static, Nested classes.
 String Handling in JAVA: Introduction, Interface Char
Sequence, Class String, Methods for Extracting
Characters from Strings, Comparison, Modifying,
Searching; Class StringBuffer.
UNIT 3
 Arrays: Introduction, Declaration and Initialization of Arrays,
Storage of Array in Computer Memory, Accessing Elements of
Arrays, Operations on Array Elements, Assigning Array to
Another Array, Dynamic Change of Array Size, Sorting of Arrays,
Search for Values in Arrays, Class Arrays, Two-dimensional
Arrays, Arrays of Varying Lengths, Three-dimensional Arrays,
Arrays as Vectors.
 Inheritance: Introduction, Process of Inheritance, Types of
Inheritances, Universal Super Class-Object Class, Inhibiting
Inheritance of Class Using Final, Access Control and Inheritance,
Multilevel Inheritance, Application of Keyword Super, Constructor
Method and Inheritance, Method Overriding, Dynamic Method
Dispatch, Abstract Classes.
 Interfaces: Introduction, Declaration of Interface,
Implementation of Interface, Multiple Interfaces, Nested
Interfaces, Inheritance of Interfaces, Default Methods in
Interfaces, Static Methods in Interface.
UNIT 4
 Packages and JAVA Library: Introduction, Defining
Package, Importing Packages and Classes into Programs,
Path and Class Path, Access Control, Packages in JAVA
SE, java.lang Package and its Classes, Class Object, class
Math, Wrapper Classes, Auto-boxing and Auto-unboxing.
 Exception Handling: Introduction, Hierarchy of
Standard Exception Classes, Keywords throws and throw,
try, catch, and finally Blocks, Multiple Catch Clauses,
Class Throwable, Unchecked Exceptions, Checked
Exceptions, custom exceptions.
 Java I/O and File: Java I/O API, standard I/O streams,
types, Byte streams, Character streams, Scanner class,
Files in Java: File, FileInputStream and FileOutputStream
Classes(Text Book 2)
UNIT 5
Multithreaded Programming:
Introduction, Need for Multiple Threads
Multithreaded Programming for Multi-core
Processor, Thread Class, Main Thread-
Creation of New Threads, Thread States,
Thread Priority
Collections Framework : Introduction,
Purpose of Collection Framework,
Application of Collection Framework,
Hierarchy of collection Interfaces / classes,
Methods defined in Collection Interface,
Interface Iterator, Collection
classes/Interfaces –List,Queue,Set,
Text Books
 JAVA one step ahead, Anitha Seth,
B.L.Juneja, Oxford.
Joy with JAVA, Fundamentals of Object
Oriented Programming, Debasis Samanta,
Monalisa Sarma, Cambridge, 2023.
History
 1990 – Sun Microsystems – Stealth Project -
Green Project.
 1991 – James Gosling, Patric Naughton, Mike
Sheradin, Bill joy
 James Gosling – Development of programming
language – C/C++ - platform independent.
 Initial name is Oak – Later named as Java.
 In 1994 – Patric Naughton - WebRunner- a Java
based Web Browser – Applets - HotJava.
 In 1995, Sun Microsystems formally announced
Java and HotJava .

9
Processor Developers
 Intel
 AMD
 Qualcomm
 NVIDIA
 IBM
 Samsung
 Motorola
 Hewlett-Packard (hp)
 Dell
 Acer
 VIA
 Marvell
 Global Foundries
 Media Tek
 Atmel
 Freescale
 MSNCC-Microcell
 Transmeta
 Cyrix
 Rockchip

10
History of Java
 JDK Alpha and Beta (1995)
Why Java populated
 JDK 1.0 (23rd Jan, 1996)
Portability
 JDK 1.1 (19th Feb, 1997) Security
 J2SE 1.2 (8th Dec, 1998) Applets
 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 March, 2014) - 217 Packages and 4240 Classes.
 Java SE 9 (September 2017)
 Java SE 10 (March 2018)
 Java SE 11 (September 2018)
 Java SE 12 (March 2019)
 Java SE 13 (September 2019)

 And so on at present JAVA SE 22 (March 19, 2024)

11
About Java
J2SE – Java 2 Platform, Standard edition -
for development and deployment
of portable applications.
J2EE -Java 2 Platform, Enterprise edition -
web based enterprise applications
J2ME - Java 2 Platform, Micro edition - Java
applications for mobile technology.

12
J2SE
As per SE22
Total Java Classes Total Classes 5,900
o 4240 in java 8 Total Packages 235
o 4024 in java 7
o 3793 in java 6
o 3279 in java 5.0
Total Java Packages
o 217

13
Java’s Magic : Bytecode

Byte code: optimized set of


instructions

JIT (Just in Time Compiler)

14
Java Features

15
Java Features
 Simple
 It is free from pointer due to this execution time of application
is improve.
 It have rich set of APIs (application programming interface).
 It have Garbage Collector which is always used to collect un-
referenced (unused) memory locations for improving performance
of a Java program.
 It contains user friendly syntax for developing any applications
 Object Oriented
 Java supports OOP features and everything is an Object in Java.
The object model in Java is simple and easy to extend.
 Robust
 Java is robust or strong programming language because of its
capability to handle run-time errors, such as exception handling.

16
Java Features
 Multi Threading:
 Java was designed to meet the real-world requirement of creating interactive,
networked programs.
 To accomplish this, Java supports multithreaded programming, which allows

you to write programs that do any things simultaneously .

 Architecture-Neutral:

 Architecture represents processor. A language or technology is said to be


architectural neutral which can run on any processors in the real world
without considering type of architecture and vendor (providers).

17
Java Features
 Interpreted:
High Performance:
 The problem with interpreter inside JVM is that it is slow. Because
of this, Java programs used to run slow. To overcome this, along
with interpreter, Java people have introduced JIT (Just-in-Time)
compiler, which enhances the speed of execution.
 Distributed: Java is designed for the distributed environment
of the Internet because it handles TCP/IP protocols. Java
also supports Remote Method Invocation (RMI). This
feature enables a program to invoke methods across a network
 Dynamic: Java support dynamic memory allocation. Due to
this memory wastage is reduced. This is done with the help of
new operator.

18
Java Features
 Secure:
 It is more secured language compare to other languages;
In this, program is covered into byte code after
compilation which is not readable by human
 Restricted to access other areas in the system
 Portable:
 If any language supports platform independent and
architectural neutral features, then that language is
portable.
Portable = Platform independent + Architecture-neutral

19
Procedural/Structured Programming
Huge programs are divided into smaller
programs as functions. These functions can
call one another.
No importance is given to security of data
and importance is laid on doing things.
Data passes globally from function to
function
Most functions access global data
Follows top-to-bottom approach

20 Suresh Yadlapati
Procedural/Structured Programming

21 Suresh Yadlapati
Object Oriented
Programming
 OOP has more importance to data rather than
doing things
 Programs are divided into classes .
 OOP allows bottom-up approach
 New data items and member functions can be
comfortably added whenever essential.
 Data is private and prevented from external
functions
 Objects can communicate with each other
through methods

22 Suresh Yadlapati
Object Oriented
Programming

23 Suresh Yadlapati
Need of OOP
• Though procedural-oriented programs are
extremely powerful, they have some of the
following limitations:
 It is difficult to add any new functionality or to upgrade a
program.
 Functions have unrestricted access to global data.
 Importance is given to the operation on data rather than the
data itself.
Need of OOP
• An object-oriented approach to the application
development enables us to design programs.
OOP has more importance to data rather than
doing things
Programs are divided into classes - Modularity .
OOP allows bottom-up approach
New data items and member functions can be
comfortably added whenever essential
Data is private and prevented from external
functions
Objects can communicate with each other
through member functions
Advantages of OOP
• Modular structure - provides a clear and modular
structure for program development.
• Easy to maintain and upgrade- Object-oriented
systems can be easily upgraded.
• Inheritance - Allows us to eliminate redundant code
and use existing classes.
• Reusability - functions and modules can be reused by
other users without any modification.
• Data hiding -The programmer can hide the data and
functions in a class from other classes.
Reusability
- functions Easy to Data
and maintain hiding -The
modules and programmer
can be upgrade- can hide the
reused by Object- data and
other users oriented functions in
without any systems can a class from
modification be easily other
. upgraded. classes.

Modular Inheritanc
structure - e - Allows us
provides a to eliminate
clear and redundant
modular code and
structure for use existing
program classes.
developmen
t.
Characteristics of Object-Oriented
Programming
Class
Object
Data Abstraction
Encapsulation and Data hiding
Inheritance
Polymorphism
Class
Object Properties Methods
car.name = car.start(
Verna )
car.model = car.drive(
2017 )
car.weight = car.brake
1250kg ()
• In object-oriented
programming, a class
car.color is a
= white car.stop()
basic building block.
• 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
Object
It is a basic unit of OOP and represents the
real-world entities.
 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(name),
state/properties, and behavior.
Each object contains data and code to
manipulate the data.
Data Abstraction

Data abstraction refers to providing only


essential information about the data to the
outside world, hiding the background
details or implementation.
Encapsulation and Data
hiding
• It is a mechanism of wrapping the data and methods
into a single unit called class.
• The data of a class may be hidden so that it cannot be
accessed by the outside code.
• Classes have the provision to hide the data or methods from
the user.
• A class member may be declared as public, protected or
private.
• A member declared as private cannot be accessed by any code
outside the class.
• Only class members can access a private member.
• The one declared protected can be accessed by the class
members as well as members of the subclass derived from the
class.
• A member declared public can be accessed by any outside code.
• Whereas the one declared without any access specifier is
accessible to classes of the same package only.
Access Specifiers
Public
Private
Protected Applied to variables,
Default constructors, methods,
and classes.
Inheritance
• A class can inherit another class;
• Acquiring the properties/methods from one class to
another class
 Allows reusability
Polymorphism
It is the concept by which a method or object takes
different forms in different. environments.
E.g., the operator + adds two whole numbers, two decimal
point numbers, strings.
⁻ Symbol * (star) shows polymorphic behavior.
⁻ It is used to multiply two values, incorporate comments such
as /* and */, import a package into a program like import
java.lang.*;.
Reuse, Coupling, and Coheshion in OOP

Cohesion refers to the degree to which the elements


inside a module belong together.
In one sense, it is a measure of the strength of relationship
between the methods and data of a class


Coupling is the degree of inter-dependence between the
pairs of modules.
- It is a measure of the strength of association established
by a connection from one entity to another.

Reusability is the ability to reuse the previously defined


objects and classes.
Differences between C and JAVA
Parameter C JAVA

Language Level Middle-level language High-level language


Programming
Structural, procedural Object-oriented
Paradigm
Approach Top-down Bottom-up
Compiled and
Compilation Compiled language
Interpreted language
Platform-independent
Platform
Platform dependent (uses Java Virtual
Dependency
Machine)
Memory Manual (functions like Automatic (garbage
Management malloc, calloc, free) collection)
Threading Does not support threading Supports multi-threading
Does not support
Pointers Supports pointers
pointers
Inheritance Does not support inheritance Supports inheritance
No built-in exception Supports exception
Error Handling
handling handling
File Extensions .c .java
More secure (due to lack of
Security Less secure
pointers, etc.)
More robust (strong
Robustness Less robust
memory management)
Supports Applet concept is not there Applets are there
System applications, Enterprise applications,
Applications
embedded systems web applications
Popularity Less popular compared to Java More Popular
Object-Oriented
Lacks OOP concepts like Fully supports OOP
Programming
polymorphism, encapsulation concepts
(OOP) Features
Diff between C++ and JAVA
Comparison Index C++ Java

Platform-independent C++ is platform-dependent. Java is platform-independent.

Mainly used for C++ is mainly used for system Java is mainly used for application
programming. programming. It is widely used in
Windows-based, web-based, enterprise,
and mobile applications.

Goto C++ supports the goto statement. Java doesn't support the goto statement.
Multiple inheritance C++ supports multiple Java doesn't support multiple
inheritance. inheritance through class. It can be
achieved by using interfaces in java.

Operator Overloading C++ supports Java doesn't support operator


operator overloading. overloading.
Object-oriented Partially Fully
Pointers C++ supports pointers. You Java supports pointer internally.
can write a pointer program in However, you can't write the
C++. pointer program in java. It
means java has restricted pointer
support in java.
Compiler and C++ uses compiler only. C++ Java uses both compiler and
Interpreter is compiled and run using the interpreter.
compiler which converts
source code into machine code
so, C++ is platform dependent.
Call by Value and C++ supports both call by Java supports call by value only.
Call by reference value and call by reference. There is no call by reference in
java.
Structure and Union C++ supports structures and Java doesn't support structures
unions. and unions.
Thread Support C++ doesn't have built-in Java has built-in thread support.
support for threads. It relies on
third-party libraries for thread
support.
Tokens in Java Programs
 A Token is a individual/smallest unit of a
program element which is recognized by the
compiler.
 A program contains set of tokens such as
Identifiers or names This is meant for variables,
methods, classes, etc.
Keywords These are special words defined in Java and
represent a set of instructions.
Literals These are values represented by a set of
characters, digits, etc.
Separators These include comma, semicolon, period
(.), (), [], etc.
Operators - Operators are mostly represented by
symbols such as + , −,*, etc.
Identifiers or Names
Anything stored in the computer memory
has a name or identifier which identifies that
section of the memory
Rules:
1. It may be a single word or a combination of words
with no space between words.
2. It should not be a keyword of Java.
3. It should not be Boolean literal, that is, true or false.
4. It should not be null literal.
5. It should not start with a digit but it can start with an
underscore.
6. It can comprise one or more unicode characters as
well as digits.
Conventions for Writing
Names
Packages - Names of packages are
completely in lower-case letters such as
mypackage, java.lang.
For Class - Names of classes and interfaces
start with an upper-case letter.
For Methods - Names of methods start with
a lower-case character.
For variables - Names of variables should
start with a lower-case character.
Keywords in Java
The keywords represent groups of
instructions for the compiler.
These are special tokens that have a
predefined meaning and their use is
restricted.
keywords cannot be used as names of
variables, methods, classes, or packages.
These are written in the lower case.
Literals in Java
 A literal is a constant value
 The value may be a number (either whole or
decimal point number) or a sequence of characters
which is called String literal, Boolean type, etc.
Types of Literals:
1. Integer literals - 6, 453, 34789
2. Floating point literal - 3.14159, 567.78
3. Boolean literal - two values—true or false
4. Character literal - Characters are represented in
single quotes such as ‘A’, ‘H’, ‘k’,
5. String literal - “AP”, “Amaravati”, “Vijayawada”,
6. Null literal - null
Separators
Declaration of Variables
Variables are objects which contains some
values, those values may change in the
program.
A variable is declared by first writing its
type, followed by its name or identifier.
Java Statements
A Java program consists of a set of
instructions, these instructions are the
statements in Java.
Empty statement –
An empty statement in Java is written as a
single semicolon.
For example, you can use it to indicate an
empty loop body of a for loop:
for(int i = 0; i < 10; a[i++]++) // Increment
array elements
/* empty */; // Loop body is empty
statement
Variable declaration statements – a variable
 Labelled statements
A labeled statement is simply a statement that has been given a name
by prepending a identifier and a colon to it.
Labels are used by the break and continue statements.
rowLoop: for(int r = 0; r < rows.length; r++)
{
// A labeled loop
colLoop: for(int c = 0; c < columns.length; c++)
{
// Another one break rowLoop;
// Use a label
}
}
 Expression statements:
var=expr; expr++; ++expr; method(); newType(); --expr; expr- -;
 Control statements
 Selection statements
 Iteration statements
 Jump statements - break, continue, return and throw

 Synchronized statement
 Guarding statement – Exceptions - try, catch block and finally
Command line arguments
A Java application can accept any number
of arguments from the command line.
These arguments can be passed at the
time of running the program.
length property array is used to find
number of arguments
User input to programs
There are various ways to read input from the
keyboard, the java.util.Scanner class is one of
them.
The Java Scanner class breaks the input into
tokens using a delimiter that is whitespace by
default.
It provides many methods to read and parse
various primitive values.
Part of util package.
Programs discussed in text book:
Performing arithmetic operations on two numbers
Finding Area of a circle
Method Description

public String next() it returns the next token from the scanner.

public String nextLine() it reads the given input as one line irrespective
of white space and returns the value as a string.
public byte nextByte() it scans the next token as a byte.

public short nextShort() it scans the next token as a short value.

public int nextInt() it scans the next token as an int value.

public long nextLong() it scans the next token as a long value.

public float nextFloat() it scans the next token as a float value.

public double nextDouble() it scans the next token as a double value.

Suresh Yadlapati
Escape sequences
These characters consists of a backslash
followed by a letter such as “\t”, “\n” and so
on and have special meaning to the
compiler.
These are used in formatting.
\u0041 (hexadecimal)- A
\ddd (Octal) - \132 - Z
scape Characters Description
\t It is used to insert a tab in the text at this point.

\' It is used to insert a single quote character in the text at


this point.
\" It is used to insert a double quote character in the text
at this point.
\r It is used to insert a carriage return in the text at this
point.
\\ It is used to insert a backslash character in the text at
this point.
\n It is used to insert a new line in the text at this point.

\f It is used to insert a form feed in the text at this point.

\b It is used to insert a backspace in the text. It is


used to move the cursor one position
back in a string. - Output depends on compiler
UNICODE Escape Characters
Char Unicode Escape Description
Sequence
& U+0026 \u0026 Ampersand
• U+2022 \u2022 Bullet
U+25E6 \u25E6 White Bullet
∙ U+2219 \u2219 Bullet
Operator
‣ U+2023 \u2023 Triangular
Bullet
⁃ U+2043 \u2043 Hyphen
Bullet
° U+00B0 \u00B0 Degree
∞ U+221E \u221E Infinity
$ U+0024 \u0024 Dollar
€ U+20AC \u20AC Euro
£ U+00A3 \u00A3 Pound
¥ U+00A5 \u00A5 Yen / Yuan
¢ U+00A2 \u00A2 Cent
₹ U+20B9 \u20B9 Indian Rupee
₨ U+20A8 \u20A8 Rupee
₱ U+20B1 \u20B1 Peso
₩ U+20A9 \u20A9 Korean Won
฿ U+0E3F \u0E3F Thai Baht
₫ U+20AB \u20AB Dong
₪ U+20AA \u20AA Shekel
ellectual Property Codes
© U+00A9 \u00A9 Copyright
® U+00AE \u00AE Registered
Trademark
℗ U+2117 \u2117 Sound
Recording
Copyright
™ U+2122 \u2122 Trademark
℠ U+2120 \u2120 Service
Mark
Comments
 3 types
 Single Line Comment
 The single-line comment is used to comment only one line of the
code.
 // Not executed

 Multiline Comment -/* and */


 Documentation comments are usually used to write
large programs for a project or software application as
it helps to create documentation API. These APIs are
needed for reference, i.e., which classes, methods,
arguments, etc., are used in the code.
To create documentation API, we need to use the javadoc
tool. The documentation comments are placed
between /** and */.

Ref: https://www.javatpoint.com/java-comments
•There is a non-data type called
Data Types in Java void.
• This type is used for methods that
 Java defines eight primitive (basic) types of data do not return any value.
 1. Integral types—byte, short, int, long
 2. Floating point types—float, double
 3. Character type—char
 4. Boolean type—boolean


Declaration of Variables
• A variable is declared by first declaring its type
followed by its identifier or name.
• The name or identifier should not be a keyword of
Java language.
• It can be of any length and may consist of
characters and digits.
Non-primitive Types
These are the class and interface types. The name
of a class or interface is the name of type. A class
object is declared as
Integers
Integers are whole numbers, that is, they
represent numbers that do not have a fractional
part.
 In Java, these numbers may be positive or
negative.
Characters
• A variable may have value in terms of a character.
• These characters represent integer values.
• Java supports Unicode for the representation of characters.
• Unicode supports all the character sets of all the major languages
of the world.
• The initial version of Unicode allocated 2 bytes for storing
characters.
• The range of values for characters in the initial version of Unicode
comprised from ‘\u0000’ to ‘\uffff ’ that is from 0 to 65535 both
end values inclusive.
‘A’ - \u0041 – 65
‘1’ - \u0031 - 49
Floating-point numbers
• The numbers that are not whole numbers, or those that have
fractional part, Examples are 3.141, 476.6, and so on.
• Java supports two types of such numbers.
 Float: This type is used for single-precision decimal floating point
numbers, that is, 7(or 8) digits after the decimal point.
 These numbers are stored on 4 bytes .
 Double This type is used for double-precision decimal floating point
numbers, that is, 15 digits after the decimal point.

The letter f or F is appended to float value


otherwise number will be considered as double
value
boolean Type Data
• For dealing with logical statements, variable of
type boolean is supported.
• The value of boolean type variable is either true
or false.
• The boolean type variables are unsigned as
similar to char type variables.
• The variable may be declared as follows :
boolean a;
a = x > y;
Type Casting
• If an expression has more than one type of a variable, the
different types have to be changed to conform to a single
type.
• The conversion of types of data from one type to another
type is called type casting or type conversion.
• Some type castings are done automatically by a compiler,
while others have to be done by the programmer.
• Automatic type conversion or widening conversion:
 The two types are compatible.
 The destination type is larger than the source type.
byte - > Short - > int-> long float -> double
char-> int
Casting Incompatible Types
To create a conversion between two
incompatible types, you must use a cast.
A cast is simply an explicit type
conversion. It has this general form:
variable=(target-type) value
double->float>int->short>byte
Tasks
Print area of circle and area of rectangle
using double data types.
Scope of variable
 Variable to be declared within any block
 A block is begin with an opening curly brace and ended by a
closing curly brace
 A block defines a scope.
 Thus, each time you start a new block, you are creating a new
scope. A scope determines what objects are visible to other
parts of your program.
 Many other computer languages define two general categories
of scopes: global and local.
 As a general rule, variables declared inside a scope are not
visible (that is, accessible) to code that is defined outside that
scope. Thus, when you declare a variable within a scope, you
are localizing that variable and protecting it from unauthorized
access and/or modification.
 Scopes can be nested. For example, each time you create a
block of code, you are creating a new, nested scope.
Literal Constants
• Each character is a constant value.
• An array of characters or a string also represents
a constant value.
• The digits in decimal system, octal system, or
hexadecimal system represent constant values.
• These are all called literal constants.
• The char literals are enclosed in single quotes (‘
’). The examples ‘A’ and ‘B’.
Symbolic Constants

• A symbolic constant is a variable whose value


does not change throughout the program.
• Some of the examples include PI,
SPEED_OF_LIGHT, GRAVITATIONAL_CONSTANT,
NATURAL_LOG_BASE(2.71)

• Usually programmers represents symbolic


constants as CAPITAL letters
public static final in PI=3.1415;
Types of variables
 Local variables – inside a method or parameters of a
method. Local variables must be initialized before
use, as they don’t have a default value and the compiler
won’t let us use an uninitialized value.
In other words, local variables don’t have
default values.
 Instance variables – Declared anywhere in a class
butouside of the class. Each object has its own copy of
these variables.
Writethe differences
Static variable – declaration of these variables precede
between local, instance
with
and static a keyword
variables in static. Only one copy is maintained.
JAVA.
Static Variable
• The variables in a class may be modified by modifier static.
• The non-static variables declared in a class are instance variables.
• Each object of the class keeps a copy of the values of these
variables.
• The static variables are class variables.
• The static variables are accessed through class reference, whereas
the instance variables are accessed through class object reference.
Attribute Final
• The value of a variable declared final cannot be changed in the program.
• It makes the variable a constant and must be initialized at the time of
declaration.
• A few examples of declarations are as:
final double PI = 3.14159;
final int M = 900;
final double X = 7.5643;
Operators
•Arithmetic operators
•Compound assignment operators
•Increment and decrement operators
•Relational operators
•Boolean logical operators
•Bitwise logical operators
•Shift operators
•Special operators
• If an operator takes only one operand for its operation,
it is called unary operator.
• If it takes two operands, it is called binary operator.
• If it takes three operands, it is called ternary operator.
Precedence and Associativity of Operators
 Precedence and associativity are two features of Java
operators.
 When there are two or more operators in an expression,
the operator with the highest priority will be executed
first.
Ex: 1 + 2 * 5
Precedence specifies – Operator with highest priority level
 What if the precedence of all operators in an expression is
the same?
Ex: 6*4%5 - Precedence is same at same level
Ans: Associativity comes into the existence
 Associativity specifies the order in which operators are
executed, which can be left to right or right to left.
int a = b = c = 8 ; // right to left
BODMAS rule is a rule in mathematics
used to solve the expression involving
more operators.

O – Order of means – powers, Square root,


exponents ….
Precedence Operator Type Associativ
ity
() Parentheses
Left to
1 (Highest) [] Array subscript
Right
· Member selection
++ Unary post-increment Right to
2
-- Unary post-decrement left
++ Unary pre-increment
-- Unary pre-decrement
+ Unary plus
- Unary minus Right to
3
! Unary logical negation left
~ Unary bitwise complement
(type) Unary type cast

* Multiplication
Left to
4 / Division
right
% Modulus
+ Addition Left to
5
- Subtraction right
<< Bitwise left shift
>> Bitwise right shift with sign
Left to
6 >>> extension
right
Bitwise right shift with zero
extension
Precedence Operator Type Associativit
y
< less than
<= less than or equal
> greater than
7 Left to right
>= greater than equal
instanceof Type comparison
(objects only)
== Relational is equal to
8 != Relational is not equal Left to right
to
9 & Bitwise AND Left to right
10 ^ Bitwise exclusive OR Left to right
11 | Bitwise inclusive OR Left to right
12 && Logical AND Left to right
13 || Logical OR Left to right
14 ?: Ternary conditional Right to left
= Assignment
+= Addition assignment
-= Subtraction assignment
15 (lowest) *= Multiplication Right to left
/= assignment
%= Division assignment
Instance of Example –
Modulus assignment
UseofInstanceOf.java
Assignment Operator
• The associativity of = is from right to left.
• On the left of =, we write the name of the
variable to which a value is to be assigned, and
on its right, we write the value to be assigned.
• The name or identifier on the left is also called l-
value and the value on the right of = is called r-
value.
l-value(name of the identifier) = r-
value(identifier or value)
Chain of Assignments:
int a,b,c,d;
A=b=c=d=50;
Basic Arithmetic Operators

Ex:ArithmeticOperators.java
Combinational Assignment Operators
• In a compound assignment operator, the operations by an operator
and assignment are combined in a single operator. As for e.g.
 int n = 8, m = 10;
 n + = m;
Increment (++) and Decrement (−−) Operators

int x=20, y=10,z;


z=++x + y;
z? and x?
z=x++ + y; if x=20, y=10
Ternary Operator
• Ternary operator is also called conditional
operator.
• In Java, there is only one ternary operator
described by token (?:).
• It takes three operands for its operation.
expression1? expression2 : expression3
 If expression1 is true, then expression2 is
executed; otherwise, expression3 is executed.
Relational Operators
Boolean Logical Operators
Bitwise Logical Operators
• These operators are applied to individual bits of numbers.
• The bitwise operators are OR, AND, XOR, and bitwise
compliment/bitwise NOT operator.
Bitwise Logical Operators
 These operators are applied to individual bits of numbers.
 The bitwise logical operators are AND(&), OR(|), XOR(^),
and NOT(~)
Bitwise OR Bitwise AND Bitwise XOR (^) Bitwise COMPLEME
(|) (&) 0110 - 6 NT (~)
0110 - 0110 - 6 0101 - 5 0110 -> 1001
6 0101 -5 ------
0101 - ----- 0011 -3
5 0100 - 4
-----
Shift
0111
operators: << - left shift , >> right
shift
-7
Syntax: variable << or >>
number_of_digits_to_be_shift

Ex: Bitwise_Operators.java
Bitwise Shift Operators
Syntax:
value <operator> <number_of_times>
 The left side of the expression is the integer that is
shifted, and the right side of the expression denotes
the number of times that it has to be shifted.
 Bitwise shift operators are further classified as
bitwise left and bitwise right shift operators.
Formatted output with printf() method
In JAVA, formatting of an output can be done in two
ways:
Formatter Class
printf() method
Formatting means:
Right and left justification
Procession of floating point numbers
Representing integers in octal and hexadecimal form
Representing time and data in different formats
Syntax:
System.out.printf(“Formatting String”, variables
separated with comma);
System.out.printf(“Price :%d”,22,”Rupees”);
Conversion characters for diff. types of
variables:
Type Variable Conversion Formatting String
letter
Integers d “%d”

Integer Octal o “%o”

Integer Hexadecimal X or x “%X” or “%x”

Character C or c “%C” or “%c”

String S or s “%S” or “%s”

Floating point number f “%f”

Floating point number E or e “%E” or “%e”


(Exponential
form)
Space in output “ “ or “\t” Ex:”%d %d %d\t
%d”
Ex: O/p of diff types of variables –
Format_String.java
Formatting output of integer numbers:
Field width – the field width is the integer
number placed between % sign and
conversion character d
Left and right justification
Default is right justification
For left justification put – after % sign and
before conversion character.
Ex: Formatting_Integer.java
Formatting output of Floating point
numbers:
Field width – the field width is the integer
number placed between % sign and
conversion character F or f
Left and right justification
Default is right justification
For left justification put – after % sign and
before conversion character.
Precession – The number of digits after .
Specified by a period (.) followed by a
number after % symbol
Ex: Formatting_Floating.java
Formatting output of Strings

Field width – it is specified by inserting an


integer between % sign and s or S.
Number of character to be displayed:
Specified by a period and number after
field width.
Upper or Lower case – s – lower case, S –
upper case
Ex: Formatting_String.java
Assignment Questions
Interpret the differences between local,
instance and static(class) variables with
suitable examples.
Write a JAVA program to print factorial of a
given number
Conversion of Decimal to Binary
Write a JAVA program to generate int and
double random numbers using random()
method of Math class.
JAVA program to calculate area of a triagle.
Develop a program to generate random of
8 integer numbers and calculate its
average.
Control Statements
 Selection statements: These statements give an option of choosing
different paths of execution of a program depending on the result of a
test condition.
• The expressions in this group are if, if–else, and switch statement.

 Iteration statements: These statements allow repeated evaluation of a


statement or a block of statements if some condition is satisfied.

• This group contains statements : while, do–while, for, and for– each.

 Jump statements: These statements make the program control jump to


another part of a program in the forward or backward directions with
or without a test condition.
• The statements in this group are break, break label, continue, continue label, and return.
if Statement
• The code for if statement is as follows:
if (conditional expression)
statement;
Nested if Expressions
If –else statement
• The code for if –else statement is as:
if (expression)
{
/* statements */
}
else {
/* statements */
}
Working
Else-if ladder - if-else chain
if(condition)
statement;
else if(condition)
statement;
else if(condition)
statement;
.
.
.
else
statement;

The if statements are executed from the top down. As soon as one of
the conditions controlling the if is true, the statement associated
with that if is executed, and the rest of the ladder is bypassed. If none
of the conditions is true, then the final else statement will be executed.
Ternary Operator ?:
• Its code is as follows:
Expression1 ?Expression2 :Expression3
• The first expression is the test condition.
• If it evaluates true, the Expression2 is executed;
otherwise Expession3 is executed
Switch Statement
switch (expression) 1. For versions of Java prior to JDK
{ 7, expression must be of type
byte, short, int, char, or an
case value1:
enumeration.
// statement 2. Beginning with JDK 7,
sequence •The switch expression is
expression
break; can also be once.
evaluated of type String.
case value2: •The value of the expression
// statement
is compared with the values
sequence
break;
of each case.
•If there is a match, the
.
case valueN : associated block of code is
// statement executed.
sequence •The break and default key
break; words are optional
default:
// default statement
Nested Switch Statement
switch(count)
{
case 1:
switch(target) { // nested switch
case 0:
System.out.println("target is zero");
break;
case 1: // no conflicts with outer switch
System.out.println("target is one");
break;
}
break;
case 2:
.
.
.
class WhileSt {
while public static void main(String
args[])
while(condition) {
int n = 10;
{
while(n > 0) {
// body of loop System.out.println("tick "
} + n);
n--;
}
}
}class DoWhileSt
{
do { public static void main(String args[]) {
int n = 10;
// body of loop do {
System.out.println("tick " + n);
}while(condition); n--;
} while(n > 0);
}
}

10
8
while Expression
• The while loop may be coded as:
while (test expression)
statement;
• If the while test expression evaluates true, the statement
following the expression is executed.
do while Loop
• This loop is similar to while loop except for the fact that the test
expression is placed at the end.
• The statement to be executed is placed between do and while
expression.
Code is:

do
Statement;
while (test expression);
do while Loop

© Oxford University Press 2018. All rights reserved.


endless while loop
• The endless while loop may be coded as:
while (true) {
// do something
}
do {
// do something
} while(true);
For loop
• The for loop is the most versatile
loop when the start and end
points of the loop are known.
• It is an entry controlled loop

for(initialization; condition;
incr/decr)
{
//code to be executed
}

11
4
Nested for loop
The for-each loop
 The for-each loop is used to traverse array or collection in java.
It is easier to use than simple for loop because we don't need
to increment value and use subscript notation.
 It works on elements basis not index. It returns element one by
one in the defined variable.
 Syntax: public class ForEachExample
{
for(data_type var:array)
public static void main(String[]
{ args) {
//code to be executed
int arr[]={12,23,44,56,78};
}
for(int i:arr)
{

System.out.println(i);
}
}
}
11
6
Nested for-each for loop
public class NestedForEach
{
public static void main(String[] args)
{
String[][] str = {{"Amaravati","Vij","Gnt"},
{"Hyd","WL","Khammam"}};

for (String[] s : str)


{
for(String c:s)
{
System.out.println(c);
}
}
}
}
Break Statement
• This is used for exiting from a loop and control goes to the
end of the current loop.

Break Statement with Label
 Break with a label statement is similar to goto statement in C++, but
the implementation is different.
Continue statement
The continue statement is used to skip the
current iteration of any loop and bring the
control to the beginning of the iteration
Continue with label
We can use a labelled continue
statement to continue the outermost
loop.
Questions
 Diff between while, do-while and for loops
 Diff between break and continue
 To check the given number is even or odd
 To check the given number is prime or not
 Even numbers – with in a specific range
 Prime numbers with in a specific range
 Printing Fibonacci numbers up to n.
 To check the given number is palindrome or not
 To check whether the given number is Armstrong or
not.(an Armstrong number is a number that equals
the sum of its individual digits, each raised to the
power of the number of digits.)
Lab Program - Binary
serach
1. Start
2. Take input array and Target
3. Initialise start = 0 and end = (array size -1)
4. Intialise mid variable
5. mid = (start+end)/2
6. if array[ mid ] == target then return mid
7. if array[ mid ] < target then start = mid+1
8. if array[ mid ] > target then end = mid-1
9. if start<=end then goto step 5
10. return -1 as Not element found
11. Exit

You might also like