KEMBAR78
Unit1 Java | PDF | Data Type | Object Oriented Programming
0% found this document useful (0 votes)
14 views101 pages

Unit1 Java

Object Oriented Programing notes

Uploaded by

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

Unit1 Java

Object Oriented Programing notes

Uploaded by

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

Unit I

Introduction Object Oriented Programming

Paradigms of Programming Languages Programming paradigms are a way to classify


programming languages according to the style of computer programming. It provides
model to the programmers to write programs. Some of the common paradigms are
1.Monolithic Programming
2. Procedural Programming
3. Structured Programming
4. Object Oriented Programming
Monolithic Programming: Monolithic programming is also called as unstructured
programming. In this paradigm the whole problem is solved as a single block. All the data are
global and there is no security. To share the codes lot of goto statements are used. This is
suitable only for small problem. It is difficult to correct errors. ex : BASIC Language, Assembly
Language.

Procedural Programming: In procedural programming, the tasks are divided in to a


number of subtasks according to their functions. These subtasks are called procedures or
methods. Any procedure can be called at any point during the program execution. The
program has global and local data. Data moves freely from one procedure to another. Most of
the procedure share common data. Procedural programming uses Top-Down programming
Approach. Here the importance is given to algorithms. The main disadvantage of this
paradigm is the difficulty in debugging and the identification of the data and its
corresponding procedure. ex : FORTRAN, Pascal
Structured Programming: Structured programming is a powerful tool that enable the
programmers to write complex programs easily. It is a subset of procedural programming.
The program is divided into modules and the modules are then divided into functions. Each
module works independent of one another. C language is a very popular structured
programming language. The main disadvantage of this paradigm is when the programs grew
larger this approach failed to show effective results in terms of bug free, maintenance and
reusability.

Object Oriented Programming: The program is divided into number of small units called
object. The data and function are build around these objects. The data of the objects can be
accessed only by the functions associated with that object. The functions of one object can
access the functions of other object. In OOP the importance is given on data rather than
functions. The problems are divided into objects. Data and function are tied together. Data
hiding is possible. New data and functions can be easily loaded. Object can communicate
with each other using functions
Features
 Emphasis is on data rather than the procedure.
 Programs are divided into Objects.
 Data structures are designed such that they characterize the objects.
 Methods that operate on the data of an object are tied together in the data structure.
@Data hidden cannot be accessed by external functions.
 Objects may communicate with each other through methods.
 New data and methods can be easily added whenever necessary. @Follows bottom-up
approach in program design.
Object Oriented Programming is an approach that provides a way of modularizing by
creating partitioned memory area for both data and functions that can be used as
templates for creating copies of such modules on demand.
Basic concepts of OOP
 Object:
 An object is a software entity that combines a set of data with a set of
operations to manipulate the data.
 An object is an instance of a class.
 An object is known by a name and every object contains a state.
 The state of is determined by the values of properties.
 The state of an object can be changed by calling methods on it.
 The sequence of states represent the behavior of the object.
 Class:
 A class is defined as the blue print of the object.
 It serves as a plan or a template.
 Description of a number of similar objects is also called a class.
 A class is a user-defined data type.
 A class contains two things i.e, properties and methods.

 Encapsulation:
 Encapsulation is one of the features of object-oriented methodology.
 The process of binding the data and methods that operate on data into object to
hide them from the outside world is called as encapsulation.
 Encapsulation is also known as data hiding. Data encapsulation is the striking
feature of a class.
 Abstraction:
 Abstraction refers to the act of representing essential features without including
the background details or explanations.
 Classes use the concept of abstraction and are defined as a list of properties and
methods to operate on these properties.

 Inheritance:
 Inheritance is the way to adopt the characteristics of a class into another class.
 Here we have two types of classes. One is base class(super class) and the other one is
derived class(sub class).
 There exist a parent-child relationship among the classes.
 A sub class inherits all the properties of a base class, in addition to this it can add its own
