Oopsjava Notes 1& 2
Oopsjava Notes 1& 2
1
I. Program Structure in Java:
1. Introduction
Java is an Object Orient and high-level programming language, originally developed by
Sun Microsystems and released in 1995. Java runs on a variety of platforms, such as
Windows, Mac OS, Linux etc.
After import statement, every java program starts with the declaration of the class.
A program may have one or more classes.
A class declaration starts with the keyword class, followed by the identifier or name of the
class. Giving the name of a package at the top is optional.
Class declarion contains name of the class and body of the class. The body of the
class may consist of several statements and is enclsed between the braces {}.
Here:
public is access specifier. This class is accessible to any ouside code. Otherwise the
class is accessibe to only same package classes.
class is a keyword of java language which is used to declare the class.
The class body starts with the left brace { and ends with the right colsing brace }.
// are comments which are neglected by the compiler.
2
A class body may comprise statements for declaration of variables. constants,
expressions, and methods.
Here:
class is a keyword
Start is a name the class. Here class is declared as public, so it is available to
all the classes.
main() is the method which initiate and terminate the program ( in java
functions are called as Methods)
println() is method of object “out”. “out” is the object of class “System”.
println() prints the string “Hello World” on the screen/monitor.
Java compiler first converts the source code into an intermediate code, known as
bytecode or virtual machine code. To run the bytecode, we need the Java Virtual
Machie (JVM). JVM exists only inside the computer memory and runs on top of
the Operating System. The bytecode is not machine specific. The Java interpreter
converts the bytecode into Machine code. The following diagram illustrates the
process of compiling and running Java programs.
For compiling the program, the Java compiler javac is run, specifying the name of
the source file on the command line as depicted here:
javac Start.java
The Java compiler creates a file called Start.class containing the bytecode version
of the program. The java interpreter in JVM executes the instructions contained in
3
this intermediate Java bytecode version of the program. The Java interpreter is
called with “java” at the command prompt.
Output:
Hello World
Here java command calls the Java interpreter which executes the Start.class
(bytecode of Start.java).
Java program contains different types of elements like white spaces, comments and
tokens. A token is the smallest program element which is recognized by the
compiler and which treats them as defined for the compiler. A program is a set of
tokens which comprise the following elements:
Keywords: These are special words defined in Java and represent a set of
instructions.
• The keywords represent groups of instructions for the compiler.
• These are special tokens that have a predefined meaning and their use is
restricted.
• keywords cannot be used as names of variables, methods, classes, or packages.
• These are written in the lower case.
• Keywords of Java Language are as follows:
4
Literals: These are values represented by a set of character, digits, etc.
• A literal represents a value which may be of primitive type, String type, or null
type.
• The value may be a number (either whole or decimal point number) or a
sequence of characters which is called String literal, Boolean type, etc.
• A literal is a constant value.
Types of Literals:
i. Integer literals
• Sequences of digits.
• The whole numbers are described by different number systems such as decimal
numbers, hexadecimal numbers, octal numbers, and binary numbers.
• Each number has a different set of digits.
Decimal Integer Literals
• These are sequences of decimal digits which are 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9.
• Examples of such literals are 6, 453, 34789, etc.
Hex Integral Literals
• These are sequences of hexadecimal digits which are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
A, B, C, D, E, and F.
• The values 10 to 15 are represented by A, B, C, D, E, and F or a, b, c, d, e, and
f.
• The numbers are preceded by 0x or 0X. Examples are 0x56ab o0X6AF2, etc.
Octal Integer Literals
• These are sequences of octal digits which are 0, 1, 2, 3, 4, 5, 6, and 7.
• These numbers are preceded by 0. Examples of literals are 07122, 04, 043526.
Binary Literal
• These are sequences of binary digits.
• Binary numbers have only two digits—0 and 1 and a base 2.
• Examples of such literals are 0b0111001, 0b101, 0b1000, etc.
5
ii. Floating point literal
• These are floating decimal point numbers or fractional decimal numbers
with base 10. Examples are 3.14159, 567.78, etc.
v. String literal
• These are strings of characters in double quotes. Examples are “Delhi”,
“John”, “AA”, etc.
6
Operators: Operators are mostly represented by symbols such as +, -, *, etc
Types of Operators:
Arithmetic Operators:
Operator Description
+ Addition or Unary plus
- Subtraction or Unary minus
* Multiplication
/ Division
% Modulus
Relational Operators:
Operator Description
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
== Equal to
!= Not equal to
Logical Operators:
Operator Description
&& Greater than
|| Greater than or equal to
! Less than
Assignment Operators:
Operator Description
+= Add and assign to
-= Subtract and assign to
*= Multiply and assign to
/= Divide and assign to
%= Modulus and assign to
7
Bitwise Operators:
Operator Description
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
~ Bitwise compliment
>> Shift Right
<< Shift Left
>>> Shift right with Zero fill
Conditional Operators:
Operator Description
?: Used to construct Conditional expression
4. Java Statements
A Statement is a instruction to the computer. A program is a set of statements or
instructions. The statements specify the sequence of actions to be performed when
some method or constructor is invoked. The statements are executed in the sequence
in the specified order. The important Java statements are as follows.
Statement Description
Empty statement These are used during program development.
Variable declaration It defines a variable that can be used to store the values.
statement
Labeled statement A block of statements is given a label. The labels should not
be keywords, previously used labels, or already declared
local variables.
Expression statement Most of the statements come under this category. There are
seven types of expression statements that include
assignment, method call and allocation, pre-increment, post
increment, pre-decrement, and post decrement statements.
Control statement This comprises selection, iteration, and jump statements.
Selection statement In these statements, one of the various control flows is
selected when a certain condition expression is true. There
are three types of selection statements including if, if-else,
and switch.
Iteration statement These involve the use of loops until some condition for the
termination of loop is satisfied. There are three types of
iteration statements that make use of while, do, and for
Jump statement In these statements, the control is transferred to the
beginning or end of the current block or to a labeled
statement. There are four types of Jump statements including
break, continue, return, and throw.
Synchronization These are used with multi-threading
statement
Guarding statement These are used to carry out the code safely that may cause
exceptions (such as division by zero, and so on). These
statements make use of try and catch block, and finally
8
5. Command Line Arguments
• A Java application can accept any number of arguments from the command line.
• These arguments can be passed at the time of running the program. This enables a
programmer to check the behavior of a program for different values of inputs.
• When a Java application is invoked, the runtime system passes the command line
arguments to the application's main method through an array of strings.
• It must be noted that the number of arguments
•
• in an array. To ensure this, we can make use of the length property of the array. This is
illustrated in
class vehicle
public static void main(String args[])
{
int x = args.length;
for(int i=0; i<x; i++)
{
System.out.println(args[i]);
}
}
Output
(After compiling, type the following lines on the command prompt. It produces the output as)
9
Program 2.3: Illustration of command line
class Sum
{
public static void main{String args)
int s=1;
s=s+Integer.parseInt(args(1]);
Output
Declaration of Variables
• A program may involve variables: variables are objects whose values may change in the
program.
• A variable is declared by first writing its type, followed by its name or identifier as
illustrated here.
• However, a variable should also be initialized, that is, a value should be assigned to it
before it is used in an expression. The line ends with a semicolon (:) as shown in the
above figure.
Examples:
10
Program 2.4 illustrates the declaration and output of some data types
class PrintOut
{
public static void main (String args[])
{
String name = "Sunita"; //"name" is variable, value is "Sunita"
String str = "Hello"; //String set has value- "Hello!"
System. out.println();
c:\>javac PrintOut.java
c:\>java PrintOut
Name= SunitaStr = Hello
Length 50
Width 8
HelloSunita
11
Program 2.6: Illustration of a user's input from keyboard into
program
import java.util.Scanner;
public class Arithmetic
{
public static void main(String[] args)
{
Scanner scaninput = new Scanner (System. in);
int n;
int m;
System.out. print( "Enter the value of n : ");
n=scaninput.nextInt();
System.out. print( "Enter the value of m : ");
m=scaninput.nextInt();
Output
C:\>javac Arithmetic.java
C:\>java Arithmetic
Enter the value of n : 10
Enter the value of m : 3
Sum of two numbers is =13
Product of two numbers is =30
Modulus of (n % m) is =1
Division of two numbers is =3
C:\>
12
7. Escape Sequences
Escape Sequences character is preceded by a backslash (\)has a special meaning to
the compiler. Escape sequences are as follows.
class Escape
{
public static void main(String[] args)
{
int n=256, a=0, b=70;
System.out.println("Value of a =" + a + "\n b= "+b +"\n");
System.out.println("\u0041 \t" + " \u0042 \t"+"\132");
System.out.println("\"Value of b\" = "+b);
System.out.println("\'Value of n\' = " +n);
}
}
Output:
C:\>javac Escape.java
C:\>java Escape
Value of a =0
b= 70
A B Z
"Value of b" = 70
'Value of n' = 256
13
8. Comments
• Comments are Line of Text which is not a part of the compiled program.
• Comments are used for documentation to explain source code.
• They are added to the source code of the program.
• Java supports three types of comments as:
1. Single-line comment: These comments are started with two front slash
characters (//)
Example:
// This is Single line comment
3. Documentation comment: These comments are enclosed with /** and */. It
is different from multi line comments in that it can extracted by javadoc utility
to generate an HTML document for the program.
Example:
/** It is documentation
Comments */
9. Programming Style.
• An analysis of the programming exercises will throw some light on the look and feel of a
program. The team members should easily understand each other's code.
• For a beginner, it is better to develop a habit of writing a program in a proper style so that
there is no conflict between the current habits and the company's imposition of style rule
at a later stage.
• There are no set patterns of good style and bad style: however, if the programmer takes
care of a few requirements on the programs as discussed, the resulting style will be better
1. The program should present a clean and orderly look. In order to develop a clean
program, the programmer can adapt the following measures:
(b) Indenting is another method often used to improve the looks and readability
(c) Use of Lambda expression and method reference of Java 8 enhances the look
14
2. The program should be easy to understand. The programmer should take care of the
following aspects:
(a) If it is team work, certain conventions about naming should be preset so that a team
member can easily identify an item.
(b) The makers of Java have a set of rules which are followed in the Java library. The same
rules or an even better convention may be set.
(c) Judicial use of comments can increase understandability. Use of too many comments
makes confusion in the program.
(d) It is better to use already defined and tested library methods rather than user-defined
methods
3. Debugging should be easy. The programmer may adopt the following measures to
ensure easy debugging.
(a) The vertical alignment of a similar item enhances the ability to find errors.
(c) The variables should be declared close to the places of their use
(d) If it is a big program, it should be divided into small segments. In Java, it is easy because
the program may comprise separate classes.
(c) The names used should imply the output type such as price, weight, length, and so on.
(a) The program should be easily modifiable to ensure simplicity in fixing errors.
(b) The comments can help in modification of the program, fixing errors.
6. The program should be fail-safe. The failure of a program should not be catastrophic.
15
II. Data Types Variables and Operators :
I. Primitive data
4. Arrays
5. Methods
The primitive data and their types are defined independent of the classes and interfaces, and
the arrays and methods derive their types from the first three entities.
An array is n collection of items that may be of primitive type, class objects, or references.
The type of an array can be determined from the type of elements present in it.
• Data Type is the type of the data which computer accepts. Every variable and expression
has a data type that is known at the compile time.
• The declaration of data type with a variable or expression limits the types of values that a
variable can have or the expression it can evaluate.
• Java is an object-oriented programming language based on classes and interfaces.
• Java defines some primitive (basic) data types that are not reference types of any class or
interface. Eight primitive (basic) types of data are defined in Java. The type names are
also the keywords shown here in bold letters
1. Integral types—byte, short, int, long
2. Floating point types - float, double
3. Character type -char
4. Boolean type – Boolean values – True, False
There is a non-data type called void and no data can be of type void. This type is used for
methods that do not return any value.
Java is a case-sensitive language. This means that it takes Area, area, and AREA are three
different objects.
16
2. Declaration of Variables - Data Types
A variable is declared by first declaring its type followed by its identifier or name, which is
given as follows:
type Identifier;
Here type is the primitive data type and Identifier is the name of the variable.
Ex:
Non-primitive Types
These are the class and interface types. The name of a class or interface is the name of type.
A class object is declared as
Class_identifier object_identifier;
Interface_identifier reference_identifier;
Example:
Data Types
i. Integers
Integers are whole numbers, that is, they represent numbers that do not have a fractional part.
The integers can be declared in four types according to the size of memory allocated for them
byte
short
int
long
17
Program 3.1 illustrates the integer data types.
class DataType
{
public static void main (String args[])
{
byte a= 4, b=8 ;// variables of type byte
short c = 67, d = 98; // variables of type short
int e = 7000, f = 20000; // variables of type int
long secondsInYear = 365 * 24 * 60 * 60; // long type
//e=d+f;
System.out.println("(b + a) = " + (b+a));
System.out.println("b + a = " + b + a);
System.out.println("c = "+ c + " \td = " + d);
System.out.println("e = " + e + "\t f= " + f);
System.out.println("Seconds in a year = "+ secondsInYear);
}
}
Output:
ii. Characters
• A variable may have value in terms of a character in which the type of variable is char.
• These characters represent integer values.
• Java supports Unicode for the representation of characters.
• Unicode supports all the character sets of all the major languages of the world.
• The initial version of Unicode allocated 2 bytes for storing characters.
• The range of values for characters in the initial version of Unicode comprised from
‘\u0000’ to ‘\uffff ’ that is from 0 to 65535 both end values inclusive.
18
Program 3 2 illustrates anthmetic operations on character constants and variables
class Datachar {
public static void main (String args[])
{
char ch1='E', ch2, ch3 ;
ch2=ch1++;
System.out.println("ch2 =" + ch2); // printing ch2
ch3=++ch1;
System.out.println("ch3 =" + ch3); // printing ch3
}
}
Output:
C:\ >javac Datachar.java
C:\ >java Datachar
ch1 =E
ch2 =E
ch3 =G
iii. Floating Point Numbers
• The numbers that are not whole numbers, or those that have fractional part, Examples are
3.141, 476.6, and so on.
• Java supports two types of such numbers.
Float: This type is used for single-precision decimal floating point numbers, that is, 7 digits
after the decimal point. These numbers are stored on 4 bytes.
Program 3.4: Illustration for working with float and double data
class FloatType
{
public static void main (String args[])
{
float width =20.0f, length = 40.5f;
float rectArea = length * width;
C:\>javac FloatType.java
C:\>java FloatType
Width = 20.0
Length = 40.5
Rectangle Area = 810.0
Diameter 10.0
Area of Circle = 78.53975
If the aforementioned logical statement is correct, The value of a is true, otherwise the value
of a is false. In Java true and false are not converted into numerical values, which is
the case in other Languages. A boolean type variable is allocated to one byte, that is, 8 bits
for storing its values Program
class Boolean
{
public static void main (String args[])
{
double x= 5.5, y=10.5, p=4.0;
int n=40, m=50;
boolean a,b,c,d;
a= x>y;
b= y>p;
c= y==x;
d= x<=y;
C:\>javac Boolean.java
C:\>java Boolean
a = false and b =true
Now c= false and d = true
20
3. Type Casting
Converting one data type to another data type is called as Type Casting. There are two types
of type casting. They are,
i. Implicit Type casting
ii. Explicit Type casting
i. Implicit Type casting
Implicit type casting is done automatically by a compiler when we assign a value to the
variable.
Example:
int a=10;
double b;
b=a;
Here a is integer and d is double variables. Integer value is automatically converted into
double by the compiler.
d=c/a;
k=a+y;
e = a + (int)y;
z=(double)c/a;
21
Output
1. The scope starts from the point the variable is defined in the block (declared and value
assigned to it).
2. Although the variable may be defined anywhere in a block, it can be used only in the
statements appear ing after its definition Therefore, there is no use in defining a variable at
the end of block.
If there are nested blocks, a variable defined in the outer block is visible in the inner blocks
also and it cannot be redefined with the same name in the inner blocks
22
E:\>javac ScopeA.java
E:\>java ScopeA
Class Scope variable - outside main() x = 5
Variable y Scope within main() y = 10
Variable z Scope within Anonymous Block z = 20
E:\>java ScopeA
i. Literal Constants
A Symbolic constant is a variable whose value does not change throughout the program.
Some of the examples include PL NORTH, EAST etc.
It is usually preferred to declare the symbolic constants using all the capital letters in a
program as follows:
23
Program 3.13 illustrates the use of symbolic constant
C:\>javac SymbolicConst.java
C:\>java SymbolicConst
radius=25.0
Perimeter of circle = 157.079632675
• The formatting string specifics the output format for each variable that consists of
percent (%) sign followed by a conversion letter.
• Thus, the format string for output of an integer and character is "X" and or
respectively.
• The order of variables in variable list should match with the list of formats in
formatting string.
• The following Table lists the conversion letters for different types of variables.
24
Program 3.14: illustration of formatting strings for output of different types of variables
class FormatPrintf
{
public static void main(String args[])
{
int n = 713;
float x = 45.86f;
double d= 56.754;
25
Output
C:\>javac FormatPrintf.java
C:\>java FormatPrintf
713 45.860001 56.754000 A Delhi
Hexadecimal value of 163 = A3
Octal value of 163 = 243
Static Variables:
• The static variables are class variables. Only one copy of such variables is kept in the
memory and all the objects share that copy.
• The static variables are accessed through class reference, whereas the instance
variables are accessed through class object reference
• The variables in a class may be modified by modifier static.
• The non-static variables declared in a class are instance variables Each object of the class
keeps a copy of the values of these variables.
Static Methods:
• The static methods are similar to class methods and can be invoked without any reference
of object of class, however, class reference (name of class) is needed, as in the following
example The method like sart() is declared as static method in Math class and is called
The static method is called using the method name that is preceded by the class name; in this
case. Math and period ().
26
E:\>javac StaticMethods.java
E:\>java StaticMethods
The Square root root of 16 = 4.0
The cubroot root of 27 = 3.0
Random Number 1 = 77
Random Number 2 = 69
Random Number 3 = 83
Random Number 4 = 2
Random Number 5 = 66
E:\>java StaticMethods
The Square root root of 16 = 4.0
The cubroot root of 27 = 3.0
Random Number 1 = 67
Random Number 2 = 31
Random Number 3 = 10
Random Number 4 = 13
Random Number 5 = 40
8. Attribute Final
Final Variable:
The value of a variable declared final cannot be changed in the program. It makes the
variable a constant. A few examples of declarations are as follows:
• As mentioned in the comments, the values of PI, M, and x cannot be changed in their
respective scopes.
Final Method:
• The attribute final may be used for methods as well as for classes. These are basically
connected with inheritance of classes.
• When final keyword is used with Java method, it becomes the final method.
• A final method cannot be overridden in a sub-class.
Final Class:
• A Java class with final modifier is called final class A final class cannot be sub-classed or
inherited. Several classes in Java are final including String, Integer, and other wrapper
classes.
27
• There are certain important points to be noted when using final keyword in Java
i. New value cannot be reassigned to a variable defined as final in Java.
ii. Final keyword can be applied to a member variable, local variable, method, or class.
iii. Final member variable must be initialized at the time of declaration.
iv. Final method cannot be overridden in Java
v. Final class cannot be inheritable in Java
vi. Final is different from finally keyword, which is used on Exception handling in Java
Example- 1:
public class Final
{
public static void main (String args[])
{
Output:
C:\>javac Final.java
Final.java:13: error: cannot assign a value to final variable f
f = 60; // Error : f is final variable can not be changed
^
1 error
C:\>
Example-2:
28
C:\>javac Final.java
C:\>java Final
n = 10
f = 20
n = 50
9. Introduction to Operators
An operator is a symbol that tells the computer to perform certain mathematical and
logical calculations.
-The different types of Java operators are,
a) Arithmetic operators
b) Relational operators
c) Logical operators
d) Increment or decrement operators
e) Assignment operators
f) Conditional operators
g) Bitwise operators
h) Special operators
29
11. Assignment Operator ( = )
Assignment operators:
-Assignment operators are used to assign the result of an expression to a variable.
Operator Meaning
= Assignment
-In addition, java has a set of short-hand assignment operators of the form
V OP=EXP;
- It is equivalent to
V=V OP EXP;
-The short-hand assignment operators are
+= , -= , *= , /= , %=
Example:
a+=b ------------- a=a+b
a-=b ------------- a=a-b
a*= b -------------- a=a*b
a/=b --------------- a=a/b
a%=b ------------- a=a%b
Example:
if(a>b)
System.out.println(“a is greater”);
else
System.out.println (“b is greater”);
31
16. Boolean Logical Operators
-The java language has three logical operators.
Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT
-The logical operators &&, || are used when we we want to test more than one condition.
&& - used when all the conditions must be true.
|| - used when any of the conditions must be true.
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
~ One’s complement
Bitwise AND operator:
-The Bitwise AND (&) is a binary operator that requires two integral operands(character
or integer).
-It does a bit-by-bit comparison between two operands.
-The result of the comparison is 1 only when both bits are 1, otherwise it is 0.
First operand bit Second operand bit Result(&)
0 0 0
0 1 0
1 0 0
1 1 1
32
Bitwise OR operator:
-The Bitwise inclusive OR (|) is a binary operator that requires two integral
operands(character or integer).
-It does a bit-by-bit comparison between two operands.
-The result of the comparison is 0 only when both bits are 0, otherwise it is 1.
33
18. Special Operators.
- Java supports some special operators such as,
a) instanceof operator
b) member selection operator
a) 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 instanceof student
- It is true if the object person belongs to the class student, otherwise it is false.
34
III. Control Statements:
1. Introduction
CONTROL STATEMENTS: (FLOW OF CONTROL)
- A Control statement is a statement used to control the flow of execution in a Java Program.
SELECTION STATEMENTS:
-Also called as conditional or decision-making control statements.
-There are two types in Selection control statements.
i) Two-way selection control statements
ii) Multi-way selection control statements
i) Two-way selection control statements:
-The different two-way selection statements are,
a) if-else statement
b) null else statement
c) Nested-if statement
Example:
if(a==2)
{
p++;
}
System.out.println(“program over”);
35
3. Nested if Expressions
-if within if is called as Nested-if.
Syntax:
if(condition-1)
{
if(condition-2)
{
Statement-1;
}
else
{
Statement-2;
}
}
else
{
if(condition-3)
{
Statement-3;
}
else
{
Statement-4;
}
}
next statement;
Example:
if(a>b)
{
if(a>c)
{
System.out.println(“a is greater”);
}
else
{
System.out.println (“c is greater”);
}
}
else
{
if(b>c)
{
System.out.println(“b is greater”);
}
else
{
System.out.println(“c is greater”);
}
}
36
4. if–else Expressions
Syntax:
if(condition)
{
true-block statements;
}
else
{
false-block statements;
}
next statement;
Example:
if(a>b)
{
System.out.println(“a is greater”);
}
else
{
System.out.println(“b is greater”);
}
37
Example:
if(a>b&&a>c&&a>d)
{
System.out.println(“a is greater”);
}
else if(b>a&&b>c&&b>d)
{
System.out.println(“b is greater”);
}
else if(c>a&&c>b&&c>d)
{
System.out.println(“c is greater”);
}
else
{
System.out.println(“d is greater”);
}
5. Ternary Operator?:
In Java, the ternary operator is a type of Java conditional operator. The meaning
of ternary is composed of three parts.
The ternary operator (? :) consists of three operands. It is used to evaluate Boolean
expressions. The operator decides which value will be assigned to the variable. It is the only
conditional operator that accepts three operands.
It can be used instead of the if-else statement. It makes the code much more easy, readable,
and shorter.
Syntax:
Expression1 ? Expression2 : Expression3
Example-1:
int a=10;
int b = (a<20)? 100 :200; // a < 20 if statement
System.out.println("b= "+b);
}
}
38
Output:
C:\>javac Ternary.java
C:\>java Ternary
b= 100
Example-2:
Output:
C:\>javac Ternary.java
C:\>java Ternary
b= 200
6. Switch Statement
Syntax:
switch(expression)
{
case value-1:statement-1;break;
case value-2:statement-2;break;
………………………….
………………………….
case value-n:statement-n;break;
default: default statement;
}
next statement;
Example:
switch(digit)
{
case 0: System.out.println(“ZERO”);break;
case 1: System.out.println(“ONE”);break;
case 2: System.out.println(“TWO”);break;
case 3: System.out.println(“THREE”);break;
case 4: System.out.println(“FOUR”);break;
case 5: System.out.println(“FIVE”);break;
case 6: System.out.println(“SIX”);break;
case 7: System.out.println(“SEVEN”);break;
case 8: System.out.println(“EIGHT”);break;
case 9: System.out.println(“NINE”);break;
default: System.out.println(“Enter between 0-9”);
}
39
7. Iteration Statements
LOOP STATEMENTS:
-The iteration control statements are also called as Repetition or Iteration control statements.
-A looping process includes the following four steps.
-Setting and initialization of a counter.
-Execution of the statements in the loop body.
-Test for a specified condition (loop control expression) for execution of a loop
-Incrementing or Decrementing counter.
i) Pretest and Posttest loops:
-In a Pretest loop, the condition is checked before we execute a loop body.
-It is also called as entry-controlled loop.
-In the Posttest loop, we always execute the loop body atleast once.
-It is also called as exit-controlled loop.
8. while Expression
a) while statement:
Syntax:
while(condition)
{
loop body;
}
next statement;
Example:
n=10,i=1,sum=0;
while(i<=n)
{
sum=sum+i;
i++;
}
System.out.println(“sum=”+sum);
40
9. do–while Loop - for Loop
Syntax:
do
{
loop body;
}while(condition);
next statement;
Example:
n=10,i=1,sum=0;
do
{
sum=sum+i;
i++;
} while(i<=n);
System.out.println(“sum=”+sum);
Example:
n=10,i,sum=0;
for(i=1;i<=n;i++)
{
sum=sum+i;
}
System.out.println(“sum=”+sum);
41
11. Nested for Loop
Syntax:
for(initialization;condition;inc or dec)
{
for(initialization;condition;inc or dec)
{
Inner loop body;
}
Example:
n=10,i, j, sum=0;
for(i=1;i<=n;i++)
{
sum=sum+i;
}
System.out.println(“sum=”+sum);
42
12. For–Each for Loop
The Java for-each loop or enhanced for loop. It provides an alternative approach to traverse the array
or collection in Java. It is mainly used to traverse the array or collection elements. The advantage of
the for-each loop is that it eliminates the possibility of bugs and makes the code more readable. It is
known as the for-each loop because it traverses each element one by one.
Advantages:
1. Less clutter in code, especially when iterators are used.
2. Less chances of errors.
3. Improves overall readability of program.
Limitations:
1. It is designed to iterate in forward direction only.
2. In iteration, it takes a single step at a time.
3. It cannot simultaneously traverse multiple arrays or collections.
Syntax:
Example:
Output:
C:\>javac ForEach.java
C:\>java ForEach
10
20
30
40
50
43
13.Break Statement
Unconditional control statements:
-The unconditional control statements are,
a) break statement
b) continue statement
break statement:
-The break statement skips from the loop or block in which it is defined.
-The control then automatically goes to the first statement after the loop or block.
-The general format is
break;
Example:
Output:
C:\>javac Break.java
C:\>java Break
0
1
2
3
4
44
14. Continue Statement.
-The continue statement is used for continuing next iteration of loop statements.
-When it occurs in the loop, it does not terminate but it skips the statements after it.
-It is useful when we want to continue the program without executing any part of the program.
-The general format is
continue;
Example:
C:\>java Continue
0
1
2
3
4
6
7
8
9
Here 5 is not printed because of continue statement. The Iteration at the condition i = =5 is
skipped or jumped to next statement.
45
UNIT-2
II. Methods:
1. Introduction
2. Defining Methods
3. Overloaded Methods
4. Overloaded ConstructorMethods
5. Class Objects as Parameters in Methods
6. Access Control
7. Recursive Methods
8. Nesting of Methods
9. Overriding Methods
10. Attributes Final and Static.
www.Jntufastupdates.com 1
I. Program Structure in Java:
Objects:
- Objects are basic run-time entities in an object-oriented system.
(or)
Any real world entity is called an object.
(or)
Objects are the combination of data and methods.
Example: Person, Place, bank account, …., so on.
- In the real-world only objects are visible but classes are invisible.
- The most important benefits of an objects are
- Modularity
- Reusability
- The properties of objects are two types
- visible
- invisible
- Let man is an object, then visible properties are eyes, ears, hands, legs,…so on and
invisible properties are name, blood group,…. so on.
- Every object contains three basic elements
- Identity (name)
- State (variables)
- Behavior (methods)
A class declaration starts with the Access modifier. It is followed by keyword class,
which is followed by the name or identifier. The body of class is enclosed between a pair
of braces { }.
www.Jntufastupdates.com 2
Syntax:
Example:
The class name starts with an upper-case letter, whereas variable names may start win
lower-case letters.
In the case of names consisting of two or more words as in MyFarm, the other words for
with a capital letter for both classes and variables. In multiword identifiers, there is no
blank space between the words
The class names should be simple and descriptive.
Class names should start with an upper-case letter and should be nouns. For example, it
could include names such as vehicles, books, and symbols.
It should have both upper and lower-case letters with the first letter capitalized
Acronyms and abbreviations should be avoided
Class modifiers:
Class modifiers are used to control the access to class and its inheritance characteristics.
Java consists of packages and the packages consist of sub-packages and classes Packages
can also be used to control the accessibility of a class
These modifiers can be grouped as (a) access modifiers and (b) non-access modifiers.
Table 5.l gives a description of the various class modifiers.
www.Jntufastupdates.com 3
Examples:
1. A class without modifier.
class Student
{
/* class body*/
}
2. A class with modifier
public class Student
{
/* class body*/
}
(or)
(or)
(or)
www.Jntufastupdates.com 4
final class Student
{
/* class body*/
}
(or)
3. Class Members
The class members are declared in the body of a class. These may comprise fields (variables in a
class). methods, nested classes, and interfaces. The members of a class comprise the members
declared in the class as well as the members inherited from a super class. The scope of all the
members extends to the entire class body.
1. Non Static variables : These include instance and local variables and vanes in scope and
value.
(a) Instance variables: These variables are individual to an object and an object keeps a
copy of these variables in its memory.
(b) Local variables: These are local in scope and not accessible outside their scope.
2. Class variables ( Static Variables) : These variables are also qualified as static variables.
The values of these variables are common to all the objects of the class. The class keeps
only one copy of these variables and all the objects share the same copy. As class
variables belong to the whole class, these are also called class variables.
www.Jntufastupdates.com 5
Example:
class CustomerId
{
static int count=0; // static variable
int id; // instance variable
CustomerId() // Constructor
{
count++;
id = count ;
}
int getId() // Method
{
return id;
}
int localVar()
{
int a=10; //Local variable
return a;
}
}
class Application
{
public static void main(String[] args)
{
CustomerId obj = new CustomerId();
System.out.println("Customer Id = " + obj.getId());
System.out.println("Local Variable = " + obj.localVar());
}
}
Output:
C:\>javac Application.java
C:\>java Application
Customer Id = 1
Local Variable = 10
www.Jntufastupdates.com 6
4. Declaration of Class Objects
Creating an object is also referred to as instantiating an object.
- Objects in java are created dynamically using the new operator.
- The new operator creates an object of the specified class and returns a reference to that
object.
Syntax: (creating an object)
Example:
www.Jntufastupdates.com 7
5. Assigning One Object to Another
Java provides the facility to assign one object to another
object
Syntax:
new_Object = old_object;
all the properties of old_object will be copied to new object.
Example:
class Farm
{
double length;
double width;
double area()
{
return length*width;
}
}
public class FarmExel
{
public static void main (String args[])
{
Farm farm1 = new Farm(); //defining an object of Farm
Farm farm2 = new Farm(); //defining new object of Farm
farm1.length = 20.0;
farm1.width = 40.0;
}
}
Output:
C:\>javac FarmExel.java
C:\>java FarmExel
Area of form1= 800.0
Area of form2 = 800.0
www.Jntufastupdates.com 8
6. Access Control for Class Members
In Java, There are three access specifiers are permitted:
• public
• protected
• private
The coding with access specifiers for variables is illustrated as
Private members of a class, whether they are instance variables or methods, can only be
accessed by other members of the same class
Any outside code cannot directly access them because they are private. However,
interface public method members may be defined to access the private members
The code other than class members can access the interface public members that pass on
the values.
Example:
www.Jntufastupdates.com 9
class FarmExe3
{
public static void main (String args[])
{
farm1.setSides(50.0,20.0);
farmArea = farm1.area();
}
}
Output
C:\>javac PrivateMembers.java
C:\>java FarmExe3
Area of farm1 = 1000.0
Length of farm1 = 50.0
Length of farm1 = 20.0
In the above program, the two object variables length and width are declared private. The
first thing is to assign values to these variables for an object. This is done by defining a public
method setSides(), which is invoked by the class object for entering values that are passed
to length and width variables The method setsides may be defined as
public void setsides (int 1, int w){length = 1; width = w;}
The class also defines another method area() to which the values are passed for calculation
of area when the method area() is invoked by the object. For obtaining values of length and
width by outside code, two public methods are defined as
These methods may be invoked by objects of the class to obtain the values of variables as
follows:
farm1.getLength()
farm1.getWidth()
www.Jntufastupdates.com 10
8. Constructor Methods for Class
- A constructor is a special method of the class and it is used to initialize an object whenever
the object is created.
- A Constructor is a special method because,
Class name and Constructor name both must be same
Doesn’t contain any return type
Automatically executed when object is created.
- Constructors are two types
i. Default Constructor (without arguments)
ii. Parameterized Constructor (with arguments)
Example:
class Perimeter
{
Perimeter() // default Constructor
{
System.out.println("No parameters");
}
Perimeter(double r) // Parameterized Constructor
{
System.out.println("Perimeter of the Circle="+(2*3.14*r));
}
Perimeter(int l, int b) // Parameterized constructor
{
System.out.println("Perimeter of the Rectangle="+(2*(l+b)));
}
}
class ConstructorDemo
{
public static void main(String args[])
{
Perimeter p1=new Perimeter();
Perimeter p2=new Perimeter(10);
Perimeter p3=new Perimeter(10,20);
}
}
Output
E:\>javac ConstructorDemo.java
E:\>java ConstructorDemo
No parameters
Perimeter of the Circle=62.800000000000004
Perimeter of the Rectangle=60
www.Jntufastupdates.com 11
9. Overloaded Constructor Methods
Like other methods, the constructors may also be overloaded. The name of all the
overloaded constructor methods same as the name of the class, but parameters have to
be different either in number of type a order of parameters in each definition.
Example:
class Perimeter
{
Perimeter()
{
System.out.println("No parameters");
}
Perimeter(double r) //Constructor Overloading
{
System.out.println("Perimeter of the Circle="+(2*3.14*r));
}
Perimeter(int l, int b) // Constructor Overloading
{
System.out.println("Perimeter of the Rectangle="+(2*(l+b)));
}
}
class ConstructorDemo
{
public static void main(String args[])
{
Perimeter p1=new Perimeter();
Perimeter p2=new Perimeter(10);
Perimeter p3=new Perimeter(10,20);
}
}
Output
C:\>javac ConstructorDemo.java
C:\>java ConstructorDemo
No parameters
Perimeter of the Circle=62.800000000000004
Perimeter of the Rectangle=60
www.Jntufastupdates.com 12
10.Nested Classes
A nested class is one that is declared entirely in the body of another class or interface. The
class, which is nested, exists only long as the enveloping class exists. Therefore, the scope of
inner class is limited to the scope of enveloping class. There are four types of nested class.
Nested static class is like any other static member of the enveloping class.
i. Member Inner Class.
ii. Anonymous Class
iii. Local Class
iv. Static Nested Class
Example:
class Outer
{
double outer_x;
double outer_y;
Outer (double a, double b)
{
outer_x = a;
outer_y = b;
}
double outer_add()
{
return outer_x+outer_y;
}
void outer_display()
{
Inner in = new Inner();
in.inner_display();
}
www.Jntufastupdates.com 13
class NestedClassDemo
{
public static void main (String args[])
{
Outer obj =new Outer(10,20);
obj.outer_display();
}
}
Output:
C:\>javac NestedClassDemo.java
C:\>java NestedClassDemo
x+y = 30.0
www.Jntufastupdates.com 14
ii. Anonymous Class
Anonymous classes are inner classes without a name.
It is defined inside another class. Because class has no name it cannot have a constructor
method and its objects cannot be declared outside the class.
Therefore, an anonymous class must be defined and initialized in a single expression.
An anonymous class may be used where the class has to be used only once.
An anonymous class extends a super class or implements an interface, but keywords extend
or implements do not appear in its definition. On the other hand, the names of super class and
interface do appear.
An anonymous class is defined by operator new followed by class name it extends, argument
list for the constructor of super class, and then the anonymous class body.
Example:
abstract class Person
{
abstract void display(); //abstract method
}
class AnonymousClass
{
public static void main (String args[])
{
Person obj = new Person() { // Creating an object of Anonymous class
void display()
{
System.out.println("In display() method ");
}
}; // anonymous class closes
Output:
-------
C:\>javac AnonymousClass.java
C:\>java AnonymousClass
In display() method
www.Jntufastupdates.com 15
iii. Local Class
A local class is declared in a block or a method, and hence, their scope is limited to the
block of method. The general properties of such classes are as follows
o These classes can refer to local variables or parameters, which are declared final
o These are not visible outside the block in which they are declared and hence, the
access modifiers such as public, private, or protected do not apply to local
classes.
Example:
Example:
class LocalClassDemo
{
public static void main (String args[])
{
class Local // Local class defined
{
int x;
Local(int a) { x =a; }
public void display()
{
System.out.println("x = "+ x);
}
}
Output
C:\>javac LocalClassDemo.java
C:\>java LocalClassDemo
x = 10
The main benefit of Static Nested classes is that their reference is not attached to outer
class reference.
Object may be accessed directly.
These classes cannot access non-static variables and methods. They can access only static
variables and methods
Static nested class can be referred by its class name.
www.Jntufastupdates.com 16
Example:
class Outer
{
static double outer_x;
static double outer_y;
Outer (double a, double b)
{
outer_x = a;
outer_y = b;
}
static double outer_add()
{
return outer_x+outer_y;
}
static void outer_display()
{
Inner in = new Inner();
in.inner_display();
}
class StaticNestedClass
{
public static void main (String args[])
{
Outer obj =new Outer(10,20);
obj.outer_display();
}
}
Output:
C:\>javac StaticNestedClass.java
C:\>java StaticNestedClass
x+y = 30.0
www.Jntufastupdates.com 17
11.Final Class and Methods
A final class is a class that is declared as a final which cannot have a subclass
Example:
final class A
{
int a;
A(int x) {a=x;}
void display()
{
System.out.println("a = "+ a);
}
}
class B extends A
{
int b;
B(int x,int y)
{
super(x);
this.b=y;
}
void display()
{
System.out.println("b = "+ b);
}
}
class FinalClass
{
public static void main (String args[])
{
A objA= new A(10);
B objB= new B(100,200);
objA.display();
objB.display();
}
}
Output:
C:\>javac FinalClass.java
FinalClass.java:11: error: cannot inherit from final A
class B extends A
^
1 error
www.Jntufastupdates.com 18
12. Passing Arguments by Value and by Reference
Arguments are the variables which are declared in the method prototype to receive the
values as a input to the Method( Function).
Example:
i. Call by value
In call by value actual arguments are copied in to formal arguments.
Example:
class Swap
{
int a,b;
void setValues(int p, int q)
{
a=p;
b=q;
}
void swapping()
{
int temp;
temp =a;
a=b;
b=temp;
}
void display()
{
System.out.println("In Swap Class: a= "+a+" b= "+b);
}
www.Jntufastupdates.com 19
}
class CallByValue
{
public static void main (String args[])
{
int x=10,y=20;
System.out.println("Before Swap : x= "+x+ " y="+y);
Swap obj =new Swap();
obj.setValues(x,y);
obj.swapping();
obj.display();
System.out.println("After Swap : x= "+x+ " y="+y);
}
}
Output:
C:\>javac CallByValue.java
C:\>java CallByValue
Before Swap : x= 10 y=20
In Swap Class: a= 20 b= 10
After Swap : x= 10 y=20
Example:
class Swap
{
int a,b;
void setValues(Swap objSwap)
{
a = objSwap.a;
b = objSwap.b;
}
void swapping()
{
int temp;
temp =a;
a=b;
b=temp;
}
void display()
{
System.out.println("In Swap Class: a= "+a+" b= "+b);
}
}
www.Jntufastupdates.com 20
class CallByReference
{
public static void main (String args[])
{
Swap obj =new Swap();
obj.a=10;
obj.b=20;
System.out.println("Before Swap : obj.a = "+ obj.a+" obj.b="+ obj.b);
Output:
C:\1. JAVA\PPT Programs>javac CallByReference.java
Example:
class Add
{
int a,b;
void setValues(int a, int b)
{
this.a = a;
this.b = b;
}
void add()
{
System.out.println("Sum = "+ (a+b) );
}
}
class ThisKeyword
{
public static void main (String args[])
{
www.Jntufastupdates.com 21
Add obj= new Add();
obj.setValues(10,20);
obj.add();
}
}
Output:
C:\ >javac ThisKeyword.java
www.Jntufastupdates.com 22
II. Methods
1. Introduction
A method in Java represents an action on data or behaviour of an object. In other
programming languages, the methods are called functions or procedures.
2. Defining Methods
A method definition comprises two components:
1. Header that includes modifier, type, identifier, or name of method and a list of
parameters.
• The parameter list is placed in a pair of parentheses.
2. Body that is placed in braces ({ }) and consists of declarations and executable
statement and other expressions.
Method definition:
Modifier return_type method_name (datatype Parameter_Name,…)
{
/*Statements --
Body of the method*/
}
www.Jntufastupdates.com 23
Modifier description is as follows.
Example:
class Add
{
int a,b;
void setValues(int x, int y) // method with two arguments
{
a = x;
b = y;
}
Output:
C:\ >javac MethodDemo.java
www.Jntufastupdates.com 24
3. Overloaded Methods
Methods with the same name and scope are permitted provided they have different
signatures that include the following:
i. Number of parameters
ii. Data types of parameters
iii. Their order in the parameter list
The compiler executes the version of the method whose parameters match with the
arguments. For example, the following types of declarations in the scope are permissible:
www.Jntufastupdates.com 25
Example:
class Add
{
int a,b;
void setValues(int a, int b) // method with two arguments
{
this.a = a;
this.b = b;
}
void add() // method without arguments
{
System.out.println("In add() method Sum = "+ (a+b) );
}
//Method overloding - integer datatype arguments
void add(int a, int b)
{
System.out.println("In add(int, int) Method- sum= "+ (a+b) );
}
class MethodOverload
{
public static void main (String args[])
{
Add obj= new Add();
obj.setValues(10,20); // method calling
obj.add(); // calling method without arguments
obj.add(15,30);// calling method with integer datatype arguments
obj.add(10.3, 30.4); // calling method with double datatype arguments
}
}
C:\>javac MethodOverload.java
C:\>java MethodOverload
In add() method Sum = 30
In add(int, int) Method- sum= 45
www.Jntufastupdates.com 26
In add(double, double) MethodSum = 40.7
A constructor method has the same name as the name of class to which it belongs. It has
no type and it does not return any value. It only initializes the object.
The constructor method may also be overloaded by changing the number of default values.
Therefore, constructors with different parameters may be declared. For the remaining
parameters, it will pick up default values when these are not specified in the object definition.
www.Jntufastupdates.com 27
Example:
class AddDemo
{
int a,b;
AddDemo() // Constructor without arguments
{
a=10;
b=20;
}
class ConstructorOverload
{
public static void main (String args[])
{
AddDemo obj1= new AddDemo(); //calling constructor without arguments
obj1.add();
Output:
C:\>javac ConstructorOverload.java
C:\>java ConstructorOverload
a = 10, b = 20: Sum = 30
a = 150, b = 60: Sum = 210
www.Jntufastupdates.com 28
5. Class Objects as Parameters in Methods
Objects can be passed as parameters to the Methods just like
primitive data types. It is called as Call by Reference.
Example:
class AddDemo
{
int a,b;
Output:
C:\>javac ObjectAsParameter.java
C:\>java ObjectAsParameter
Sum = 230
6. Access Control
Java supports access control at the class level and at the level of class members. At the class
level, the following two categories are generally used:
i. default case no modifier applied : In the default case, when no access specifier is
applied, the class can be accessed by other classes only in the same package
ii. public : A class declared public may be accessed by any other class in any package.
In a class, Java supports the information hiding mechanism so that the user of a class does not
get to know how the process is taking place. A class contains data members and method
members or a nested class.
To access any of the members data method, or nested class-can be controlled by the
following modifiers.
i. private
ii. protected
www.Jntufastupdates.com 29
iii. public
iv. default case-no modifier specified
i. private : The private members can only be accessed by the other members
(methods) of the same class. No other code outside the class can access them.
Ex:
private int x;
private int getx()
{
return x;
}
ii. protected : The protected members can accessed by own class and derived class
only.
protected int x;
protected int getx()
{
return x;
}
iii. public : The public members can accessed by all the classes.
Ex:
public int x;
public int getx()
{
return x;
}
iv. default case ( no modifier specified ): The default members can accessed by all the
classes within the package only.
int x;
int getx()
{
return x;
}
www.Jntufastupdates.com 30
7. Recursive Methods
A Method which is calling itself is called as Recursive Method.
Example: Recursive method to find factorial of a given number.
class Fact
{
int factorial (int n)
{
if(n<2)
return n;
else
return n*(factorial(n-1));
}
class FactDemo
{
public static void main(String[] args)
{
Fact obj =new Fact();
int n=5;
int res = obj.factorial(n);
System.out.println("Factorial of " + n + " = " +res);
}
}
Output:
C:\>javac FactDemo.java
C:\>java FactDemo
Factorial of 5 = 120
www.Jntufastupdates.com 31
8. Nesting of Methods
A method calling in another method with in the class is called as Nesting of
Methods.
Example:
class Rectangle
{
void perimeter(int l, int w)
{
System.out.println("Length ="+l+", Width= "+w);
System.out.println("Perimeter = " + (l+w));
}
class RectangleDemo
{
public static void main(String[] args)
{
Rectangle obj = new Rectangle();
obj.area(5,4);
}
}
Output:
C:\ >javac RectangleDemo.java
9. Overriding Methods
See this topic in Inheritance.
www.Jntufastupdates.com 32