[go: up one dir, main page]

0% found this document useful (0 votes)
7 views127 pages

Unit 1

The document provides an overview of Object-Oriented Programming (OOP) with Java, covering its principles, advantages, and features. It discusses key concepts such as classes, objects, inheritance, encapsulation, and polymorphism, as well as the history and applications of Java. The document emphasizes Java's simplicity, portability, and its role in both standalone and web applications.

Uploaded by

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

Unit 1

The document provides an overview of Object-Oriented Programming (OOP) with Java, covering its principles, advantages, and features. It discusses key concepts such as classes, objects, inheritance, encapsulation, and polymorphism, as well as the history and applications of Java. The document emphasizes Java's simplicity, portability, and its role in both standalone and web applications.

Uploaded by

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

ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY

OBJECT ORIENTED
PROGRAMMING WITH JAVA
By

B SNV Ramana Murthy


Dept of CSE (AI & ML)
Aditya College of Engineering & Technology
Surampalem
Aditya College of Engineering & Technology

UNIT – 1 Syllabus
• UNIT-I: Introduction: 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, Data Types in Java, 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.
JAVA Programming BSNV R Murthy 2
Aditya College of Engineering & Technology

Introduction
• Since the invention of the Computer, many programming approaches have been
tried. Such as modular programming, top-down programming, bottom-up
programming and structured programming.
• A programming language specifies the words and symbols that we can use to
write a program
• A programming language employs a set of rules that dictate how the words and
symbols can be put together to form valid program statements
• The Java programming language was created by Sun Microsystems, Inc.
• It was introduced in 1995 and it's popularity has grown quickly since.

JAVA Programming BSNV R Murthy 3


Aditya College of Engineering & Technology

Introduction
• Like C, C++ etc. Java is another computer language but with a difference.

• Java’s designers have borrowed the best features of many existing language such
as C and C++ and added a few new features to form a simple language.

• One of the important reason for java’s success is the amazing functionality it adds
to the WWW.
• Java has two lives, one as a stand-alone computer language for general purpose
programming and the other as a supporting language for Internet programming.

• The general purpose programs are known as applications and the programs
written for internet are known as applets.

JAVA Programming BSNV R Murthy 4


Aditya College of Engineering & Technology

Introduction
In Java, there are three types of programs as follows:
• Stand- aline application programs : These programs are made and run on users
computers
• Applet programs : These programs are meant to run in a web page on the
Internet.
• Java Servlets : These programs run in computers that provide web services. They
are also often called server isde programs or servlets.

JAVA Programming BSNV R Murthy 5


Aditya College of Engineering & Technology

OOPs Concepts

JAVA Programming BSNV R Murthy 6


Aditya College of Engineering & Technology

Procedural vs OOPs
POP OOPs
 POP stands for Procedure Oriented OOP stands for Object Oriented
Programming Programming
 Problem is divided into small things called Programs are divided into things called as
as functions objects
 Emphasis is on functions i.e., doing things Emphasis is on data rather than procedures
 Approach : Top down Approach : Bottom up
 Debugging is very difficult Debugging is very easy
No such features are supported Abstraction, Inheritance, Encapsulation &
polymorphism are its key features
Examples: C, Basic, FORTRAN etc.. Examples: Java, C++, VB.NET, C# etc..
Security: Less secure Security: More
JAVA Programming BSNV R Murthy 7
Aditya College of Engineering & Technology

Advantages of OOPs
• Easy to understand
• Code reuse
• Improved software-development productivity ( Faster in time and Lower in
cost of development )
• Improved software maintainability.
• Encapsulation
• Data security
• Addresses real world problems
• Polymorphism
• Extensibility
JAVA Programming BSNV R Murthy 8
Aditya College of Engineering & Technology

Applications of OOPs
• Real-time systems
• Simulation and modeling
• Object-oriented databases
• Hypertext, hypermedia and Expert Text
• AI and expert systems
• Neural networks and parallel programming
• Decision support systems
• CAD/CAM/CIM systems.

JAVA Programming BSNV R Murthy 9


Aditya College of Engineering & Technology

Principles of Object Oriented Languages


OOPs languages have principles map very closely to the real world.
• Objects
• Classes
• Abstraction
• Inheritance
• Encapsulation
• Polymorphism
• Dynamic binding
• Message passing

JAVA Programming BSNV R Murthy 10


Aditya College of Engineering & Technology

Object
• An object is a basic unit of Object-Oriented Programming that
represents real-life entities.
• Every object has an identity, attributes, behavior and state.
• Examples: car, pen, table, apple, rose, student, account, keyboard,
chair etc..
• Similar objects are grouped and categorized.
• Each object has responsibility to react for a particular type of
functionality.
JAVA Programming BSNV R Murthy 11
Aditya College of Engineering & Technology

Class
• A class is a user-defined blueprint or prototype from which objects
are created.
• It represents the set of properties or methods that are common to all
objects of one type.
• Using classes, you can create multiple objects with the same behavior
instead of writing their code multiple times.
• This includes classes for objects occurring more than once in your
code.

JAVA Programming BSNV R Murthy 12


Aditya College of Engineering & Technology

Class
Examples
Class: Fruit ; Object: Apple, Banana,
Mango

Class: Flower; Object: Rose, Lilly, Jasmine


etc..

The class defines the nature and methods


common to the objects which are similar.

JAVA Programming BSNV R Murthy 13


Aditya College of Engineering & Technology