features.
 Polymorphism:
 Polymorphism means the ability to take more than one form.
 An operation may exhibit different behavior in different instances.
 The behavior depends up on the type of data used in the operation.
 Consider the operation of addition for two numbers, the operation will generate sum, if the
operands were strings, then the operation will produce a third string by concatenation.

 Dynamic Binding:
 Binding refers to the linking of method call to the method.
 Dynamic Binding means that the code associated with a method call is not known until the
time of the call at runtime.
 It is associated with polymorphism and inheritance.
 Message Passing:
 An object oriented program consists of a set of objects that communicate with each other.
 The process of programming in an object-oriented language involves the following basics.
a) Creating classes that define object and their behavior.
b) Creating object from class definitions.
c) Establishing communication between objects. Objects communicate with one-another by sending
and receiving information much the same way as people pass messages to one-another is called
message passing.

Message passing involves specifying the name of the object, the name of the
method(message) and the information to be sent. Consider the following example:
information<>message ; name<>Object ; salary<>Employee.salary(name); Employee
Benefits
1. Through inheritance we can eliminate redundant code and extend the use of
existing classes.
2. We can build programs from the standard working modules that communicate
with one another rather than having to start writing the code from scratch.
3. The principle of data hiding helps the programmer to build secure programs
that cannot be invaded by code in other parts of the program.
4. It is possible to have multiple objects to co-exist without any interference.
5. It is possible to map objects in the program domain to those objects in the
program.
6. It is easy to partition the work in a project based on objects.
7. The data centered design approach enables us to capture more details of a
model in an implementation.
8. Systems can be easily upgraded from small to large systems.
9. Message passing techniques for communication between objects make the
interface descriptive with external systems much simpler.
Applications

1.Real time systems


2. Simulation and modeling
3. Object-Oriented database.
4. Hypertext, Hypermedia
5. Artificial Intelligence and Expert Systems
6. Neural Networks and Parallel programming
7. Decision support and office automation systems.
History

 Java is one of the programming language used by industry programmers for


development of distributed applications by making use of client server architecture.
 Java developed at SUN micro systems in the year 1990 by James Gosling and others.
 Originally SUN micro system is one of the academic university(Stanford University
network) James Gosling designed rules for developing Java and these rules are
programmatically implemented by IMC U. S.A.,
 Whatever the trail version developed and released in the year 1990 known as Oak,
which is original name of java and scientifically which is one of the tree name Oak has
taken 18 months to develop.
 The software Oak is able to solve 50% of the industry requirements this unable to
solve 50% of industry problems. This is one of the compliment and complain given by
the industry programmers to the SUN micro system.
 SUN Micro system has performed reengineering operation on Oak and released a new
version of Oak known as Java in the year 1995.
JAVA Features:

1. Compiled and Interpreted


2. Platform Independent and portable
3. Object- oriented
4. Robust and secure
5. Distributed
6. Familiar, simple and small
7. Multithreaded and Interactive
8. High performance
9. Dynamic and Extensible
1. Compiled and Interpreted: Basically a computer language is either compiled or
interpreted. Java comes together both these approach thus making Java a two-stage
system. Java compiler translates Java code to Bytecode instructions and Java
Interpreter generate machine code that can be directly executed by machine that is
running the Java program.

2. Platform Independent and portable: Java supports the feature portability. Java
programs can be easily moved from one computer system to another and anywhere.
Changes and upgrades in operating systems, processors and system resources will not
force any alteration in Java programs. This is reason why Java has become a trendy
language for programming on Internet which interconnects different kind of systems
worldwide. Java certifies portability in two ways. First way is, Java compiler generates
the bytecode and that can be executed on any machine. Second way is, size of
primitive data types are machine independent.
3. Object- oriented: Java is truly object-oriented language. In Java, almost everything is
an Object. All program code and data exist in objects and classes. Java comes with an
extensive set of classes; organize in packages that can be used in program by
Inheritance. The object model in Java is trouble-free and easy to enlarge.

