Module1 Java
Module1 Java
Unit I
Concepts of Object oriented programming, Benefits of OOP, Features of Java. Java
environment, Java tokens, Constant, variables, data types, operators, Control Statements-
branching statements, looping statements, jump statements, labelled loops.
Unit II
Defining a Class, Fields declaration, Method declaration, Creating object, Accessing class
members, method overloading, Constructors, constructor overloading, super keyword, static
Members, Inheritance, overriding methods, dynamic method dispatch, final(variables, methods
and classes), abstract methods and classes, interfaces, visibility control.
UNIT III
Arrays- One dimensional arrays, declaration, creation, initialization of arrays, two dimensional
arrays, String class. Packages: - Java API packages overview (lang, util, io, awt, swing, applet),
user defined packages-creating packages, using packages Exception Handling Techniques-try-
catch-throw-throws-finally -Multi-threading- creation of multithreaded program-Thread class-
Runnable interface, Thread life cycle.
UNIT IV
Event Handling-Delegation Event Model-Event Classes-Sources of Events-Event Listeners-
Event classes- Swing- architecture, components of swing- JLabel, JButton, JCheckBox,
JRadioButton, JList, JComboBox, JTextField, JText Area, JPanel, JFrame, Layout
Managers(Flow Layout, Grid Layout, Card Layout, Border Layout, Box Layout, Null Layout
).
UNIT V
Applet Fundamentals -applet tag, applet life cycle, passing parameters to applets. Working with
graphics - Line, Rectangle, Oval, Arc, color setting. JDBC architecture- JDBC connection,
JDBC statement object, JDBC drivers.
Book of study :
1. E. Balagurusamy- Programming with Java , Third Edition, McGraw Hill Companies.
2. K. Somasundaram - PROGRAMMING IN JAVA2, First Edition, Jaico Publishing House.
Reference:
1. Patrick Naughton - Java2 The Complete Reference, Seventh Edition:
2. Cay S Horstmann & Gary Cornell - Core Java Volume 1- Fundamentals, Eighth edition.
3. Java 6 Programming Black Book 2007 Edition, Dreamtech press.
Module I
Concepts of Object oriented programming, Benefits of OOP, Features of Java. Java
environment, Java tokens, Constant, variables, data types, operators, Control Statements-
branching statements, looping statements, jump statements, labeled loops.
Data abstraction :
Abstraction refers to the act of representing essential features without including the back
ground details or explanation. Classes use the concept of abstraction and are defined as a list
of attributes such as size, weight, cost and functions to operate on these attributes. They
encapsulate all essential properties of the object that are to be created. The attributes are called
as data members as they hold data and the functions which operate on these data are called as
member functions. Class use the concept of data abstraction so they are called abstract data
type (ADT).
Inheritance
Inheritance in Java is a mechanism in which object of one class acquires all the properties and
behaviours of another class. Inheritance supports the concept of hierarchical classification.
The idea behind inheritance in Java is reusability, that is you can create new classes from
existing classes. When you inherit from an existing class, we can reuse methods and fields of
the parent class. Moreover, you can add new methods and fields in the current class also.
The class which inherits the properties of other is known as subclass (derived class, child class)
and the class whose properties are inherited is known as superclass (base class, parent class).
Polymorphism:
Polymorphism means the ability to take more than one form. For example, an operation have
different behaviour in different instances. The behaviour depends upon the type of the data
used in the operation.
For example, consider the operation of addition. For two numbers, the operation will generate
a sum. If the operands are strings, then the operation will produce a third string by
concatenation.
Consider the figure given below. It illustrates a single function area() can be used to handle
different number and different types of arguments.
Polymorphism plays an important role in allowing objects having different internal structures
to share the same external interface. Polymorphism is extensively used in implementing
inheritance.
Compile Time and Runtime mechanisms
In the context of a programming language, compile time may refer to any of the following,
• The operations performed by the compiler such as syntactic and semantic analysis.
• The pre-runtime assessment of the program’s behaviour.
In java, apart from the syntax and semantic checks, one important logicalk task that is
considered to be performed at compile time is the implementation of inheritance. It is at the
compile time that the child class inherits the public data members and methods of the base
class.
Run time is the time period when a syntactically correct program is actually executed in the
computer system.One of the important concept associated with runtime is the implementation
of polymorphism. It is also referred as polymorphism.
Dynamic Binding
Binding refers to the linking of a procedure call to the code to be executed in response to the
call. Dynamic binding means that the code associated with a given procedure call is not known
until the time of call at runtime. It is associated with polymorphism and inheritance.A
procedure call associated with a polymorphic reference depends on the dynamic type of that
reference.
Message communication
An object oriented program consists of a set of objects that communicates with each other. The
process of programming in an object oriented language involves the following basic steps.
1. Creating classes that define objects and their behaviour.
2. Creating objects from class definitions.
3. Establishing communication among objects.
Objects communicate with one another by sending and receiving information .
A message for an object is a request for execution of a procedure, and therefore will invoke a
method in the receiving objects that generates the desired result.
Message passing involves specifying the object, the name of the method and informaton to be
sent.
Benefits of oops
• We can build the programs from standard working modules that communicate with one
another, rather than having to start writing the code from scratch which leads to saving
of development time and higher productivity,
• OOP language allows to break the program into the bit-sized problems that can be
solved easily (one object at a time).
• The new technology promises greater programmer productivity, better quality of
software and lesser maintenance cost.
• OOP systems can be easily upgraded from small to large systems.
• It is possible that multiple instances of objects co-exist without any interference.
• It is very easy to partition the work in a project based on objects.
• It is possible to map the objects in problem domain to those in the program.
• The principle of data hiding helps the programmer to build secure programs which
cannot be invaded by the code in other parts of the program.
• By using inheritance, we can eliminate redundant code and extend the use of existing
classes.
• Message passing techniques is used for communication between objects which makes
the interface descriptions with external systems much simpler.
• The data-centred design approach enables us to capture more details of model in an
implementable form.
Java History
HISTORY Java is the general purpose, true object oriented programming language and is
highly suitable for modelling the real world and solving the real world problems. In the
company Sun Microsystem, James Gosling (an employee there), started a project named
„GREEN‟. He began his work by attempting to extend C++ features for developing embedded
software for electronic companies to automate the electronic devices such as microwave. But
this could not be accomplished by C++. So James Goslings started to develop a new language
known as “OAK”. In may 1995, Sun officially announced this language at Sun world 95.Due
to some reasons, the name was changed to “JAVA”. The prime motive of Java was the need
for a platform independent language. The second motive was to design a language which is
„Internet Enable‟. To run the programs on internet, Green project team come up with the idea
of developing “Web Applet”. The team developed a web browser called “Hot Java” to locate
and run applet programs on internet. The most striking feature of Java is „Platform
neutralness‟. Java is the first language that is not tied to any particular hardware or O.S.
JAVA MILESTONES
YEAR DEVELOPMENT
1990 Sun Microsystem started to develop special software for electronic
devices. A team of Sun Microsystems programmers headed by James
Gosling was formed to undertake this task.
1992 The team, known as Green Project Team demonstrated OAK in hand held
devices.
1994 Green project team developed a web browser “Hot Java” to run applets
on internet.
1996 Java established itself as the leader of internet programming. Sun released
Java development kit 1.0
1999 Sun released Java2 standard edition (J2SE) and Enterprise Edition
(J2EE).
2006 Java SE 6 was released. With this release, sun changed the name from
‘J2SE’ to ‘Java SE’ and also removed ‘0’ from the versio name
Features of Java
1. SIMPLE: Java was designed to be easy for the professional programmers to learn and
use effectively. Java uses C/C++ syntax. So, it is very simple to work in Java.
5. ROBUST AND SECURE: Java is a robust language. Here robust means, it provides
many safeguards to ensure reliable code. It has strict compile-time and run-time
checking for data types. It also has the concept of exception handling to capture errors
and remove the fear of crashing the system. Security is the major issue, when you work
on internet. It not only verify all memory access but also ensure that no viruses are
entering through the applet. That’s why it doesn’t use pointers.
10. EASE OF DEVELOPMENT: Java 2 Standard edition (J2SE) 5.0 supports features
such as generics, enhanced for loop, autoboxing or unboxing, typesafe enums, varargs,
static import and annotation. These features reduce the work of the programmers.
13. DESKTOP CLIENT: J2SE 5.0 provides enhanced features to meet the requirements
and challenges of the Java desktop users. It provides an improved swing look and feel
called Ocean. This feature is mainly used for developing graphics applications.
Java Environment
Java environment includes a large number of development tools and hundreds of classesand
methods. The development tools are oart of th esystem known as Java Development
Kit(JDK) and the classes and methods are part of the Java Standard Library(JSL) also known
as Application Programming Interface(API).
Java Development kit
The java Development Kit comes with a collection of tools that are used for developing and
running java programs. They include:
Tool Description
appletviewer Enables us to run java applets(without actually using a java-compatible
browser)
java Java interpreter, which runs applets and applications by reading and
interpreting bytecode files
javac The java compiler, which translates java sourcecode to bytecode files that
the interpreter 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 bytecode files into a
program description
jdb Java debugger, which helps us to find errors in our programs
JAVA TOKENS
A Java program is basically a collection of classes. A class is defined by a set of declaration
statements and methods containing executable statements. Smallest individual units in a
program are known as tokens. The compiler recognizes them for building up expressions and
statements.
Java program is acollection of tokens, comments and white spaces. Java language includes
five types of tokens. They are,
1. Reserved keywords
2. Identifiers
3. Literals
4. Operators
5. Separators
KEYWORDS
Keywords are an essential part of a language definition. They implement specific features of
the language.Java language has 50 words as keywords. These keywords, combined with
operators and separators form definition of the Java language.
All keywords have specific meaning in java so we cannot use them as names of variables,
classes, methods and so on. Key words are to be written in lower-case letters. Since java is case
sensitive, one can use these words as identifiers by changing one or more letters to upper case.
Java Keywords
IDENTIFIERS
Identifiers are programmer- designed tokens. Identifiers are used to name a variable,
constant, function, class, and array. It usually defined by the user. It uses letters, underscores,
or a dollar sign as the first character. The label is also known as a special kind of identifier
that is used in the goto statement.
Java identifiers follow these rules,
1. They can have alphabets, digits and underscore and dollar sign characters.
2. They must not begin with a digit.
3. Uppercase and lowercase letters are distinct.
4. Thay can be of any length
Eg. Average, sum, dayTemperature etc..
LITERALS
Literals in java are a sequence of characters like digits, letters and other charactes that represent
constant values to be stored in variables. Java language specifies the following types of literals.
• Integer literals
• Floating_point literals
• Character literals
• String literals
• Boolean literals
• Null literal
Literal Type
23 int
9.86 float
"javatpoint" String
OPERATORS
An operator is a symbol that takes one or more arguments and operates them to produce a
result.
SEPARATORS
Separators are symbols used to indicate where groups of code are divided and arranged. The
separators in Java is also known as punctuators.
There separators in Java, are as follows:
Name Use
Square Brackets [] It is used to define array elements. A pair of square brackets represents
the single-dimensional array, two pairs of square brackets represent the
two-dimensional array.
Parentheses () It is used to call the functions and passing the parameters
Curly Braces {} The curly braces denote the starting and ending of a code block for
classes, methods and local scopes
Comma (,) It is used to separate consecutive identifiers in a variable declaration
Semicolon (;) It is the symbol that can be found at end of the statements. It separates
the two statements
Period (.) It separates the package name form the sub-packages and classes. It also
separates a variable or method from a reference variable.
CONSTANTS
A value which is fixed and does not change during the execution of a program is called
constants in java. In other words, Java constants are fixed (known as immutable) data values
that cannot be changed.
Java supports various types of constants. They are as follows:
Integer Constants
An integer constant is a sequence of digits without a decimal point. For example, 10 and -200
are integer constants. There are three types of integer constants. They are as follows:
• Decimal integer
Decimal integer is a sequence of digits from 0 to 9. These constants are either positive or
negative. Plus sign is optional.
For example, 24, -55, 0, and +3425 are valid examples of decimal integer constants in
decimal notation.
Non-digit characters, embedded spaces, and commas are not allowed between digits. For
example, 12 3450, 20.00, $1200 are illegal numbers.
• Octal integer
An octal integer constant is a sequence of any combination of digits from 0 to 7. Octal integer
always starts with 0. The digits 8 and 9 are not valid in octal notation.
The examples of valid integer constants in octal notation are 024, 0, 0578, and 0123.
• Hexadecimal integer
Hexadecimal integer constants consist of digits 0 to 9 and alphabets “a” to “f” or “A” to “F”.
These constants are preceded by 0x. Letter “A” to “F” represents the numbers 10 to 15.
The valid examples of hexadecimal integer constants are 0x23, 0x5B, 0x9F, 0x, etc. “x” can
also be either small or capital.
Real Constants
Real constants consist of a sequence of digits with fractional parts or decimal points. These
constants are also called floating-point constants. The valid examples of real constants are
2.3, 0.0034, -0.75, 56.7, etc.
These numbers are shown in the decimal point notation. It is also possible that the number
may not have digits before decimal point or digits after the decimal point. For example, 205.,
.45, -.30, etc.
A real constants number can also be expressed in exponential or scientific notation. For
example, the value 235.569 can also be written as 2.35569e2 in exponential notation. Here,
e2 means multiply by 10^2.
It has the following general form:
mantissa e exponent
Where,
mantissa is either integer number or a real number expressed in decimal notation. The term
exponent is an integer with an optional plus or minus sign.
The letter “e” is used to separate mantissa and exponent which can be written in either
lowercase or uppercase. The valid examples of floating points constants are 0.54e2, 12e-4,
1.5e+5, 2.13E4, -1.5E-4, etc.
Embedded (blank) space is not permitted in any numeric constants. Exponential notation is
useful to represent either very small or very large number in magnitude.
For example, 250000000 can also be written as 2.5e8 or 25E7. Similarly, -0.000000021 is
equivalent to -2.1e-8.
A floating point constant consists of for parts
1. a whole number
2. a decimal point
3. a fractional part
4. an exponent
Character Constants
A single character constant ( or simply character constant) is a single character enclosed
within a pair of single quote. The example of single-character constants are as follows:
The last constant is blank space. The character constant ‘5’ is not equivalent to the number 5.
String Constants
A string constant is a sequence of characters within a pair of double-quotes. The characters
can be alphabets, special characters, digits, and blank spaces. The valid examples of string
constants are given below:
“Hello Java” “1924” “?…!” “2+7” “X” etc.
Backslash Character Constants
Java provides some special backslash character constants that are used in output methods. For
example, the symbol ‘n’ which stands for newline character..Each one of them represents one
character, although they consists of two characters. These character combinations are called
escape sequences.
There are various types of backslash character constants that are supported by java The list is
given in the below table.
Constants Meaning
‘\ b ‘ back space
‘\ f ‘ form feed
‘\ n ‘ new line
‘\r‘ carriage return
‘\t‘ horizontal tab
‘\ ‘ ‘ single quote
‘\ ” ‘ double quote
‘\\ ‘ backslash
VARIABLES
A variable is an identifier that denotes a storage location used to store a data value. Variable
is name of reserved area allocated in memory. In other words, it is a name of memory
location.
A variable name can be chosen by the programmer in a meaningful way so as to reflect what
it represents in the porgram. Examples for variable names are,
• average
• height
• total_height
• classStrength
Rules for declaring variable in java
• A variable name can consist of Capital letters A-Z, lowercase letters a-z, digits 0-9,
and two special characters such as underscore and dollar Sign.
• The first character must be a letter.
• Blank spaces cannot be used in variable names.
• Java keywords cannot be used as variable names.
• In java variable names are case-sensitive i.e., uppercase and lower case are distinct.
• Variable length can be of any length.
DATA TYPES
Operators
Java Operators
In Java, an expression has two parts: operand and operator. The variables or constants that
operators act upon are called operands.
An operator in java is a symbol or a keyword that tells the compiler to perform a specific
mathematical or logical operations.
Symbolic operator in Java
1. Arithmetic operators:
2. Relational operators
3. Logical operators: &&, ||, !.
4. Assignment operators: =,
5. Increment and decrement operators: + +, – –
Conditional operators: ?:
Bitwise operators: &, !, ^, ~, <<, >>, >>>
Shift operators: <<, >>, >>>.
Arithmetic Operators
Java Arithmetic operators are used to performing fundamental arithmetic operations such as
addition, subtraction, multiplication, and division on numeric data types.
The numeric data types can be char, byte, short, int, long, float, and double. Java provides
five arithmetic operators. They are listed in the below table.
Subtraction or unary
2. – Performs subtraction operation.
minus
Integer Arithmetic
If both operands in a single arithmetic expression are integers, the expression is called
arithmetic expression, and the operation is called integer arithmetic. Integer arithmetic always
takes integer values.
a+b = 30
a-b = 10
a*b = 200
a/b = 2
a%b = 0 (Remainder of integer division)
Real Arithmetic
An arithmetic operation that involves only real operands is called real arithmetic. In real
operand, values are assumed either in decimal or exponential notation.
public class RealTest
{
public static void main(String[] args)
{
double a = 15.5, b = 20.2;
System.out.println("a+b = " +(a+b));
System.out.println("a-b = " +(a-b));
System.out.println("a*b = " +(a*b));
System.out.println("a/b = " +(a/b));
System.out.println("a%b = " +(a%b));
}
}
Mixed-mode Arithmetic
When one operand is integer and other operands are real, this kind of expression is called
mixed-mode arithmetic operation. First, integer operand is converted into real operand and
then real arithmetic operation is performed.
public class MixedTest
{
int x = 20; // Integer
double y = 12.5; // Real
void div()
{
double z = x/y;
System.out.println("z = " +z);
}
public static void main(String[] args)
{
MixedTest mt = new MixedTest();
mt.div();
}
}
Relational Operators
Relational operators in Java are those operators that are used to perform the comparison
between two numeric values or two quantities.
These operators determine the relationship between them by comparing operands. For
example, to know which is a bigger number, comparing the age of two persons, comparing
the price of two items, etc.
These comparisons can be performed with the help of relational operators. Relational
operators require two operands..
Operator Meaning
== Is equal to
!= Is not equal to
These operators are mainly used when applying control statements in the program.
The output of the relational operator is (true/false) boolean value, and in Java, true or false is
a non-numeric value that is not related to zero or one.
public class RelationalOperatorsDemo
{
public static void main(String[] args)
{
int x = 10;
int y = 30;
System.out.println("x = " +x+ "y = " +y);
System.out.println("x is greater than y: " +(x>y));
System.out.println("x is less than y: " +(x=x));
System.out.println("x is less than equal to y: " +(x<=y));
System.out.println("x is equal to y: " +(x==y));
System.out.println("(x+20 < y+10): " +(x+20 < y+10));
}
}
Logical Operators
Lgical operators in Java are those operators which are used to form compound conditions by
combining two or more conditions or relations.
Sometimes in Java, these operators are also called Boolean operators because they return a
boolean value.
An example of logical operators is given below.
x > y && x > z
This kind of expression that combines two or more relational expressions is called logical
expression or compound relational expression. The result of logical expression is also a value
of true or false.
Java, there are three types of logical operators. They are listed in the below table.
Operators Meaning
|| OR operator
! NOT operator
v op = expression;
where,
op: It is a Java binary operator. It may be + – * / % << >> etc.
v and expression are the same as explained in the simple assignment.
The operator op = is known as a shorthand assignment operator in Java because
Increment and Decrement operator
The operator which is used to increase the value of a variable (operand) by one is called
increment operator in java. It is represented by ( ++ ). The operator ++ adds 1 to the operand.
It can have the following forms:
++x; or x++;
++x is equivalent to x = x + 1; (or x += 1; ).
Consider the following examples:
1. int a = 5;
++a;
2. int a = 5;
a++
Here, the value of variable a is incremented by 1 when ++ operator is used before or after x.
In Java, both are valid expressions.
Decrement ( — ) Operator in Java
The operator which is used to decrement the value of a variable (operand) by one is called
decrement operator in java. It is represented by ( — ). The operator — subtracts 1 to the
operand. It can have the following forms:
–x; or x–;
–x is equivalent to x=x – 1; (or x -=1; ).
Conditinal Operator
The character pair ? : is called ternary operator in Java because it acts on three variables. This
operator is also known as conditional operator. It is used to make conditional expression.
Syntax:
variable = exp1 ? exp2 : exp3;
where exp1, exp2, and exp3 are expressions.
The operator ? : works as follows,
the expression exp1 is evaluated. If it is true, the expression exp2 will be evaluated and the
value of exp2 will store in the variable. If exp1 is false, exp3 will be evaluated and its value
will store in the variable.
Consider the following example:
int a = 40;
int b = 30;
int x = (a > b) ? a : b;
Here, first (a > b) is evaluated. If it is true, the value of a is stored in the variable x. If it is
false, the value of b is stored in the variable x.
Here, (a > b) is true because the value of a is greater than value of b. Therefore, the value of a
will assign in the variable x. That is, x = 40.
public class Test
{
public static void main(String[] args)
{
int x = 20;
int y = 10;
int z = (x > y) ? x : y;
System.out.println("Greatest number: " +z);
}
}
Output:
Greatest number: 20
Bitwise Operator
This operator that acts on individual bits (0 or 1) of the operands is called bitwise operator in
java. It acts only integer data types such as byte, short, int, and long. Bitwise operators in java
cannot be applied to float and double data types.
The internal representation of numbers in the case of bitwise operators is represented by the
binary number system. Binary number is represented by two digits 0 or 1. Therefore, these
operators are mainly used to modify bit patterns (binary representation).
In java, there are seven types of bitwise operators. They are ,
Operator Meaning
| bitwise OR
^ bitwise exclusive OR
CONTROL STATEMENTS
DECISION MAKING AND BRANCHING
A java program is a set of statements, which are normally executed sequentially in the order
in which they appear. Control flow statements are those statements that change the flow of
execution and provide better control to the programmer on the flow of execution in the
program. These statements are executed randomly and repeatedly. Control statements in java
programming are used to write better and complex programs.
The whole classification of control flow statements or decision-making statements can be
represented as shown below.
Java supports two kinds of control flow statements:
1. Conditional statements
A program that breaks the sequential flow and jumps to another part of the code is called
branching in java. When branching is based on a specific condition, then it is called
conditional branching or conditional statements. Since the flow of execution is transferred
on a particular condition from one part of code to another part, it is also called conditional
execution.
2. Unconditional statements
When the flow of execution jumps to another part of code without carrying out any
conditional test, it is called unconditional statements or unconditional execution.
Java language possesses such decision making capabilities and supports the following
statements known as control or decision making statements:
1. If statement
2. switch statement
3. conditional operator statement
Decision making with if statement
The if statement is a powerful decision making statement and is used to control the flow of
execution of statements. It is basically a two-way decision statement and is used in
conjunction with an expression.
It takes the form
If (test expression)
It allows the computer to evaluate the expression first and then, depending on whether the
value of the expression is true or false, it transfers the control to a particular statement.
Simple if statement
The general form or syntax of if
if ( test-expression)
{
Statement - block;
}
Statement-X;
The statement block may be a single statement or group of statements. If the test expression
is true, the statement – block will be executed. Otherwise the statement – block will be
skipped and the execution will jump to statement- x.
Flow chart of simple if
Statement Block
Program 1
class IfExample {
public static void main(String[] args)
{
int age=20;
if(age>18){
System.out.print("Age is greater than 18");
}
}
}
Output:
Age is greater than 18
Program 2
class IfDemo {
public static void main(String args[])
{
String str = "Simple if statement";
int i = 4;
if (i == 4)
{
i++;
System.out.println(str);
}
System.out.println("i = " + i);
}
}
Output
Simple if statement
I=5
The if…else statement
The if … else statement is an extension of the simple if statement
The general form is
if (test-expression)
{
True - block of statements
}
else
{
False - block of statements
}
Statement- x
In this type of a construct, if the test-expression is true, then the true block of statements
following the if statement, are executed. Otherwise, the false block statements are executed.
After that, the control is transferred to statement x.
Flow chart of if… else
Entry
Statement X
Program 1
class IfElseExample
{
public static void main(String[] args)
{
int number=13;
if(number%2==0)
{
System.out.println("even number");
}
else
{
System.out.println("odd number");
}
}
}
Output
Odd number
Program 3 Leap Year
A year is leap, if it is divisible by 4 and 400. But, not by 100.
public class LeapYearExample {
public static void main(String[] args) {
int year=2020;
if(((year % 4 ==0) && (year % 100 !=0)) || (year % 400==0)){
System.out.println("LEAP YEAR");
}
else{
System.out.println("COMMON YEAR");
}
}
Nesting of if….else statements
When a series of decisions are involved, we have to use more than one if…else statement in
nested form.
Syntax
if (test condition1)
{
if (test condition2)
{
Statement-1;
}
else
{
Ststement – 2;
}
}
else
{
Looping
Ststement – 3;
}
Ststement – x;
If the condition-1 is false, the statement- 3 will be executed, otherwise it continues to perform
the second test. If the condition-2 is true, the statement-1 will be evaluated, otherwise the
statement- 2 will be evaluated and then the control is transferred to the statement-x.
Flow chart
Entry
if(condition1)
Statement- 1;
else if(condition2)
Statement -2
else if(condition3)
Statement -3
.......................
else if (condition n)
Statement -n
else
Default- statement;
Statement –x;
This construct is known as else if ladder. The conditions are evaluated from the top of the
ladder downwards. As soon as the true condition is found, the statement associated with it is
executed and the control is transferred to the statement-x (skipping the rest of the ladder).
Whwn all the n conditions become false, then the final else containing the default- statement
will be executed.
Chart
Flow chart
Program 1
class IfElseIfExample
{
public static void main(String[] args)
{
int marks=65;
if(marks<50)
{
System.out.println("fail");
}
else if(marks>=50 && marks<60)
{
System.out.println("D grade");
}
else if(marks>=60 && marks<70)
{
System.out.println("C grade");
}
else if(marks>=70 && marks<80)
{
System.out.println("B grade");
}
else if(marks>=80 && marks<90)
{
System.out.println("A grade");
}
else if(marks>=90 && marks<100)
{
System.out.println("A+ grade");
}
else
{
System.out.println("Invalid!");
}
}
}
Output:
C grade
The switch statement
A switch statement allows a variable to be tested for equality against a list of values. Each
value is called a case, and the variable being switched on is checked for each case. When a
match is found, a block of statements associated with that case is executed.
The general form of switch statement is shown below.
switch(expression)
{
case value1:
block 1
break;
case value2:
block 2
break;
...........
………
default:
default block
break;
}
Statement x;
The expression is an integer expression or characters. Value 1, value 2….. are constants or
constant expressons and are known as case labels. Each of these values should be unique
within a switch statement. Block1, block2…. Are statement lists and may contain zero or
more statements. The case labels end with a colon.
………………………….
Program
public class SwitchMonthExample
{
public static void main(String[] args)
{
int month=7;
String month = "";
switch(month)
{
case 1: month ="1 - January";
break;
case 2: month ="2 - February";
break;
case 3: monthS ="3 - March";
break;
case 4: month ="4 - April";
break;
case 5: month ="5 - May";
break;
case 6: month ="6 - June";
break;
case 7: month ="7 - July";
break;
case 8: month ="8 - August";
break;
case 9: month ="9 - September";
break;
case 10: month ="10 - October";
break;
case 11: month ="11 - November";
break;
case 12: month ="12 - December";
break;
default:System.out.println("Invalid Month!");
}
System.out.println(month);
}
}
Program
public class SwitchVowelExample {
public static void main(String[] args) {
char ch='O';
switch(ch)
{
case 'a':
System.out.println("Vowel");
break;
case 'e':
System.out.println("Vowel");
break;
case 'i':
System.out.println("Vowel");
break;
case 'o':
System.out.println("Vowel");
break;
case 'u':
System.out.println("Vowel");
break;
case 'A':
System.out.println("Vowel");
break;
case 'E':
System.out.println("Vowel");
break;
case 'I':
System.out.println("Vowel");
break;
case 'O':
System.out.println("Vowel");
break;
case 'U':
System.out.println("Vowel");
break;
default:
System.out.println("Consonant");
}
}
}
The ?: operator
In Java, a ternary operator can be used to replace the if...else statement in certain situations. A
ternary operator evaluates the test condition and executes a block of code based on the result
of the condition.
This is useful for making 2 way decisions. This operator is a combination of ? and: . it takes 3
operands. Hence, the name ternary operator. This operator is popularly known as conditional
operator.
Syntax
Here, condition is evaluated and if condition is true, expression1 is executed and, if condition
is false, expression2 is executed.
Program 1
class Main
{
public static void main(String[] args)
{
int number = 24;
if(number > 0)
{
System.out.println("Positive Number");
}
else
{
System.out.println("Negative Number");
}
}
}
Java User Input
The java.io package provides various classes to read write data from various sources and
destinations. You can read data from user (keyboard) using various classes such as, Scanner,
BufferedReader, InputStreamReader, Console etc.
Using Scanner class
From Java 1.5 Scanner class was introduced. This class accepts a File, InputStream, Path and,
String objects, reads all the primitive data types and Strings from the given source.
To read data from keyboard you need to use standard input as source (System.in). For each
datatype a nextXXX() is provided namely, nextInt(), nextShort(), nextFloat(), nextLong(),
nextBigDecimal(), nextBigInteger(), nextLong(), nextShort(), nextDouble(), nextByte(),
nextFloat(), next().
The Scanner class is used to get user input, and it is found in the java.util package. To use the
Scanner class, create an object of the class and use any of the available methods found in the
Scanner class documentation
Input Types
Method Description
import java.util.Scanner;
public class Main
{
public static void main(String args[])
{
Scanner scan= new Scanner(System.in);
String text= scan.nextLine();
System.out.println(text);
int num= scan.nextInt();
System.out.println(num);
}
}
import java.util.Scanner;
class Main
{
public static void main(String[] args)
{
Scanner myObj = new Scanner(System.in);
System.out.println("Enter name, age and salary:");
String name = myObj.nextLine();
int age = myObj.nextInt();
double salary = myObj.nextDouble();
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Salary: " + salary);
}
}
The while is an entry controlled loop statement. The test condition is evaluated and if the
condition is true, then the body of the loop is executed. After execution of the body, the test
condition is once again evaluated and if it is true, the body is executed once again. This process
of repeated execution of the body continues until the test condition finally becomes false. On
exit, the program continues with the statement immediately after the body of the loop.
Program
Print Fibonacci series
import java.util.Scanner;
public class Fibonacci
{
public static void main(String[] args)
{
int n, a = 0, b = 0, c = 1;
Scanner s = new Scanner(System.in);
System.out.println("Enter value of n:");
n = s.nextInt();
System.out.println("Fibonacci Series:");
for(int i = 1; i <= n; i++)
{
a = b;
b = c;
c = a + b;
System.out.println (a+" ");
}}}
Factorial of a number
import java.util.Scanner;
class Factorial
{
public static void main (String args [])
{
int i =1, factorial=1, number;
System.out.println ("Enter the number:");
Scanner sc = new Scanner (System.in);
number = sc.nextInt ();
while (i <=number)
{
factorial = factorial * i;
i++;
}
System.out.println ("Factorial of the given number is: "+factorial);
}
}
Reverse of a number
import java.util.Scanner;
class Reverse
{
public static void main (String args [])
{
int num=0, rev =0;
System.out.println ("Input your number and press enter: ");
Scanner sc = new Scanner (System.in);
num = sc.nextInt ();
while ( num != 0 )
{
rev= rev * 10;
rev = rev + num%10;
num = num/10;
}
System.out.println ("Reverse of input number is: "+rev);
}
}
Armstrong Number
class Armstrong
{
public static void main (String [] args)
{
int num = 370, number, temp, total = 0;
number = num;
while (number != 0)
{
temp = number % 10;
total = total + temp*temp*temp;
number /= 10;
}
if (total == num)
System.out.println (num + “is an Armstrong number");
else
System.out.println (num + “is not an Armstrong number");
}
}
Armstrong number by taking input from user
import java.util.Scanner;
public class ArmstrongNumber
{
public static void main (String args [])
{
int number;
int check, rem, sum = 0;
System.out.println ("Enter the number to be verified :");
Scanner sc = new Scanner (System.in);
number = sc.nextInt ();
check = number;
while (check! = 0)
{
rem = check % 10;
sum = sum + (rem * rem * rem);
check = check / 10;
}
if (sum == number)
System.out.println ("Given number is an Armstrong number.");
else
System.out.println ("Given number is not an Armstrong number.");
}
}
Initialization ;
do
{
Body of the loop ;
}
while (test condition) ;
On reaching the do statement, the program proceeds to evaluate the body of the loop first. At
the end of the loop, the test condition in the while statement is evaluated. If the test condition
is true, the program continues to evaluate the body of the loop once again. This process
continues as long as the condition is true. When the condition becomes false, the loop will be
terminated and the control goes to the statement that appears immediately after the while
statement.
Since the test condition is evaluated at the bottom of the loop, the do….while construct is an
exit controlled loop.
The difference between do-while and while is that do-while evaluates its expression at the
bottom of the loop instead of the top. Therefore, the statements within the do block are
always executed at least once
Program
class dowhileloopDemo
{
public static void main(String args[])
{
int x = 21, sum = 0;
do
{
Sum= sum + x;
x--;
}
while (x > 10);
System.out.println("Summation: " + sum);
}
}
The for Statement
The for loop is an entry controlled loop that provides a more clear loop control structure.
Syntax
2. The value of the control variable is tested using the test condition. The test condition is
a relational expression, such as i<10 that determines when the loop will exit. If the
condition is true, the body of the loop is executed; otherwise the loop is terminated and
the execution continues with the statement that immediately follows the loop.
3. When the body of the loop is executed, the control is transferred back to the for
statement after evaluating the last statement in the loop.
Now, the control variable is incremented using an assignment statement such as i=i+1
and the new value of the control variable is again tested to see whether it satisfies the
loop condition.
if the condition is satisfied, the body of the loop is again executed. This process
continues till the value of the control variable fails to satisfy the test condition.
Program 1
class forTest
{
public static void main(String args[])
{
int i;
for( i=1; i<=10; i++)
System.out.println(i);
}
}
import java.util.Scanner;
class BreakContinueWhileLoop
{
public static void main (String [] args)
{
int n;
Scanner input = new Scanner (System.in);
while (true)
{
System.out.println ("Input an integer");
n = input.nextInt ();
if (n != 0)
{
System.out.println ("You entered” + n);
continue;
}
else
{
break;
}
}
}
}
Jumps in loops:
Break : [jumping of out of a loop]
Break is used to come out of a loop, an early exists from a loop can be accomplished by using
break statement. The break statement can be used within while, do, (or for loops).
When the break statement is encounted inside a loop, the loop is immediately exited and the
program continuous with the statement immediately following the loop.
When the loops are nested the break would only exist from the loop containing it. that is the
break will exit only a single loop.
Syntax:
break;
Continue:[skipping a part of a loop]
During the loop operations it may be necessary to skip a part of the body of the loop under
certain conditions.
Like the break statement java supports another similar statement called the continue
statement.
Unlike the break the continue on the name implies causes the loop to be continued with the
next iteration after skipping any statement s in between the continue statement tells the
compiler skip the following statements and continue with the next iteration. The format of
continue statement is as follows.
Syntax :
continue;
In while & do loops continue causes the control to go directly to the test condition and then
to continue the iteration process.
In case of for loop the increment section of the loop is executed before the test condition is
evaluated.