You are on page 1of 84

Java Programming

R. Ravi Kumar
Introduction to Java

2
Introduction to Java
OOPs Concepts
Need for Different Approach in Modern Programming
 Since the invention of the computer, Many programming
approaches have been tried.
 Modular, Top-down, Bottom-up, and Structured
Programming.
 The primary motivation is to handle increasing complexity
of programs that are reliable and maintainable.
 With languages such as C, Structured programming
became very popular.
 As the programs grew larger, even the structured approach
failed in terms of bug-free, easy-to-maintain, and reusable
programs.

3
Introduction to Java
OOPs Concepts
 Object Oriented Programming (OOP) is an approach to
program organization and development, which
attempts to eliminate some of the pitfalls of
conventional languages.
 It incorporates the best features of structured
programming with several new features.
 Languages that support OOP features – Smalltalk,
Objective C, C++, Ada, and Object Pascal.
 The latest one added to this list is Java and C#
4
Introduction to Java
OBJECT-ORIENTED PARADIGM
 OOP treats data as a critical element
Method Method
and does not allow it to flow freely
around the system. Data
 It ties data more closely to the Method Method
functions that operate on it and
protects it from unintentional
modification by other functions.
 OOP allows to decompose a problem in to number of
entities called Objects and build data and functions
around these entities.
 Object = Data + Methods 5
Introduction to Java
OOPs Features:
 Emphasis is on data rather than procedure.
 Programs are divided into what are known as Objects.
 Methods that are operate on the data of an object are tied
together in the data structure.
 Data is hidden and 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.

6
Introduction to Java
OOPs Definition:
Object-oriented programming is an approach that provides a
way of modularizing programs by creating partitioned memory
area for both data functions that can be used as templates for
creating copies of such modules on demand.

 This means that an object is considered to be a partitioned


area of computer memory that stores data and a set of
operations that can access that data.
 Since the memory partitions are independent, the objects can
be used in a variety of different programs without
modificatons.
7
Introduction to Java
Objects and Classes:
 Objects are the basic runtime entities in an object-oriented
system.
 Objects contain data and code to manipulate that data.
 They may represent a person, a place, a bank account, a table
of data or any items that the program may handle.
 Program objects should be chosen such that they match
closely with the real-world objects.
 An object takes up space in memory and has an associated
address.
 The objects interact by sending messages to one another.
8
Introduction to Java
Objects and Classes:
 Objects contain data and code to manipulate that data.
 The entire set of data and code of an object can be made a
user-defined data type using the concept of a class.
 Class may be thought of as a ‘data type’ and an object as a
‘variable’ of that data type
 Once a class has been defined, any number of objects can be
created belonging to that class.

“A class is a collection of objects of similar type”

9
Introduction to Java
Data Abstraction and Encapsulation:
“Wrapping up of data and methods into a single unit (called
class) is known as encapsulation”
“Insulation of the data from direct access by the program is
called data hiding”

 Encapsulation makes it possible for object to be treated like


“black boxes”, each performing a specific task without any
concern for internal implementation.

10
Introduction to Java
Inheritance:
“Inheritance is the process by which one object acquires the
properties of objects of another class”
Bird

Attributes:
Feathers
• Reusability Lay Eggs

• Add additional features to Flying Bird Non Flying Bird

an existing class without Attributes: Attributes:


----------- -------------
modifying it ----------- -------------

Robin Swallow Penguin Kiwi

Attributes: Attribute: Attribute: Attribute:


--------------- ----------------- ---------------- ------------------
11
Introduction to Java
Polymorphism: (from the Greek, meaning “many forms”
“Polymorphism means the ability to take more than one form. ”

Shape

Draw ( )
• Reusability
Circle Object Box Object Triangle Object
• Add additional features to Draw (circle) Draw (box) Draw (triangle)
an existing class without
modifying it

12
Introduction to Java
Applications of OOP:
 Real-time systems
 Simulation and modeling
 Object-oriented database
 Hypertext, hypermedia
 AI and expert systems
 Neural networks and parallel programming
 Decision support and office automation systems
 CIM/CAD/CAD system

13
Introduction to Java
JAVA Evolution:
 Java was conceived by James Gosling, Patrick Naughton, Chris Warth,
Ed Frank, and Mike Sheridan at Sun Microsystems, Inc. in 1991.
 Initially called “Oak” but was renamed as “Java” due to legal issues.
 1992 – The team, known as Green Project team by Sun, demonstrated
the application of their new language to control a list of home
appliances.
 1993 – Due to popularity of World Wide Web, the Green Project team
came up with the idea of developing Web applets using JAVA.
 1994 – The team developed a Web browser called “HotJava” to locate
and run applet programs on Internet.
 1995 – Oak was renamed as “Java”.
14
Introduction to Java
JAVA Features:
 Compiled and Interpreted
 Platform-Independent and Portable
 Object-Oriented
 Robust and Secure
 Distributed
 Familiar, Simple and Small
 Multithreaded and Interactive
 High Performance
 Dynamic and Extensible 15
Introduction to Java
Overview of JAVA development process:

 Usually a computer language is either compiled or


interpreted.
 Java combines both these approaches – making Java a two-
stage system.
 Java compiler translates source code into intermediate code
known as bytecode instructions.
 In the second stage, Java interpreter generate machine code
that can be directly executed by machine. 16
Introduction to Java
JVM: Java Virtual Machine

17
Introduction to Java
JAVA Environment:
 It includes a large number of development tools and
hundreds of classes and methods.
 The development tools are part of the system known as Java
Development Kit (JDK)
 The classes and methods are part of the Java Standard
Library (JSL), also known as the Application Programming
Interface (API)

18
Introduction to Java
JAVA Environment:
 The Java Development Kit comes with a collection of tools
that are used for developing and running Java programs.
 Applet viewer – for viewing Java applets
 Javac – Java Compiler
 Java – Java interpreter
 Javap – Java disassembler
 Javah – for C header files
 Javadoc – for creating HTML documents
 Jdb – Java debugger 19
Introduction to Java
JAVA Version History:
 JDK 1.0 (January 23, 1996)
 JDK 1.1 (February 19, 1997)
 J2SE 1.2 (December 8, 1998)
 J2SE 1.3 (May 8, 2000)
 J2SE 1.4 (February 6, 2002)
 J2SE 5.0 (September 30, 2004)
 Java SE 6 (December 11, 2006)
– Java SE 6 Update 10
– Java SE 6 Update 11
– Java SE 6 Update 12
– Java SE 6 Update 14
– Java SE 6 Update 16
– Java SE 6 Update 17

 Java SE 7 20
Introduction to Java
Process of Building and Running Java Application programs:
Text Editor

Java Source HTML


Code Javadoc
Files
Javac

Java Class Header


File Javah Files

Java jdb

Java Program
Output
21
Introduction to Java
Two Ways of using Java:
Java Source
Code

Java Compiler

Java enabled
Java Interpreter
Web Browser

Output Output

22
JDK Editions
 Java Standard Edition (J2SE)
– J2SE can be used to develop client-side standalone
applications or applets.
 Java Enterprise Edition (J2EE)
– J2EE can be used to develop server-side applications such
as Java servlets and Java ServerPages.
 Java Micro Edition (J2ME).
– J2ME can be used to develop applications for mobile
devices such as cell phones.

We are going to use J2SE to introduce Java


programming.
23
Introduction to Java
Simple Java Program:
/*
This is a simple java program.
Call this file “Example.java”
*/
class Example
{
//Program begins with a call to main().
public static void main (String args[ ])
{
System.out.println(“Welcome to Java!!!!”);
}
}

24
Introduction to Java
General Structure of a Java program:

Documentation Section Suggested

Package Statement Optional

Import Statements Optional

Interface Statements Optional

Class Definitions Optional


Main Method class
{ Essential
Main Method Definition
}
25
Introduction to Java
A closer look:
Java comment:
 Lets you enter a remark into a program’s source file.
 The contents of a comment are ignored by the compiler.
 Java supports three styles of comments.
1. Multiline comment - /*--------------- */
2. Single line comment - // --------------
3. Documentation Comment - /** ---------- */

The Documentation comment is used to produce an HTML file


that documents your program.

26
Introduction to Java
A closer look:
Next Line:
 The keyword class is used to declare that a new class is
being defined and Example is an identifier that is the name
of the class.
 The entire class definition, including all of its members, will
be between he opening curly brace ({) and the closing curly
brace (}).
 The next line in the program is the single-line comment.

27
Introduction to Java
A closer look:
Next Line:
 The next line of the code is:
Public static void main (String args[ ])
 This line begins the main () method. This is the line at which
the program will begin executing
 public keyword is an access specifier, which allows the
programmer to control the visibility of class members.
 static keyword allows main() to be called without having to
instantiate a particular instance of the class.
 void tells the compiler that main() does not return a value.

28
Introduction to Java
A closer look:
Next Line:
 String args [ ] is a parameter inside main().
 It declares a parameter named args, which is an array of
instances of the class String.
 args receives any command-line arguments present when the
program is executed.
 The next line is
System.out.println(“Welcome to java!!!!!!”);
 This line outputs the string “Welcome to java!!!!!” followed
by new-line on the screen.

29
Introduction to Java
A closer look:
Next Line:
 Output is accomplished by the built-in println() method.
 System is a predefined class that provides access to the
system, and out is the output stream that is connected the
console.
 Note that println() statement ends with a semicolon. All
statements in java end with a semicolon.

30
Introduction to Java
Second Example:
Example2.java:
 This example demonstrates the use of variable.
 A variable is a named memory location that may be
assigned a value by you.
class Example2 {
public static void main (String args [ ])
{
int num; //this declares a variable called num
num = 200; // this assigns num the value 200
System.out.println(“This is num: “ +num);
num = num*2;
System.out.print(“The value of num *2 is “);
System.out.println(num);
}
31
}
Data types, operators
Constants, Variable:
Constants:
 Constants in Java refers to fixed values that do not change
during the execution of a program.
 Java supports:- Syntex for declaring constant:
 Integer Constants final data_type constant_name
 Real Constants
 Single Character Constants
 String Constants
 Backslash Character Constants

32
Data types, operators
Constants, Variable:
Constants:

Java Constants

Numeric Constants Character Constants

Integer Real Character String


Constants Constants Constants Constants

33
Data types, operators
Constants, Variable:
Constants:
Integer Constants:
 It refers to sequence of digits.
 Three types of integers:-
 Decimal
 Octal
 Hexadecimal

Decimal: Consists of a set of digits, 0 through 9, preceded by an


optional minus sign.
Ex: 1223 -258 0 365656
34
Data types, operators
Constants, Variable:
Constants:
Octal Integer Constants:
 Consists of any combination of digits from the set 0 through
7, with a leading 0.
Ex: 037 0 0456 054

Hexadecimal Integer Constant:


 A sequence of digits preceded by 0x or 0X .
 They may also include alphabets A – F for numbers 10
through 15.
Ex: 0X2 0X9F 0xbcd 0x
35
Data types, operators
Constants, Variable:
Constants:
Real Constants:
 Representation of numbers containing fractional parts.
Ex: 0.0054 -0.85 500.555
 The real number may also be expressed in exponential
notation.
 For example: 321.12 may be written as 3.2112e2
 e2 means multiply by 102
mantissa e exponent
 The mantissa is either real number in decimal notation or an
integer.
 A real constant may contain: a whole number, a decimal
point, a fractional part, and an exponent 36
Data types, operators
Constants, Variable:
Constants:
Single Character Constants:
 A character constant contains a single character enclosed
within a pair of single quote marks.
Ex: ‘5’ ‘A’ ‘;’ ‘’

String Constants:
 A string constant is a sequence of characters enclosed
between double quotes.
 The characters may be alphabets, digits, special characters
and blank spaces.
Ex: “nift” “2010” “JAVA” “!....?” “6+4”
37
Data types, operators
Constants, Variable:
Constants:
Backslash Character Constants:
 Java supports some special backslash character constants
that are used in output methods also known as escape
sequences.
‘\b’ -- back space
‘\f’ -- form feed (printer devices)
‘\n’ -- new line
‘\r’ -- carriage return
‘\t’ -- horizontal tab
‘\’’ -- single quote
‘\”’ -- double quote
‘\\’ -- backslah
38
Data types, operators
Constants, Variable:
Variables:
 Variable is an identifier denotes a storage location used to store a data
value.
 Variable name can be chosen by the programmer in a meaningful way
so as to reflect what it represents in the program.
 Variable names may consists of alphabets, digits, the underscore and
dollar characters, subject to the following conditions:-
 They must not begin with a digit
 Uppercase and lowercase are distinct
 Should not be a keyword
 White space is not allowed
 Variable names can be of any length

39
Data types, operators
Constants, Variable:
Data types:
 Java is strongly Typed language.
 Java’s safety and robustness comes from this fact.
 Every variable in Java has a data type that specifies the size and type of
value that can be stored.
DATA TYPES IN JAVA

Primitive Non-Primitive
(intrinsic) (Derived)

Numeric Non-Numeric Classes Arrays

Integer Floating-point Character Boolean Interfaces

40
Data types, operators
Constants, Variable:
Data types:
 Java defines eight simple types of data: byte, short, int, long,
char, float, double, and boolean. These can be put in four
groups.
 Integers: byte, short, int, long – for whole valued signed
numbers
 Floating-point: float and double – numbers with fractional
precision
 Character: char – symbols in character set, like letters and
numbers
 Boolean: boolean – for representing true / false

41
Data types, operators
Constants, Variable:
Data types:
Integers:
 byte, short, int, and long
 unsigned integer type was eliminated in Java
Name Width Range
long 64 -9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
int 32 -2,147,483,648 to 2,147,483,647
Short 16 -32,768 to 32,767
byte 8 -128 to 127

We can append letter ‘L’ or ‘l’ at the end of the number for long data type
42
Data types, operators
Constants, Variable:
Data types:
Floating Point:
 Also known as real numbers
 Expressions require fractional precision.
Name Width Range
double 64 4.9e-324 to 1.8e+308
float 32 1.4e-045 to 3.4e+038

43
Data types, operators
Constants, Variable:
Data types:
Characters:
 The data type used to store characters is ‘char’
 Java is not same as char in C or C++. Java uses Unicode
to represent characters.
Name Width Range
char 16 0 to 65,536

44
Data types, operators
Constants, Variable:
Data types:
Boolean:
 For logical values
 It can have only one of two possible values, true or false.
Ex:
boolean c;
boolean d;

45
Data types, operators
Constants, Variable:
Declaration of Variables:
 A variable must be declared before it is used in program.
 A variable can be used to store a value of any data type.
 Declaration does three things,
 It tells the compiler what the variable name is
 It specifies what type of data the variable will hold
 The place of declaration decides the scope of the variable.

Syntax for declaring variable:


data_type variable1, variable2, variable3,…..variableN;

46
Data types, operators
Constants, Variable:
Assigning Value to a Variable:
 Variable must be given a value after it has been declared
but before it is used in an expression.
 It can be done by,
 By using an assignment statement.
 By using a read statement at runtime
Using Assignment Statement:
variableName = value;
Ex: myinteger = 100;
It is also possible to assign a value to a variable at the time of its declaration
data_type variableName = value;
47
Data types, operators
Constants, Variable:
Assigning Value to a Variable:
Using Read Statement: (JDK 1.4.0)
import java.io.DataInputStream;
class read{
public static void main (String args[])
{
DataInputStream in = new DataInputStream(System.in);
Int intNumber = 0;
Float floatNumber = 0.0;
try{
System.out.println(“Enter an Integer: “);
intNumber = Integer.parseInt(in.readLine());
System.out.println(“Enter a float number: “);
floatNumber = Float.valueOf(in.readLine()).floatValue();
}
Catch (Exception e){ }
System.out.println(“intNumber = “ + intNumber);
System.out.println(“floatNumber = “ + floatNumber);
}
48
}
Data types, operators
Constants, Variable:
Assigning Value to a Variable:

Using Read Statement:

 JDK 1.5.0 – introduced with Scanner in place of DataInputStream

 JDK 1.6.0 – introduced with Console to deal with console input

49
Data types, operators
Using Read Statement: (JDK 1.6.0)
import java.io.Console;
class console{
public static void main (String args[])
{
Console console = System.console();

//read user name, using java.util.Formatter syntax :

String username = console.readLine("User Name? ");

//read the password, without echoing the output


char[] password = console.readPassword("Password? ");

int i=0;
String getpassword = "";

while(i <= 3)
{
getpassword = getpassword+password[i];
i++;
} 50
Data types, operators
Using Read Statement: (JDK 1.6.0)

if(username.equals("Admin") && getpassword.equals("nift"))


{
console.printf("Welcome, %1$s.", username);
}
else
{
console.printf("You have typed wrong Username and password!" );
}
}
}

51
Data types, operators
Constants, Variable:
Scope of Variable:
 Java variables are classified into ,
 instance variable
 class variable
 local variable

 Instance and Class variables are declared inside a class.


 Instance variables are created when objects are instantiated and
they are associated with objects.
 Class variables are common to all the objects and accessed without
using a particular object.
 Variables declared and used inside methods are called local variable
 Local variables are not visible outside the methods within the class.
52
Data types, operators
Constants, Variable:
Symbolic Constants:
 Symbolic names take the same form as variable names. But, they
are witten in CAPITALS to visually distinguish them from normal
variables
 After declaration, they should not be assigned any other value by
using an assignment statement.
 Symbolic constants are declared for types.
 They can not be declared inside a method. They should be used only
as class data members in the beginning of the class.

Ex:
final int LENGTH = 100;
final float PI = 3.14159;

53
Data types, operators
Constants, Variable:
Type Casting:
 To store a value of one type into a variable of another type.
 The value to be stored by proceeding it with the type name in
parantheses.
type variable1 = (type) variable2;
Ex:
int m = 50;
byte n = (byte) m;

 Casting to smaller type can result in a loss of data.


 Casting a floating point value to an integer will result in a
loss of the fractional part.

54
Operators and Expressions

 Java supports a rich set of operators.


 Arithmetic operators
 Relational operators
 Logical operators
 Assignment operators
 Increment and decrement operators
 Conditional operators
 Bitwise operators
 Special operators

55
Operators and Expressions
Arithmetic operators:
Operator Meaning
+ Addition or unary plus
- Subtraction or unary minus
* Multiplication
/ Division
% Modulo division

 Integer arithmetic
 Real arithmetic
 Mixed-mode arithmetic

56
Operators and Expressions
Relational operators :

Operator Meaning
< is less than
<= is less than or equal to
> is greater than
>= is greater than or equal to
== is equal to
!= is not equal to

 The result is of boolean value


 An expressions of this kind is termed as relational expressions

57
Operators and Expressions
Logical operators :

Operator Meaning
&& logical AND
|| logical OR
! logical NOT

 The logical operators && and || are used when we want to form
compound conditions by combining two or more relations.
a > b && x == 10
 An expression of this kind is termed as a logical expressions
 Yields true or false value according to the truth table

58
Truth Table
op-1 op-2 op-1 && op-2 op-1 || op-2

true true true true

true false false true

false true false true

false false false false

59
Operators and Expressions
Assignment operators :
 In addition to usual assignment operator ‘=‘, java has a set of
‘Shorthand’ assignment operators.
v op= exp;
v – variable
exp – expression
op – binary operator
Statement with simple Statement with Shorthand
assignment operator operator
a =a+1 a += a
a =a-1 a –= a
a = a * (n + 1) a *= (n + 1)
a = a / ( n + 1) a /= ( n + 1)
a =a%b a %= b 60
Operators and Expressions
Increment and Decrement operators :

Operator Meaning
++ increment
-- decrement

 Operator ++ adds 1 to the operand


 Operator – subtracts 1 to the operand
 Both are unary operators
Ex:
++m; or m++;
--m; or m--;
61
Operators and Expressions
Conditional operators :

exp1 ? exp2 : exp3

 The ternary operator ?: is available in java.

62
Operators and Expressions
Bitwise operators :

Operator Meaning
& bitwise AND
! bitwise OR
^ bitwise exclusive OR
~ one’s complement
<< shift left
>> shift right
>>> shift right with zero fill
 Used to manipulation of data at values of bit level for testing the
bits, or shifting them to the right or left.
 They are not applied to float or double.
63
Operators and Expressions
Special operators :

Instanceof operator
member selection 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.
 Used to check whether the object belongs to a particular class or
not.
person instanceof student
 Dot opeator is used to access the instance variables and methods of
class objects.
personal // reference to the variable age

64
Operators and Expressions
Arithmetic Expressions :

An arithmetic expression is a combination of variables,


constants, and operators arranged as per the syntax
of the language

Algebraic expression Java expression


ab–c a*b–c
(m + n) (x + y) (m + n) * (x + y)
ab a*b/c
c
3x2 + 2x + 1 3*x*x+2*x+1
x+c x/y+c
65
Operators and Expressions
Evaluation of Expressions :

Expressions are evaluated using an assignment statement


variable = expression;
 The expression is evaluated first and the result then replaces the
previous value of the variable on the left-hand side.
 All the variables in the expression must be assigned values before
evaluation.

Ex:
x = a * b – c; y = b / c * a; z = b – b / c + d;

66
Operators and Expressions
Precedence of Arithmetic Operators :
 An arithmetic expression without any parentheses will be evaluated
from left to right using the rules of precedence of operators.
Operator Description Associability Rank
. Member Selection Left to right 1
() Function call

[] Array element reference


– Unary minus Right to left 2
++ Increment
–– Decrement
! Logical negation
~ Ones complement
(type) Casting
* Multiplication Left to right 3
/ Division
% Modulus
+ Addition Left to right 4
– Subtraction
<< Left shift Left to right 5
67
>> Right shift
Operators and Expressions
Precedence of Arithmetic Operators :
Operator Description Associatively Rank
>>> Right shift with zero fill
< Less than Left to right 6
<= Less than or equal to
> Greater than
>= Greater than or equal to
instanceof Type comparision
== Equality Left to right 7
!= Inequality
& Bitwise AND Left to right 8
^ Bitwise XOR Left to right 9
| Bitwise OR Left to right 10
&& Logical AND Left to right 11
|| Logical OR Left to right 12
?: Conditional operator Right to left 13
= Assignment operator Right to left 14
Op= Shorthand assignment

68
Operators and Expressions
Precedence of Arithmetic Operators :
 The basic evaluation procedure includes two left-to-right passes
through the expression.
 During the first pass the higher priority operators are applied .
 During the second pass the low priority operators are applied.

Ex:
x = 9 – 12 / 3 + 3 * 2 – 1 is evaluated as follows
First pass:
Step 1: x = 9 – 4 + 3 * 2 – 1 (12 / 3 evaluated)
Step 2: x = 9 – 4 + 6 – 1 (3 * 2 evaluated)

Second pass:
Step 3: x = 5 + 6 – 1 (9 – 4 evaluated)
Step 4: x = 11 – 1 (5 + 6 evaluated)
Step 5: x = 10 (11-1 evaluated)
69
Decision Making and Branching
 Java’s program control statements can be put into;
1. Selection statements
2. Iteration statements
3. Control statements

Selection statements:

1. ‘if’ statement

2. ‘switch’ statement

3. Conditional operator statement

70
Decision Making and Branching
Selection statements:

1. ‘if’ statement
 The ‘if’ is a powerful decision making
statement used to control the flow of
execution of statements.
 The syntax for ‘if’ statement:
if (test_expression)
False
Test expression

True

71
Decision Making and Branching
Selection statements:

1. ‘IF’ statement
The if statement may be implemented in different forms depending
on the complexity of conditions to be tested.

1. Simple IF statement

2. If . . . . ELSE statement

3. Nested IF . . . . ELSE statement

4. ELSE IF ladder

72
Decision Making and Branching
Selection statements:
Entry
1. Simple ‘IF’ statement
if (test_expression)
{
statement-block; True
Test expression
}
statement – x;

statement-block
False

Statement – x

Next statement
73
Decision Making and Branching
Selection statements:

1. ‘IF’ statement
Example:
import java.io.Console;
class ifexample{
public static void main (String args[]){
Console console = System.console( );
int inputnum = Integer.parseInt(console.readLine(" Input number: "));
System.out.println(“Even numbers from 1 to “ + inputnum);
for(int i = 0; i <=inputnum; i++)
{
if(i %2 == 0)
{
System.out.println(i);
}
}
}
}
74
Decision Making and Branching
Selection statements:
Entry
1. IF ….. ELSE statement
if (test_expression)
{
True-block statement (s);
True False
}
Else Test expression
{
False-block statement (s)
}
statement – x;
True-block False-block
statement statement

Statement – x

Next statement
75
Decision Making and Branching
Example:
import java.io.Console;

class ifelseexample{

public static void main(String args[])


{
Console console = System.console( );
int inputnum = Integer.parseInt(console.readLine(" Input number: "));
System.out.print("\n");
System.out.println("+--------------------------------------------------+");
System.out.println("\t Odd numbers \t |\t Even Numbers");
System.out.println("+--------------------------------------------------+");
for(int i = 1; i <=inputnum; i++) {
if(i %2 != 0) { System.out.print("\t\t"+i +"\t |\t \t "); }
else { System.out.println(i); }
}
System.out.println("\n+--------------------------------------------------+");
}
} 76
Decision Making and Branching
Nesting of IF ……. ELSE statement:
if (test condition1)
{
if (test condition2)
{
statement – 1;
}
else
{
statement – 2;
}
}
else
{
statement – 3;
}
statement – x; 77
Decision Making and Branching
Nesting of IF ……. ELSE statement:
class ifelsenesting
{
public static void main(String args[])
{
int a = 325, b = 712, c = 478;
Sytem.out.println("Largest value is: ");
if (a > b)
{
if (a > c) { System.out.println(a); }
else { System.out.println(c); }
}
else
{
if (c > b) { System.out.println(c); }
else { System.out.println(b); }
}
}
}
78
Decision Making and Branching
ELSE IF Ladder:
if (condition 1)
statement – 1;
else if (condition 2)
statement – 2;
else if (condition 3)
statement – 3;
………………………
else if (condition n)
statement – n;
else
default – statement;
statement – x; 79
Decision Making and Branching
ELSE IF Ladder:
switch (expression)
{
case value – 1:
block – 1
break;
case value – 2:
block – 2
break;
……………….
……………….
default:
default-block
break;
}
statement – x; 80
Decision Making and Branching
Example:
import java.io.Console;
class Switchexample{
public static void main(String args[])
{ Console console = System.console( );
System.out.println("Enter two numbers for operation:");
int x = Integer.parseInt(console.readLine(" Input number 1: "));
int x = Integer.parseInt(console.readLine(" Input number 2: "));
System.out.print("\n");
System.out.println("1. Add");
System.out.println("2. Subtract");
System.out.println("3. Multiply");
System.out.println("4. Divide");
int x = Integer.parseInt(console.readLine(" Enter your choice:"));
System.out.println("");
81
Decision Making and Branching
Example:
switch (a){
case 1:
System.out.println(x + “ + ”+y+” =“ + (x+y));
break;
case 2:
System.out.println(x + “ - ”+y+” =“ + (x-y));
break;
case 3:
System.out.println(x + “ * ”+y+” =“ + (x*y));
break;
case 4:
System.out.println(x + “ / ”+y+” =“ + (x/y));
break;
default:
System.out.println("Invalid Entry!");
}
}
}
82
Decision Making and Branching

Conditional Operator:

Conditional expression ? expression 1 : expression 2

83
Decision Making and Looping

Conditional Operator:

Conditional expression ? expression 1 : expression 2

84

You might also like