4. Robust and secure: Java is a most strong language which provides many securities
to make certain reliable code. It is designed as garbage –collected language, which helps
the programmers virtually from all memory management problems. Java also includes
the concept of exception handling, which detain serious errors and reduces all kind of
threat of crashing the system. Security is an important feature of Java and this is the
strong reason that programmer use this language for programming on Internet. The
absence of pointers in Java ensures that programs cannot get right of entry to memory
location without proper approval.
5. Distributed: Java is called as Distributed language for construct applications on
networks which can contribute both data and programs. Java applications can open
and access remote objects on Internet easily. That means multiple programmers at
multiple remote locations to work together on single task.

6. Simple and small: Java is very small and simple language. Java does not use
pointer and header files, goto statements, etc. It eliminates operator overloading
and multiple inheritance.

7. Multithreaded and Interactive: Multithreaded means managing multiple tasks


simultaneously. Java maintains multithreaded programs. That means we need not
wait for the application to complete one task before starting next task. This feature
is helpful for graphic applications.
8. High performance: Java performance is very extraordinary for an interpreted
language, majorly due to the use of intermediate bytecode. Java architecture is also
designed to reduce overheads during runtime. The incorporation of multithreading
improves the execution speed of program.

9. Dynamic and Extensible: Java is also dynamic language. Java is capable of


dynamically linking in new class, libraries, methods and objects. Java can also
establish the type of class through the query building it possible to either dynamically
link or abort the program, depending on the reply. Java program is support functions
written in other language such as C and C++, known as native methods.
Byte code

Byte code is set of Optimized instruction generated during


compilation phase and whose nature is more powerful than
ordinary pointer code. Byte code is common for all operating
systems. Hence it is treated as platform independent and OS
independent.
Java Virtual machine

JVM is the set of programs developed by SUN Microsystems and supplied as


part of JDK and whose role is reading the line by line of byte code and
converting into native understanding form of OS. For each and every OS we
have different types of JVMS hence JVM is treated as OS dependent.
As we know that all programming language compilers convert the source
code to machine code. Same job done by Java Compiler to run a Java
program, but the difference is that Java compiler convert the source code
into Intermediate code is called as bytecode. This machine is called the
Java Virtual machine and it exists only inside the computer memory.
Java Object Framework act as the intermediary between the user programs and the
virtual machine which in turn act as the intermediary between the operating system
and the Java Object Framework.
Java Environment

Java environment includes a number of development tools, classes


and methods. The development tools are part of the system known
as Java Development Kit (JDK) and the classes and methods are
part of the Java Standard Library (JSL), also known as the
Application Programming Interface (API).
JDK (Java Development kit)

The Java Development kit comes with a collection of tools that are used for
developing and running java programs. They include:

 Applet Viewer: Enable us to run java applets (without actually using a java
compatible browser)
 Java: Java interpreter, which runs applets and applications by reading and
interpreting byte code files
 Javac: The java compiler, which translates java source code to byte code files
that interpret, can understand.
 Javadoc: Creates HTML format documentation from java source code files

 Javah: Produces header files for use with native methods

 Javap: Java disassembler, which enables us to convert byte code files into program
description.

 Jdb: Java debugger, which helps us to find errors in Java program


Application programming interface API
The Java Standard Library contain (or API) contains hundreds of classes and methods
grouped into several functional packages. Most commonly used packages are

1. Language Support Package: A collection of classes and methods needed for


implementing basic features of java.
2. Utility Package: A collection of classes to provide utility functions such as date and
time functions.
3. Input/output Packages: A collection of classes and methods needed for I/O
manipulation.
4. Network Package: A collection of classes needed for communicating with other
computers via Internet.
5. AWT Package: A collection of classes needed for implementing Graphical User
interface.
6. Applet Package: A collection of classes and methods needed to create java applets.
Overview

Two types of java programs


1. Stand alone applications: Stand alone applications are programs written in java
to carry out certain tasks on standalone local computer. Executing a Standalone
applications involves two steps
 Compiling source program into byte code using javac compiler
 Executing the bytecode program using java interpreter.