Object Class
Class is a blueprint or template from
Object is an instance of a class.
which objects are created.
Object is a real world entity such as
pen, laptop, mobile, bed, keyboard, Class is a group of similar objects.
mouse, chair etc.
Object is a physical entity. Class is a logical entity.
Object allocates memory when it is Class doesn't allocated memory when
created. it is created
Object is created through new
Class is declared using class keyword
keyword

JAVA Programming BSNV R Murthy 14


Aditya College of Engineering & Technology

Class Syntax
Class has attributes i.e., variables and methods which are operations
performed on attributes.

Syntax: class class_name


{
variable declarations;
method definitions;
}
JAVA Programming BSNV R Murthy 15
Aditya College of Engineering & Technology

Classes & Objects in JAVA

JAVA Programming BSNV R Murthy 16


Aditya College of Engineering & Technology

Class & Objects in JAVA

JAVA Programming BSNV R Murthy 17


Aditya College of Engineering & Technology

Abstraction
• Data Abstraction is the property by virtue of which only the essential
details are displayed to the user. The trivial or non-essential units are
not displayed to the user.
• Data Abstraction may also be defined as the process of identifying
only the required characteristics of an object, ignoring the irrelevant
details.
• The properties and behaviors of an object differentiate it from other
objects of similar type and also help in classifying/grouping the
object.

JAVA Programming BSNV R Murthy 18


Aditya College of Engineering & Technology

Abstraction
Ex: A car is viewed as a car rather than its
individual components.
• When you drive your car you do not have to be
concerned with the exact internal working of your
car.
• What you are concerned with is interacting with
your car via its interfaces like steering wheel, brake
pedal, accelerator pedal etc.

JAVA Programming BSNV R Murthy 19


Aditya College of Engineering & Technology

Encapsulation
• Technically, in encapsulation, the variables or the data in a class is
hidden from any other class and can be accessed only through any
member function of the class in which they are declared.
• In encapsulation, the data in a class is hidden from other classes,
which is similar to what data-hiding does. So, the terms
“encapsulation” and “data-hiding” are used interchangeably.

JAVA Programming BSNV R Murthy 20


Aditya College of Engineering & Technology

Encapsulation
• Encapsulation is a concept that binds together the data of an object,
and functions that manipulate the data in to a single unit or single
component.
• Encapsulation provides more security to the data with data hiding,
from outside interference and misuse.

• Encapsulation can be achieved by declaring all the variables in a class


as private and writing public methods in the class to set and get the
values of the variables.

JAVA Programming BSNV R Murthy 21


Aditya College of Engineering & Technology

Abstraction & Encapsulation

JAVA Programming BSNV R Murthy 22


Aditya College of Engineering & Technology

Encapsulation

JAVA Programming BSNV R Murthy 23


Aditya College of Engineering & Technology

Encapsulation

JAVA Programming BSNV R Murthy 24


Aditya College of Engineering & Technology

Inheritance
• Inheritance is an important pillar of OOP (Object Oriented
Programming).
• Most important aspect of oops is code reusability.
• Inheritance is the process of forming a new class from an existing
class.
The existing class called as base class, new class is
formed called as derived class.

We are achieving inheritance by using extends keyword.


Inheritance is also known as “is-a” relationship.
JAVA Programming BSNV R Murthy 25
Aditya College of Engineering & Technology

Inheritance

JAVA Programming BSNV R Murthy 26


Aditya College of Engineering & Technology

Inheritance

JAVA Programming BSNV R Murthy 27


Aditya College of Engineering & Technology

Polymorphism
• The ability to use an operator or function in different ways is called
polymorphism
• Poly refers to many.
• A single function or an operator, functioning in many ways different
upon the usage is called polymorphism.
• Ex:
Method Overloading
Method Overriding
Operator Overloading

JAVA Programming BSNV R Murthy 28


Aditya College of Engineering & Technology

Polymorphism

JAVA Programming BSNV R Murthy 29


Aditya College of Engineering & Technology

Polymorphism

JAVA Programming BSNV R Murthy 30


Aditya College of Engineering & Technology

Dynamic method binding


• Binding is what happens when a method invocation is bound to an
implementation.

• Binding can happen at two different times


Compile time - static binding ( or ) Early binding
Run time - dynamic binding ( or ) Late binding

• Dynamic binding is also known as late binding.

• The implementation code of a method is not known till it is get executed.


• Java always supports to dynamic binding by default.

JAVA Programming BSNV R Murthy 31


Aditya College of Engineering & Technology

Static binding vs Dynamic binding


Static binding Dynamic binding
Binding which can be resolved at When compiler not able to resolve the
compile time by compiler. binding at compile time.
Also called early binding. Also called late binding.
Binding happens before a program Binding happens during run time.
actually runs.
Ex. Method Overloading Ex. Method Overriding

JAVA Programming BSNV R Murthy 32


Aditya College of Engineering & Technology

Dynamic binding

JAVA Programming BSNV R Murthy 33


Aditya College of Engineering & Technology

Message Passing
• Message passing is the vital activity for executing an object oriented program.

• Action is initiated in OOP by the transmission of a message to an agent (an


object) responsible for the action.

JAVA Programming BSNV R Murthy 34


Aditya College of Engineering & Technology

Message Passing

JAVA Programming BSNV R Murthy 35


Aditya College of Engineering & Technology

Introduction to JAVA
• Java is a general-purpose object oriented programming language.

• Java is a high-level programming language developed by Sun


Microsystems.

• It is intended to let application developers "write once, run