2. Web applets: Applets are small java programs developed for Internet applications.
An applet located on remote computer can be downloaded via Internet and executed
on a local computer using java enabled browser.
Stand alone programs can read and write files and perform certain operations that
applet cannot do. An applet can only run within a web browser.
Simple Java Program
 This program defines a class called ―FirstProgram. A class is an object oriented
term. It is designed to perform a specific task. A Java class is defined by its class
name, an open curly brace, a list of methods and fields, and a close curly brace.
 The line ―public static void main (String [] args) - shows where the program
will start running. The word main means that this is the main method –
 The public keyword is an access modifier. When a class member is preceded by
public, then that member can be accessed by code outside the class in which it is
declared.
 The keyword static allows main( ) to be called before an object of the class has
been created. This is necessary because main( ) is called by the JVM before any
objects are made.
 The keyword void simply tells the compiler that main( ) does not return a value.
 In main( ) there is only one parameter, String args[ ], which declares a
parameter named args. This is an array of objects of type String. (Arrays are
collections of similar objects.) Objects of type String store sequences of
characters. In this case, args receives any command-line arguments present when
the program is executed.

System.out.println("This is my first program");

The statement outputs the character between quotes to the console.


Java Program Structure
Documentation Section: This section contains set of comment lines giving the name of
the program, the author, etc.
Package Statement: the first statement allowed in java file is a package statement. This
statement declares a package name and informs the compiler that the classes defined here
belong to this package.
Example: package student;
Import Statements: The next after the package statement may be number of import
statements. For example: import student.test;
This statement instructs the compiler to load the test lass contained in the package student.
Interface Statements: An interface is like a class but includes a group of method
declarations.
Class Definitions: A java program may contain multiple class definitions.
Main Method Class: Every java stand alone program needs a main method as its starting
point.
Java Tokens
 Reserved words
Keywords have specific meaning in Java. We cannot use them as variable, classes
and method(abstract, char, do, try, throw…)
 Identifiers
 Literals
Liter als are a sequence of characters (digits, letters and other
characters)characterize constant values to be stored in variables.
 Operators
Operators are used in programs to operate data and variables. They frequently
form a part of mathematical or logical expressions.
 Separators
Keywords:
Java language has reserved 50 words as keywords. Keywords have specific meaning in
Java. We cannot use them as variable, classes and method.
Identifiers

Identifiers are programmer-created tokens. They are used for naming classes,
methods, variables, objects, labels, packages and interfaces in a program. Java
identifiers follow the following rules:
 They can have alphabets, digits, and the underscore and dollar sign
characters.
 They must not start with a digit.
 Uppercase and lowercase letters are individual.
 They can be of any length.
 Identifier must be meaningful, easily understandable and descriptive.
Literals
Literals are a sequence of characters (digits, letters and other characters)
that characterize constant values to be stored in variables. Java language
specifies five major types of literals are as follows:
1. Integer literals
2. Floating point literals
3. Character literals
4. String literals
5. Boolean literals
Operator
Java carries a broad range of operators. An operator is symbols that specify operation to be
performed may be certain mathematical and logical operation. Operators are used in programs
to operate data and variables. They frequently form a part of mathematical or logical
expressions. Categories of operators are as follows:
1. Arithmetic operators
2. Logical operators
3. Relational operators
4. Assignment operators
5. Conditional operators
6. Increment and decrement operators
7. Bit wise operators
Separator
Separators are symbols. It shows the separated code.
Java Statements

A statement is an executable combination of tokens ending with a semicolon (;).


Comments

 A comment is a note written to a human reader of a program.


 The program compiles and runs exactly the same with or without comments.
 Comments start with the two characters // (slash slash). Those characters and
everything that follows them on the same line are ignored by the java compiler.
 Everything between the two characters /*and the two characters */ are unobserved
by the compiler.
 There can be many lines of comments between the /* and the */.
Command Line Arguments:

Command line arguments are parameters that are supplied to the application
program at the time of invoking its execution. They must be supplied at the time of
its execution following the file name.
In the main () method, the args is confirmed as an array of string known as string
objects. Any argument provided in the command line at the time of program
execution, are accepted to the array args as its elements. Using index or
subscripted entry can access the individual elements of an array. The number of
element in the array args can be getting with the length parameter.
class Add
{
public static void main(String args[])
{
int a=Integer.parseInt(args[0]);
int b=Integer.parseInt(args[1]);
int c=a+b;
System.out.println(“Addition is=” +c);
}
Output:
}
c:\javac Add.java
c:\java Add 5 2->Command Lime
arguments
Addition is=7
Constants

Constant means fixed value which cannot be changed at the time of execution of
program. In Java, there are two types of constant as follows:

 Numeric Constants
a. Integer constant
b. Real constant
 Character Constants
a. Character constant
b. String constant
a) Decimal integer b) Octal integer c) Hexadecimal
Embedded spaces, It allows any integer
commas and sequence of ‘F‘ or ’a‘ to ‘f‘ (‘A‘ to
characters are not numbers or digits ‘F‘ stands for the
allowed in between from 0 to 7 with numbers ‘10‘ to ‘15‘)
digits. leading 0 and it is it is called as
called as octal Hexadecimal integer.
integer.
For example: For example:
23 411 For example: 0x7
7,00,000 011 00X
00 0A2B
17.33
0425
a. Real Constant b. Character c. String
It allows us fractional Constant Constant
data and it is also It allows us single It allows us the
called as floating character within series of characters
point constant. It is pair of single coute. within pair of
used for percentage, double coute.
height and so on. For example:
‘A‘ For example:
For example: ‘7‘ “WELCOME”
‘\‘ “END OF
0.0234
PROGRAM”
0.777 “BYE …BYE”
-1.23 “A”
Symbolic constant
There are many things which is requires repeatedly and if we want to make changes
then we have to make these changes in whole program where this variable is used.
For this purpose, Java provides ‘final‘keyword to declare the value of variable as
follows:

Syntax:
final type Symbolic_name=value;
For example:
For declaring PI value:
final float PI=3.1459;
Backslash character constant
Variables
Variables are labels that express a particular position in memory and connect it
with a data type.
The first way to declare a variable: This specifies its data type, and reserves
memory for it. It assigns zero to primitive types and null to objects.

dataType variableName;

The second way to declare a variable: This specifies its data type, reserves
memory for it, and puts an initial value into that memory. The initial value must be
of the correct data type.
dataType variableName = initialValue;
The first way to declare two variables: all of the same data type, reserves memory for
each.

dataType variableNameOne, variableNameTwo;


The second way to declare two variables: both of the same data type, reserves memory,
and put an initial value in each variable.

dataType variableNameI = initialValueI, variableNameII=initialValueII;


Variable name
Use only the characters ‘a‘ through ‘z‘, ‘A‘ through ‘Z‘, ‘0‘ through ‘9‘, character ‘_‘,
and character ‘$‘.

 A name cannot include the space character.


 Do not begin with a digit.
 A name can be of any realistic length.
 Upper and lower case count as different characters.
 A name cannot be a reserved word (keyword).
Data types:

A data type is a scheme for representing values.


An example is int which is the Integer, a data type values are not just numbers, but
any manner of data that a computer can process.
The data type defines the kind of data that is represented by a variable.
As with the keyword class, Java data types are case sensitive.

There are two types of data types


a) Primitive data type
b) Non-primitive data type
In primitive data types, there are two categories
a) Numeric i.e, Integer, Floating points
b) Non-numeric i.e, Character and Boolean

In non-primitive types, there are three categories


a) classes
b) arrays
c) interface
Integer data type: Integer datatype can hold the numbers (the number can be
positive number or negative number).
In Java, there are four types of integer as follows:
a) byte
b) short
c) int
d) long
We can make integer long by adding ‘l‘ or ‘L‘ at the end of the number.
Floating point data type: It is also called as Real number and when we
require accuracy then we can use it.
There are two types of floating point data type.
a) Float
b) Double

It is represent single and double precision numbers. The float type is used
for single precision and it uses 4 bytes for storage space. It is very useful
when we require accuracy with small degree of precision. But in double
type, it is used for double precision and uses 8 bytes of starage space. It is
useful for large degree of precision.
Character data type: It is used to store single character in memory. It uses 2
bytes storage space.

Boolean data type


 It is used when we want to test a particular condition during the execution of
the program.
 There are only two values that a boolean type can hold:
true and false.
 Boolean type is denoted by the keyword boolean and uses only one bit of
storage.
Scope of Variable
3 Types:
Instance and class variable are declared inside a class. Instance variables are created
when the objects are instantiated and there for they are associated with objects. They
take different values for each object.

Class variables are global to a class and belong to entire set of objects that class
creates. Only one memory location is created for each class variable.

Variables declared and used inside methods are called local variables. They are not
available outside the method definition.
Standard Default Values
Operators

An operator is symbols that specify operation to be performed may be


certain mathematical and logical operation. Operators are used in
programs to operate data and variables. They frequently form a part of
mathematical or logical expressions.
Arithmetic operators
Arithmetic operators are used to
make mathematical expressions
and the working out as same in
algebra. Java provides the
fundamental arithmetic operators
Increment and Decrement Operators:
The increment operator ++ adds 1 to a variable. Usually the variable is an integer type,
but it can be a floating point type. The two plus signs must not be split by any character.
Usually they are written immediately next to the variable
Relational Operators:

When evaluation of two numbers is performed depending upon their relation, assured
decisions are made. The value of relational expression is either true or false.
If A=7 and A < 10 is true while 10 < A is false. Following table shows the details of
operators.
Logical operators
When we want to form compound conditions by combining two or more
relations, then we can use logical operators.
Assignment Operators
Assignment Operators is used to assign the value of an
expression to a variable and is also called as Shorthand
operators.

Variable_name binary_operator = expression


Conditional Operators

The character pair ?: is a ternary operator of Java, which is used to


construct conditional expressions of the following form:

Expression1 ? Expression3 : Expression3

The operator ? : works as follows: Expression1 is evaluated if it is


true then Expression3 is evaluated and becomes the value of the
conditional expression. If Expression1 is false then Expression3 is
evaluated and its value becomes the conditional expression.
Program to check whether number is positive or negative.
class PosNeg
{
public static void main(String args[])
Shift Operator
Special Operators
Java supports some special operators such as instanceof operator and member selection
operator (.).
1. Instanceof Operator:
The instanceof is an object reference operator and returns true if the object on
the left hand side is an instance of the class given on the right hand side. This operator
allows us to determine whether the object belongs to a particular class or not.
Example:
person instaceof student;
is true if the object person belongs to the class student; otherwise it is false
2. Dot Operator
The dot operator is used to access the instance variable and methods of class objects.

Examples:
person. age;
person. salary();

It is also used to access classes and sub packages from a package.


Operator Precedence
An arithmetic expression without any parentheses will be calculated from left to right
using the rules of precedence of operators.
There are two priority levels of arithmetic operators are as follows:
(a) High priority (* / %)
(b) (b) Low priority (+ -)

The evaluation process includes two left to right passes through the expression. During
the first pass, the high priority operators are applied as they are encountered. During the
second pass, the low priority operators are applied as they are encountered.
Example
Type Conversion in Assignment