anywhere" (WORA).

JAVA Programming BSNV R Murthy 36


Aditya College of Engineering & Technology

History of JAVA
• In 1990, James Gosling and his team was given the task of creating
programs to control consumer electronics.
• They used C++ as its model, stripping away all the difficult features of
C++, and named "Oak ".
• "By the time Sun Micro systems discovered that the name "Oak" was
already claimed and they changed the name to " Java" .

JAVA Programming BSNV R Murthy 37


Aditya College of Engineering & Technology

Applications of JAVA
• Mobile applications (specially Android apps)
• Desktop applications
• Web applications
• Web servers and application servers
• Games
• Scientific applications
• Database connections
• Enterprise applications

JAVA Programming BSNV R Murthy 38


Aditya College of Engineering & Technology

Features of JAVA (or) Buzzwords


 Java is Simple to learn
 Java is Object Oriented
 Java is Distributed
 Java is Robust - (Strong )
 Java is Secured
 Java is Architecture Neutral
 Java is Portable
 Java is Interpreted
 Java is High Performance
 Java is Multithreaded
 Java is Dynamic

JAVA Programming BSNV R Murthy 39


Aditya College of Engineering & Technology

Features of JAVA (or) Buzzwords


 Java is Simple to learn
• Syntax is simple and easy to learn

• Java is resemblance with C & C++

• No pointers

• No operator overloading

• No multiple inheritance

• Automatic Garbage Collection

JAVA Programming BSNV R Murthy 40


Aditya College of Engineering & Technology

Features of JAVA (or) Buzzwords


 Java is Object Oriented
• Java supports programming with classes, objects.

• It also supports other oops concepts like polymorphism, inheritance,


encapsulation etc.,

• Objects are communicated through messages.

JAVA Programming BSNV R Murthy 41


Aditya College of Engineering & Technology

Features of JAVA (or) Buzzwords


 Java is Architecture Neutral (Platform independent)

JAVA Programming BSNV R Murthy 42


Aditya College of Engineering & Technology

Features of JAVA (or) Buzzwords


 Java is Portable
• Java is the most portable language, which can be executed almost all popular
platforms in the world.
• The variety of platforms are :
Windows, Mac OS,
UNIX/Linux like HP-Unix,
Sun Solaris, Red hat Linux,
Ubuntu, Cent OS, etc.,

JAVA Programming BSNV R Murthy 43


Aditya College of Engineering & Technology

Features of JAVA (or) Buzzwords


 Java is Interpreted
• To translate the byte code into native machine code, java uses interpreter.

• Interpreter provides dynamic nature of execution with runtime checking.

• But Interpreters are slow when compared with compilers.

• To make fast execution, Java uses Just-in-Time compilers, which provides


high performance.

JAVA Programming BSNV R Murthy 44


Aditya College of Engineering & Technology

Features of JAVA (or) Buzzwords


 Java is Interpreted

JAVA Programming BSNV R Murthy 45


Aditya College of Engineering & Technology

Features of JAVA (or) Buzzwords


 Java is Distributed

• The .class files of java can be easily transferred to remote machine.

• Support for TCP, UDP, and basic Socket communication.

• Ex : applets, servlets, remote method invocation (RMI), EJB, JDBC.

JAVA Programming BSNV R Murthy 46


Aditya College of Engineering & Technology

Features of JAVA (or) Buzzwords


 Java is Robust - (Strong)
• It means, programs written in java will crash less often.
• JVM first checks the reliability of the code before execution.
• Java has the strong memory allocation and automatic garbage collection
mechanism, to avoid memory failures.
• Java has got excellent inbuilt exception handling features.
• Not like C, arrays are handled without memory leaks.
• Strict Run-time checking and no pointers.
• Java is Strongly typed language.

JAVA Programming BSNV R Murthy 47


Aditya College of Engineering & Technology

Features of JAVA (or) Buzzwords


 Java is Secured
• Java allows all the programs to run inside the JVM (‘sandbox’) only and
prevents many activities from non-trusted resources including reading or
writing to the local.
• No pointers, because pointers lead to hack easily.
• Bytecode, which are tested by the JVM at the time of program execution for
viruses and other malicious programs.
• Security problems like eavesdropping, tampering etc., are minimized on
internet.

JAVA Programming BSNV R Murthy 48


Aditya College of Engineering & Technology

Features of JAVA (or) Buzzwords


 Java is High Performance

• Just-in-time compilers

• Adaptive optimization, means dynamic recompilation of portions of a


program based on the current execution profile.

• Efficient memory management through garbage collector.

• Handle large memory space at run time.

JAVA Programming BSNV R Murthy 49


Aditya College of Engineering & Technology

Features of JAVA (or) Buzzwords


 Java is Multithreaded
• Thread is basically a lightweight sub-process, a smallest unit of processing.

• Multithreading in java is a process of executing multiple threads


simultaneously.

• Multithreading is used to achieve multitasking.

• Uses the processor’s resources most efficiently.

JAVA Programming BSNV R Murthy 50


Aditya College of Engineering & Technology

Features of JAVA (or) Buzzwords


 Java is Dynamic
• Java loads the byte code dynamically at runtime and executes

• Java API is part of JRE and these libraries are dynamically linked at runtime
while executing on the target platform.

• Java classes carry run-time type information, that uses to dynamically linking
of objects at run time.

JAVA Programming BSNV R Murthy 51


Aditya College of Engineering & Technology