 When different types of data are mixed within an expression,


they are all converted to the same type. This is accomplished
through the use of java’s type promotion rules.
 First all char byte and short values are promoted to int.
 If one operand is a long the whole expression is promoted to
long.
 If one operand is a float operand the entire expression is
promoted to float.
 If double then result is double.
 Type promotion only affects the evaluation of n expression.
When one type of data is assigned to another
type of variable an automatic type conversion will
take place if
1. The two types are compatible.
2. The destination type is larger than the source
type. When these two conditions are met a
widening conversion takes place.
Casting Incompatible Types
A cast is an instruction to the compiler to convert one datatype into another datatype. Its
general form is (target-type) expression

Example:
double x, y;
//…
(int ) (x/y) -> x and y are double but result is converted to int.
Mathematical Functions

Mathematical functions such as cos, sin, log, etc. are frequently used in an analysis of
real life problems. Java supports these basic math functions through Math class defined in
the java.lang package.
Using I/O
Java input and output are based on the use of streams, or sequences of bytes that travel
from a source to a destination over a communication path.
If a program is writing to astream, you can consider it as a stream’s source. If it is reading
from a stream, it is the stream’s destination. The communication path is dependent on
the type of I/O being performed.
It can consist of memory-to-memory transfers, a file system, a network, and other forms
of I/O.
Streams are powerful because they abstract away the details of the communication path
from input and output operations. This allows all I/O to be performed using a common set
of methods. These methods can be extended to provide higher-level custom I/O
capabilities.
Three streams given below are created automatically:
 System.out - standard output stream
 System.in - standard input stream
 System.err - standard error
Stream
 Stream is the logical connection between Java program and file.
 Stream is basically a sequence of bytes, which has a continuous flow between Java
programs and data storage. All streams behave in the same manner, even if the
actual physical devices to which they are linked differ. Thus, the same I/O classes and
methods can be applied to any type of device.
 An input stream can abstract many different kinds of input: from a disk file, a
keyboard, or a network socket.
 An output stream may refer to the console, a disk having every part of your code
understand the difference between a keyboard and a network, file, or a network
connection.
 Java provides many input and output stream classes which are used to read and write.
Streams are of two types.
1. Byte Stream
2. Character Stream
Byte stream Classes
Used in the input and output of byte. We do this with the help of different Byte stream
classes.
Groups
 InputStream Classes - These classes are subclasses of an abstract
class,InputStream and they are used to read bytes from a source(file,
memory or console).

 OutputStream Classes - These classes are subclasses of an abstract


class,OutputStream and they are used to write bytes to a
destination(file, memory or console).
The Character Stream Classes

Character streams are defined by using two class hierarchies. At the top
are two abstract classes, Reader and Writer. These abstract classes handle
Unicode character streams. Java has several concrete subclasses of each of
these. The character stream classes are shown in Table.

The abstract classes Reader and Writer define several key methods that the
other stream classes implement. Two of the most important methods are
read() and write(), which read and write characters of data, respectively.
These methods are overridden by derived stream classes.
The Predefined Streams

 This package defines a class called System, which encapsulates


several aspects of the run-time environment.
 For example, using some of its methods, you can obtain the
current time and the settings of various properties associated
with the system.
 System also contains three predefined stream variables: in, out,
and err.
 These fields are declared as public, static, and final within
System. This means that they can be used by any other part of
your program and without reference to a specific System object
System.out refers to the standard output stream. By default, this is the console.
System.in refers to standard input, which is the keyboard by default.

System.err refers to the standard error stream, which also is the console by default.
However, these streams may be redirected to any compatible I/O device.

System.in is an object of type InputStream; System.out and System.err are objects of


type PrintStream. These are byte streams, even though they typically are used to read
and write characters from and to the console. It can wrap these within character- based
streams, if desired.
Reading Console Input
 Using a byte stream to read console input is still technically possible, but doing so is
not recommended.
 The preferred method of reading console input is to use a character-oriented stream,
which makes your program easier to internationalize and maintain.
 console input is accomplished by reading from System.in. To obtain a character- based
stream that is attached to the console, wrap System.in in a BufferedReader object.
 BufferedReader supports a buffered input stream. Its most commonly used
constructor is shown here:
BufferedReader(Reader inputReader)
 Input Reader is the stream that is linked to the instance of BufferedReader that is
being created. Reader is an abstract class. One of its concrete subclasses is
InputStreamReader, which converts bytes to characters. To obtain an
InputStreamReader object that is linked to System.in, use the following constructor:
Input StreamReader(InputStream inputStream)

 Because System.in refers to an object of type InputStream, it can be used for


inputStream. Putting it all together, the following line of code creates a
BufferedReader that is connected to the keyboard:
BufferedReader br = new BufferedReader (new
InputStreamReader (System.in));

 After this statement executes, br is a character-based stream that is linked to the


console through System.in.
Reading Characters

 To read a character from a BufferedReader,


use read(). The version of read() that we
will be using is int read() throws
IOException Each time that read() is called,
it reads a character from the input stream
and returns it as an integer value. It
returns -1 when the end of the stream is
encountered. As you can see, it can throw
an IOException.
Reading Strings

To read string from keyboard we


use readLine() that is a member of
the BufferedReader class. Its
general form i String readLine()
throws IOException it returns String
object.
Writing Console Output

 Console output is most easily accomplished with print() and println().


 These methods are defined by the class PrintStream (which is the type of object
referenced by System.out). Even though System.out is a byte stream, using it for
simple program output is still acceptable. Because PrintStream is an output stream
derived from OutputStream, it also implements the low-level method write(). Thus,
write() can be used to write to the console.
 The simplest form of write() defined by PrintStream is shown here: void write(int
byteval) This method writes to the stream the byte specified by byteval. Although
byteval is declared as an integer, only the low-order eight bits are written.
DECISION MAKING AND BRANCHING
Set of statements which are executed sequentially in an order which they appear. In that
statements, some calculations need to be executed with some conditions for that we
have to provide control to that statements. In other words, Control statements are used
to provide the flow of execution with condition.
When a program breaks the sequential flow, and jumps to another part of code it is called
branching. When branching is based on particular condition it is called conditional
branching. If branching is not based on any condition it is called as unconditional
branching.

There are 3 types:


1. if statements
2. switch statement
3. Conditional Operator Statement
Simple if statement

Syntax:
If(Test condition)
{statement block;}
Statement-x;

 In statement block, there may be single statement or multiple statements.


 If the test condition is true then statement block will be executed.
 If the condition is false then statement block will omit and statement-x will be
executed.
if---else statement

Syntax:
If(Test expression)
{true block
Statement(s)}
Else
{false block
Statement(s)}

If the test expression is true, then true-block Statements(s) are executed; otherwise
false-block Statements(s) are executed.
Nested if---else statement
Syntax:
If(Test expression 1)
{If(Test condition 2)
{Statements-1}
Else
{Statements-2}
Else
{Statements-3}
Statement x

If the test expression -1 is true then it will go to condition2. If the condition2 is true
then statement -1 will be executed otherwise statement-2 will be executed. If the test
expression -1 is false then statement-3 will be executed. In both cases the statement-x
will always executed.
else if ladder
Syntax:
if (condition1)
Statement-1;
else if (condition2) Here the conditions are evaluated from top to
downwards. As soon as true condition is found
Statement-2; the statements associated with it is executed
else if (condition3) and the control is transferred to the statement
– x by skipping the rest of the ladder. When all
Statement-3; ……………………… ……... conditions become false, the final else
else if (condition n) containing the default- statement will be
executed.
Statement-n;
Else
default – Statement
Statement - x
Switch statement

Switch statement check the value of given


variable or statement against a list of case
values and when the match is found a
statement-block of that case is executed. Its
also called as multiway decision statement.
 The condition is byte, short, character or an integer.
 value-1,value-2,value-3,…are constant and is called as labels. Each of these values
must be matchless or unique with the statement.
 Statement block1, Statement block2, Statement block3,..are list of statements which
contain one statement or more than one statements.
 Case label is always end with “:” (colon).
 When the switch is executed the value of the expression is successively compared
against the values value-1, value-2, … If a case is found whose value matches with the
value of the expression then the block of statements that fallows the case are
executed.
 The break statement at the end of each block indicates the end of a particular case
and cause to exit from the switch.
 The default as an optional case. When present it will be executed if the value of the
expression does not match with any of the case values
Conditional Operators ?:

A ternary operator of Java, which is used to construct conditional expressions of the


following form

Expression1 is evaluated if it is true then Expression2 is evaluated and becomes the


value of the conditional expression. If Expression1 is false then Expression3 is evaluated
and its value becomes the conditional expression

You might also like