Features of JAVA
• Many Java features are inherited from the earlier languages:
B, C, C++

JAVA Programming BSNV R Murthy 52


Aditya College of Engineering & Technology

Differences between C and JAVA


Basis C JAVA
Programming Pattern It is a procedural language. It is a pure object-oriented
programming language.
Approach It uses the top-down approach. It also uses the bottom-up
approach.
Dynamic or Static It is a static programming It is a dynamic programming
language. language.
Code Execution The code is executed directly. The code is executed by the JVM.
Platform Dependency It is platform dependent. It is platform-independent
because of byte code.

JAVA Programming BSNV R Murthy 53


Aditya College of Engineering & Technology

Differences between C and JAVA


Basis C JAVA
Translator It uses a compiler only to Java uses both compiler and interpreter
translate the code into and it is also known as an interpreted
machine language. language.
File Generation It generates the .exe, and It generates .class file.
.bak, files.
Number of Keyword There are 32 keywords in the There are 52 keywords in the Java
C language. language.
Source File Extension The source file has a .c The source file has a .java extension.
extension.
Pointer Concept It supports pointer. Java does not support the pointer concept
because of security.
JAVA Programming BSNV R Murthy 54
Aditya College of Engineering & Technology

Differences between C and JAVA


Basis C JAVA
Union and Structure It supports union and structure data It does not support union
Datatype types. and structure data types.
Pre-processor It uses pre-processor directives such as It does not use directives but
Directives #include, #define, etc. uses packages.
Constructor/ It does not support constructor and It supports constructors only.
Destructor destructor.
Exception Handling It does not support exception It also supports exception
handling. handling.
Memory It uses the calloc(), malloc(), free(), and It uses a garbage collector to
Management realloc() methods to manage the manage the memory.
memory.
JAVA Programming BSNV R Murthy 55
Aditya College of Engineering & Technology

Differences between C and JAVA


Basis C JAVA
Overloading It does not support the Only method overloading can be
overloading concept. achieved.
goto Statement It supports the goto statement. It does not support the goto
statements.
Used for It is widely used to develop It is used to develop web
drivers and operating systems. applications, mobile applications,
and windows applications.

JAVA Programming BSNV R Murthy 56


Aditya College of Engineering & Technology

Program Structure
A Java Program source file having extension of .java,
consists of a collection of classes.

A class is a template containing methods and


variables.

Comments are added to the source , to improve


readability.

JAVA Programming BSNV R Murthy 57


Aditya College of Engineering & Technology

Writing simple Java Programs


Java is an Object oriented language. Every java program imports packages which are
provides necessary classes and interfaces.
For example: import java.util.*;
import java.io.*;
After import statement, every java program starts with the declaration of the class. A
program may have one or more classes.
A class declaration starts with the keyword class, followed by the identifier or name of
the class.
Giving the name of a package at the top is optional.
Class declaration contains name of the class and body of the class. The body of the class
may consist of several statements and is enclosed between the braces {}.

JAVA Programming BSNV R Murthy 58


Aditya College of Engineering & Technology

Writing simple Java Programs


A sample of class declarations is as follows.

Here: public is access specifier. This class is accessible to any outside code. Otherwise the class is
accessible to only same package classes.
class is a keyword of java language which is used to declare the class.
The class body starts with the left brace { and ends with the right closing brace }. // are comments
which are neglected by the compiler.
A class body may comprise statements for declaration of variables. constants, expressions, and
methods.

JAVA Programming BSNV R Murthy 59


Aditya College of Engineering & Technology

Writing simple Java Programs


C Program vs Java Program

JAVA Programming BSNV R Murthy 60


Aditya College of Engineering & Technology

Compiling and running of Program


C Program vs Java Program

JAVA Programming BSNV R Murthy 61


Aditya College of Engineering & Technology

Writing simple Java Program


/* Call this file “Example.java”.*/
class Example
{
//starts execution with a call to main() function

public static void main(String args[ ])

{
System.out.println(“This is a simple Java program”);
}
}

JAVA Programming BSNV R Murthy 62


Aditya College of Engineering & Technology

Writing simple Java Program


• Entering the source code: text editor like notepad, edit plus, notepad++, netbeans IDE
or any other IDE
• Saving the source code:
Select File | Save As from the notepad menu.
In the ‘File name’ field, type “Example.java” within the double quotes
In the ‘Save as type’ field select All Files (*.*).
Click enter to save the file.

JAVA Programming BSNV R Murthy 63


Aditya College of Engineering & Technology

Writing simple Java Program


• Compiling & running the source :
type cmd at the run prompt; move to the folder that contains the saved Example.java file :
compile the program using javac,
C:\javaeg\>javac Example.java
• Compilation creates a file called Example.class
• This class contains bytecode which is interpreted by JVM.
• To execute the program type the following command at the dos prompt:
C:\javaeg\>java Example
• The output of the program is shown below:
This is a simple Java program

JAVA Programming BSNV R Murthy 64


Aditya College of Engineering & Technology

Important points in Java Program


• Java is CASE SENSITIVE

• Whitespace is ignored by compiler

• Whitespace makes things easier to read, hence it affects your grade

• File name has to be the same as class name in file.

• Need to import necessary class definitions

JAVA Programming BSNV R Murthy 65


Aditya College of Engineering & Technology

Comments in Java Program


 The documentation section is an important section but optional for a Java program.

 It includes basic information about a Java program. The information includes


the author's name, date of creation, version, program name, company
name, and description of the program.

 It improves the readability of the program. Whatever we write in the documentation


section, the Java compiler ignores the statements during the execution of the
program.

 The comments may be


 single-line,
 multi-line, and
 documentation comments.

JAVA Programming BSNV R Murthy 66


Aditya College of Engineering & Technology

Comments in Java Program


• Single-line Comment: It starts with a pair of forwarding slash (//). For example:
//First Java Program

• Multi-line Comment: It starts with a /* and ends with */. We write between these two symbols.

• For example:

1. /*It is an example of

2. multiline comment*/

• Documentation Comment: It starts with the delimiter (/**) and ends with */.

• For example:

• /**It is an example of documentation comment*/

JAVA Programming BSNV R Murthy 67


Aditya College of Engineering & Technology

Elements or Tokens in Java Programs


• A token is an atomic unit in the program for compilation.
• Types of tokens:
 Identifiers: names the programmer chooses
 Reserved Keywords: names already in the programming language
 Literals ( constants) : Numeric: int and double, Logical: boolean , Textual:
char and String & Reference: null
 Separators (also known as punctuators): punctuation characters and paired-
delimiters and white spaces
 Operators: symbols that operate on arguments and produce results
 Comments : Line, Block

JAVA Programming BSNV R Murthy 68


Aditya College of Engineering & Technology

Elements or Tokens in Java Programs


 Identifiers: names the programmer chooses - Variable names, method names, constants,
array names, class names, interface names etc., are Identifiers.
• Rules for identifiers :
 Can start with a letter(alphabet), underscore(_), or any currency symbol like dollar sign($),
pound (£).
 are case sensitive and have no maximum length.
 Second letter onwards we can use digits.
 Should not be keywords or reserve words
 No spaces are allowed.
valid invalid
username identi+fier
user_name 6userName
_sys_var1 #sys_var1
$change change&

JAVA Programming BSNV R Murthy 69


Aditya College of Engineering & Technology

Elements or Tokens in Java Programs


Conventions for Writing Names
• Package Names: only in lower case and words are seperated by dot(.)
Ex : java.lang, java.awt.event
• Classes and Interfaces: Each word first letter is in Upper case.
Ex: IndexOutOfBoundsException, SavingAccount
• Methods: Each word first letter is uppercase except first word, and followed by paranthesis ()
Ex : getUserName(), setAccountBalance()
• Variables: Each word first letter is uppercase except first word
Ex : bookName, studentRollNumber
• Constants: All words are in uppercase and seperated by underscore.
Ex : MAX_VALUE, HEAD_COUNT, MAXIMUM_SIZE

JAVA Programming BSNV R Murthy 70


Aditya College of Engineering & Technology

Elements or Tokens in Java Programs


 Reserved Keywords: names already in the programming language

JAVA Programming BSNV R Murthy 71


Aditya College of Engineering & Technology

Elements or Tokens in Java Programs


Literals ( constants) :These are values represented by a set of character, digits, etc.
Integer literals
Decimal Integer Literals
Hex Integral Literals
Octal Integer Literals
Binary Literals
Floating point literal
Boolean literal - These are Boolean values. There are only two values—true or false.
Character literal - These are the values in characters.
Characters are represented in single quotes such as ‘A’, ‘H’, ‘k’, and so on.
String literal -These are strings of characters in double quotes. Examples are “Delhi”.
Null literal - There is only one value of Null Literal, that is, null.
JAVA Programming BSNV R Murthy 72
Aditya College of Engineering & Technology

Elements or Tokens in Java Programs


Separators (also known as punctuators): punctuation characters and paired-
delimiters and white spaces
These include comma, semicolon, period(.), Parenthesis (), Square brackets [],
etc.,

JAVA Programming BSNV R Murthy 73


Aditya College of Engineering & Technology

Elements or Tokens in Java Programs


Operators: symbols that operate on arguments and produce results
Types of Operators
Arithmetic Operators (+ , - ,*, /, %)
Relational Operators (> , >= , < , <= , == ,!=)
Logical Operators ( &&, ||,!)
Assignment Operators (= , += , -= , *= , /= , %= )
Increment / Decrement Operators (++ , --)
Bitwise Operators (&, |, ^ , ~ , << , >>, >>> )
Conditional Operators (? : )

JAVA Programming BSNV R Murthy 74


Aditya College of Engineering & Technology

JAVA STATEMENTS
 A statement specifies an action in a Java program.

 Java statements can be broadly classified into three categories:

 Declaration statement

 Expression statement

 Control flow statement

JAVA Programming BSNV R Murthy 75


Aditya College of Engineering & Technology

JAVA STATEMENTS
Declaration statement

 A declaration statement is used to declare a variable.

Ex. int num;

int num2 = 100;

string str;

JAVA Programming BSNV R Murthy 76


Aditya College of Engineering & Technology

JAVA STATEMENTS
Expression statement
 An expression with a semicolon at the end is called an expression statement.
Ex. //Increment and decrement expressions
num++; num--;
++num; --num;
//Assignment expressions
num = 100; num *= 10;
//Method invocation expressions
System.out.println("This is a statement");
someMethod(param1, param2);

JAVA Programming BSNV R Murthy 77


Aditya College of Engineering & Technology

JAVA STATEMENTS
Flow Control statement
 By default, all statements in a Java program are executed in the order they
appear in the program. Sometimes you may want to execute a set of
statements repeatedly for a number of times or as long as a particular
condition is true.

 All of these are possible in Java using flow control statements. The if
statement, while loop statement and for loop statement are examples of
control flow statements.

JAVA Programming BSNV R Murthy 78


Aditya College of Engineering & Technology

Command Line Arguments


 A Java application can accept any number of arguments from the command
line.

 Command line arguments are parameters that are passed to the application
program at the time of execution.

 The parameters are received by args array of string type.

The first argument is stored at args[0] The second argument is stored at args[1]
and so on…

JAVA Programming BSNV R Murthy 79


Aditya College of Engineering & Technology

Command Line Arguments


Example
vehicle.java
CLargument.java
In an array, we can make use of the length property of the array.
Output

JAVA Programming BSNV R Murthy 80


Aditya College of Engineering & Technology

Command Line Arguments


Example : Add two no’s using command line arguments.
Cadd2.java

JAVA Programming BSNV R Murthy 81


Aditya College of Engineering & Technology

Declaration of Variables

Examples:
double price = 28.5;
char ch = "C":
String name - "John";
illustrates the declaration and output of some data types

PrintOut.java

JAVA Programming BSNV R Murthy 82


Aditya College of Engineering & Technology

USER INPUT TO THE PROGRAM


 The class Scanner of package java.util to carry out input to the program.

 Importing the class is the first step. import java.util.Scanner;

 The object of the class Scanner is declared as follows.

Scanner scaninput = new Scanner (System. in);

The object “scaninput” invokes the method nextInt() which reads the value
typed by the user.

JAVA Programming BSNV R Murthy 83


Aditya College of Engineering & Technology

USER INPUT TO THE PROGRAM


Input Types and their respective methods:
Method Description
nextBoolean() Reads a boolean value from the user
nextByte() Reads a byte value from the user
nextDouble() Reads a double value from the user
nextFloat() Reads a float value from the user
nextInt() Reads a int value from the user
nextLine() Reads a String value from the user
nextLong() Reads a long value from the user
nextShort() Reads a short value from the user
JAVA Programming BSNV R Murthy 84
Aditya College of Engineering & Technology

USER INPUT TO THE PROGRAM


Illustration of a user's input from keyboard into program.

Example 1: Arithmetic.java

Example2 :Kinput.java

JAVA Programming BSNV R Murthy 85


Aditya College of Engineering & Technology

ESCAPE SEQUENCE CHARACTERS


A character preceded by a backslash (\) is an escape sequence and has a special
meaning to the compiler.
The following table shows the Java escape sequences.
Escape Sequence Description
\t Inserts a tab in the text at this point.
\b Inserts a backspace in the text at this point.
\n n Inserts a newline in the text at this point.
\r r Inserts a carriage return in the text at this point.
\f Inserts a form feed in the text at this point.
\’ Inserts a single quote character in the text at this point.
\” Inserts a double quote character in the text at this point.
\\ Inserts a backslash character in the text at this point.
\ddd Octal Character
\uxxxx
JAVA Programming Hexadecimal unicode
BSNV R character
Murthy 86
Aditya College of Engineering & Technology

ESCAPE SEQUENCE CHARACTERS


Example:

Escape.java

JAVA Programming BSNV R Murthy 87


Aditya College of Engineering & Technology

Programming Style
There are no set patterns of good style and bad style

 The program should present a clean and orderly look.

 The program should be easy to understand.

 Debugging should be easy.

 The program should be easy to use.

 The program should be easy to maintain.

 The program should be fail-safe.

JAVA Programming BSNV R Murthy 88


Aditya College of Engineering & Technology

DATA TYPES in JAVA

JAVA Programming BSNV R Murthy 89


Aditya College of Engineering & Technology

DATA TYPES in JAVA

JAVA Programming BSNV R Murthy 90


Aditya College of Engineering & Technology

DATA TYPES in JAVA


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
Class_identifier object_identifier;
Similarly, an interface reference is declared as
Interface_identifier reference_identifier;
Example: String str "Delhi“
Illustrates the all data types: DataType.java

JAVA Programming BSNV R Murthy 91


Aditya College of Engineering & Technology

TYPE CASTING
Converting one data type to another data type is called as Type Casting.
There are two types of type casting.
They are,
i. Implicit Type casting
Implicit type casting is done automatically by a compiler when we assign a
value to the variable.
Example: int a=10;
double b;
b=a;
Here a is integer and d is double variables. Integer value is automatically converted
into double by the compiler
JAVA Programming BSNV R Murthy 92
Aditya College of Engineering & Technology

TYPE CASTING
II. Explicit Type casting
The explicit type casting is carried out by the following code:
type variable = (new_type) variable;
It is illustrated by the following code lines:
double D = 6.865;
int A = (int) D;
In such a conversion, there is loss of data

JAVA Programming BSNV R Murthy 93


Aditya College of Engineering & Technology

TYPE CASTING
II. Explicit Type casting
The explicit type casting is carried out by the following code:
type variable = (new_type) variable;
It is illustrated by the following code lines:
double D = 6.865;
int A = (int) D;
In such a conversion, there is loss of data

Example: TypeCast.java

JAVA Programming BSNV R Murthy 94


Aditya College of Engineering & Technology

SCOPE OF VARIABLE IDENTIFIER


It is visible and holds the last entered value In Java.
There are distinctly two types of scopes.
(a) class scope
(b) method scope
A variable declared in a class has class scope and scope of a variable declared in a
method has method scope.
The variables declared in a block have block scope.
Thus, the variables defined in main() at the beginning have scope in entire main()
method, however, those defined in a block have block scope.
A block starts with the left brace ( { ) and ends with the right brace ( } ).

JAVA Programming BSNV R Murthy 95


Aditya College of Engineering & Technology

SCOPE OF VARIABLE IDENTIFIER


Illustration of block scope
Example: ScopeA.java

JAVA Programming BSNV R Murthy 96


Aditya College of Engineering & Technology

LITERAL CONSTANTS, SYMBOLIC CONSTANTS

i. Literal Constants
The char literals are enclosed in single quotes (‘ ’). The examples ‘A’ and ‘B’.
These may also be written as \u0041 and \u0042
ii. Symbolic Constants
A Symbolic constant is a variable whose value does not change throughout
the program. Some of the examples include Pi, NORTH, EAST etc.
Illustrates the use of symbolic constant
Example: SymbolicConst.java

JAVA Programming BSNV R Murthy 97


Aditya College of Engineering & Technology

Formatted Output with printf() Method

In Java, the formatting of output may be carried out in two ways:


1. By using class Formatter
2. 2. By method printf()
The syntax of the method printf () method is as follows
System.out.printf("Formatting string" variables separated by comma);

Illustration of formatting strings for output of different types of variables


FPrintf.java

JAVA Programming BSNV R Murthy 98


Aditya College of Engineering & Technology

Static Variables and Methods

Static Variables:
The static variables are class variables.
Only one copy of such variables is kept in the memory and all the objects share
that copy.
The static variables are accessed through class reference, whereas the instance
variables are accessed through class object reference.
Example: EmpCount.java
Static Method:

JAVA Programming BSNV R Murthy 99


Aditya College of Engineering & Technology

Static Variables and Methods

Static Method:
The static methods are similar to class methods and can be invoked without any
reference of object of class.
However, class reference (name of class) is needed, as in the following example
The method like sqrt() is declared as static method in Math class and is called
Math.sqrt(5); // Finds square root of 5
The static method is called using the method name that is preceded by the class
name; in this case. Math and period ().
Example:StaticMethods.java

JAVA Programming BSNV R Murthy 100


Aditya College of Engineering & Technology

ATTRIBUTE FINAL

Final Variable: The value of a variable declared final cannot be changed in the
program. It makes the variable a constant.
A few examples of declarations are as follows:
final double PI = 3.14159; // The value of PI cannot be changed in its scope
final int M = 900; // The value of M cannot be changed in its scope.
Final Method: The attribute final may be used for methods as well as for classes.
These are basically connected with inheritance of classes.
When final keyword is used with Java method, it becomes the final method.
A final method cannot be overridden in a sub-class.
Final Class: A Java class with final modifier is called final class A final class cannot
be sub-classed or inherited.
JAVA Programming Example:Final.java BSNV R Murthy 101
Aditya College of Engineering & Technology

FLOW OF CONTROL
CONTROL STATEMENTS: (FLOW OF CONTROL) - A Control statement is a statement
used to control the flow of execution in a Java Program.

JAVA Programming BSNV R Murthy 102


Aditya College of Engineering & Technology

If Statement

• The Java if statement tests the condition.


• It executes the if block if condition is true.

Syntax:
if(condition)

//code to be executed

}
JAVA Programming BSNV R Murthy 103
Aditya College of Engineering & Technology

If else Statement

• The Java if-else statement also tests the


condition.
• It executes the if block if condition is true
otherwise else block is executed.
Syntax:
if(condition)
{
//code if condition is true
}
Else
{
//code if condition is false
JAVA Programming BSNV R Murthy 104
}
Aditya College of Engineering & Technology

else if ladder Statement

• The if-else-if ladder statement executes one condition from multiple


statements.

• Syntax:

• if(condition1){//code to be executed if condition1 is true }


• else if(condition2){ //code to be executed if condition2 is true
}
else if(condition3){//code to be executed if condition3 is true
• }
• ...
• …

JAVA Programming BSNV R Murthy 105


Aditya College of Engineering & Technology

else if ladder Statement

• The if-else-if ladder statement


executes one condition from
multiple statements.
Syntax:
if(condition1){//code to be execut
ed if condition1 is true }
else if(condition2){
//code to be executed if con
dition2 is true }
else if(condition3){//code t
o be executed if condition3 is tru
e
}
...

JAVA Programming BSNV R Murthy 106
Aditya College of Engineering & Technology

Switch Statement

 The Java switch statement executes one statement from multiple conditions. It is like if-else- if
ladder statement.
 The switch statement works with byte, short, int, long, enum types, String and some wrapper
types like Byte, Short, Int, and Long.
• Points to Remember:
• There can be one or N number of case values for a switch expression.
• The case value must be of switch expression type only. The case value must be literal or constant. It
doesn't allow variables.

JAVA Programming BSNV R Murthy 107


Aditya College of Engineering & Technology

Switch Statement

Syntax:
switch(expression)
{
case value1: //code to be executed;
break; //optional
case value2: //code to be executed;
break; //optional


default: //code to be executed if all cases are not matched;
}
JAVA Programming BSNV R Murthy 108
Aditya College of Engineering & Technology

Switch Statement

JAVA Programming BSNV R Murthy 109


Aditya College of Engineering & Technology

Ternary Operator

The ternary operator is a type of Java conditional operator.


The meaning of ternary is composed of three parts.
The ternary operator (? :) consists of three operands.
It is used to evaluate Boolean expressions.
The operator decides which value will be assigned to the variable.
It is the only conditional operator that accepts three operands.
It can be used instead of the if-else statement.
It makes the code much more easy, readable, and shorter.
Syntax: Expression1 ? Expression2 : Expression3

JAVA Programming BSNV R Murthy 110


Aditya College of Engineering & Technology

Ternary Operator

Example:
public class Ternary
{
public static void main (String args[])
{
int a=10;
int b = (a< 20) ? 100 : 200;
System.out.println("b= "+b);
}
}

JAVA Programming BSNV R Murthy 111


Aditya College of Engineering & Technology

LOOP STATEMENTS

• In computer programming, loops are used to repeat a block of code.

• In Java, there are three types of loops.

• for loop

• While loop

• Do-while loop

JAVA Programming BSNV R Murthy 112


Aditya College of Engineering & Technology

For LOOP STATEMENTS

• A simple for loop is the same as C/C++ We can initialize the variable check
condition and increment/decrement value. It consists of four parts:
• Initialization:
• It is the initial condition which is executed once when the loop starts. Here, we
can initialize the variable, or we can use an already initialized variable. It is an
optional condition.
• Condition:
• It is the second condition which is executed each time to test the condition of
the loop. It continues execution until the condition is false. It must return
Boolean value either true or false. It is an optional condition.
• Statement: The statement of the loop is executed each time until the second
condition is false.
• Increment/Decrement: It increments or decrements the variable value. It is
JAVA Programming BSNV R Murthy 113
an optional condition.
Aditya College of Engineering & Technology

For LOOP STATEMENTS

for(initialization; condition; incr/decr)


{
//statement or code to be executed
}

JAVA Programming BSNV R Murthy 114


Aditya College of Engineering & Technology

Nested For LOOP STATEMENTS

• If we have a for loop inside the another loop, it is known as nested for loop.
• The inner loop executes completely whenever outer loop executes.

JAVA Programming BSNV R Murthy 115


Aditya College of Engineering & Technology

For each LOOP STATEMENTS

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:

for(Type var: array)


{
//code to be executed
}

JAVA Programming BSNV R Murthy 116


Aditya College of Engineering & Technology

For each LOOP STATEMENTS

//Java For-each loop example which prints the elements of the array
public class ForEach
{
public static void main(String[] args)
{
int arr[]={12,23,44,56,78}; //Declaring an array
//Printing array using for-each loop
for(int i:arr)
{
System.out.println(i);
}
}
}
JAVA Programming BSNV R Murthy 117
Aditya College of Engineering & Technology

For each LOOP STATEMENTS

class Main
{
public static void main(String[] args)
{
// an array of numbers
int[] numbers = {3, 4, 5, -5, 0, 12};
int sum=0; // iterating through each element of the array
for (int number: numbers)
{
sum += number;
}
System.out.println("Sum = " + sum);
}
JAVA Programming BSNV R Murthy 118
}
Aditya College of Engineering & Technology

For each LOOP STATEMENTS

JAVA Programming BSNV R Murthy 119


Aditya College of Engineering & Technology

While & do-while LOOP STATEMENTS

The while loop loops through a block of code as long as a specified condition is true.
 The do/while loop is a variant of the while loop.
 This loop will execute the code block once, before checking if the condition is true, then it will
repeat the loop as long as the condition is true.

JAVA Programming BSNV R Murthy 120


Aditya College of Engineering & Technology

While LOOP STATEMENTS

// Program to display numbers from 1 to 5


class Main
{
public static void main(String[] args)
{
// declare variables
int i = 1;
// while loop from 1 to 5
while(i <= 5)
{
System.out.println(i);
i++;
}

}
}
JAVA Programming BSNV R Murthy 121
Aditya College of Engineering & Technology

Do-While LOOP STATEMENTS

// Program to display numbers from 1 to 5


class Main
{
public static void main(String[] args)
{
// declare variables
int i = 1;
// do- while loop from 1 to 5
do
{
System.out.println(i);
i++;
} while(i <= 5) ;
}
}

JAVA Programming BSNV R Murthy 122


Aditya College of Engineering & Technology

Break STATEMENTS

Unconditional control statements: -


The unconditional control statements are,
a) break statement
b) continue statement

break statement: -The break statement skips from the loop or block in which it is defined.
The control then automatically goes to the first statement after the loop or block.
The general format is break;

JAVA Programming BSNV R Murthy 123


Aditya College of Engineering & Technology

Break STATEMENTS

public class Break


{
Output:
public static void main (String args[])
{ C:\>javac Break.java
//printing the values from 1 to 10 C:\>java Break
0
for(int i =0; i<10;i++)
1
{ 2
if (i==5) 3
break; //Break Statement 4
System.out.println( i );
Here loop is stopped due to break statement.
}
}
}

JAVA Programming BSNV R Murthy 124


Aditya College of Engineering & Technology

Continue STATEMENTS

The continue statement is used for continuing next iteration of loop statements. –
When it occurs in the loop, it does not terminate but it skips the statements after
it.
It is useful when we want to continue the program without executing any part of
the program.

The general format is continue;

JAVA Programming BSNV R Murthy 125


Aditya College of Engineering & Technology

Continue STATEMENTS

class Test
{
public static void main(String[] args) {
for (int i = 1; i <= 10; ++i)
{
i=1 2 3 4 9 10
if (i > 4 && i < 9)
{
continue;
}
System.out.println(i);
}
}
}
JAVA Programming BSNV R Murthy 126
ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY

Thank You

You might also like