JAVA_UNIT_1-2

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 61

Object Oriented

Programming
Using

Java
Java programming

UNIT 1
1. Introduction to Java
1.1. Basics of java programming
1.2. Data types
1.3. Variables
1.4. Operators
1.5. Control structures including selection
1.6. Looping
1.7. Java methods
1.8. Overloading
1.9. Math class
1.10. Arrays in Java
2. Objects and classes
2.1. Objects and classes
2.2. Basics of objects and classes in java
2.3. Constructors
2.4. Finalizer
2.5. Visibility modifiers
2.6. Methods and objects
2.7. Inbuilt classes like string
2.8. Character
2.9. String buffer
2.10. File
2.11. This reference
Java programming

UNIT 01. INTRODUCTION TO JAVA


1

1.1. BASICS OF JAVA PROGRAMMING


HISTORY OF JAVA:
Java is a high level Object Oriented Programming Language, developed by
. The first name of the java is “Oak”

Goals of Oak programing:


1. Platform independent
2. Extremely reliable
3. Compact

James Gosling
Bill joy
Patric Noughten
} are the father (developers) of java programing.

Why the name Java?


The James Gosling and his team members were consuming lot of coffee
while developing this language. So the coffee has the own role in developing
this language and good quality coffee is exported from the place called Java,
hence this name is Java.
The symbol for Java language is coffee cup and saucer.

Features of Java:
1. SIMPLE
The allocation of the memory in java program is automatic and the garbage
collection is also done by automatic. Compared to C and C++ the general syntax of
java language is very easy so that Java language is very simple.

2. SECURE
Java programming provides network based applications firewalls, are strictly
written in Java for the execution of Java environment. Java is a protecting
application of the software from virus infection so that the java is secured.

1
Java programming
3. PORTABLE
The translation of the Java programing into the byte code is done by Java Virtual
Machine (JVM) and there is no any difference for all operating system known as
portable.
4. OBJECT ORIENTED
Java is Pure Object oriented programming because all the programs must be written
in class only. Without class do not built the Java programs. Classes, objects,
inheritance, interface, multithreading are the object oriented programming
concept.
5. ROBUST
Java is used to allocate the memory and de-allocate the memory is automatic that
means garbage collection. So that, Java is Robust.
6. MULTI-THREADED
The two or more program can executed at same time or concurrently or
simultaneously.
7. ARCHITECTURE
It is used to execute the Java programs in all types of operating systems and WORA
(Write Once and Run Anywhere) in the same programs.
8. INTERPRETED AND PERFORMANCE
The Java Virtual Machine is used to convert from source code to byte code with the
help of java interpreter, java command.
9. DISTRIBUTED
It is used to distribute the java programing files in surrounding area with the help
of the internet or TCP/IP.
10. DYNAMIC
Whenever you have to change the program code that must be compiled and run the
program otherwise cannot execute the current result of the program that means
the program is re-solved so the java is Dynamic.

Platform independent language Java


The Java Virtual Machine [JVM] is used to support the execution of the java program
in any type of an operating system such as UNIX, Windows, Linux and Mac OS. Java
can execute the Java programs in all types of operating systems and WORA [Write
Once Run Anywhere]. So that Java is portable and platform independent programming
language.

2
Java programming
Java Virtual Machine [JVM]

A Java Virtual Machine [JVM] is a virtual machine that enables a computer to


run Java programs as well as programs written in other languages that are also
compiled in java bytecode. JVM is a specification that provides runtime environment
in which java bytecode can be executed.

The Java Virtual Machine (JVM) is the heart of java program execution process.
It is responsible for loading class file and converting each byte code instruction
into the machine language instruction that can be created by the underlying
microprocessor. The below diagram shows the architecture of JVM.

Class loader Subsystem


 Loads .class file into memory (RAM). (Example: class file is stored in secondary
storage device such as hard disk)
 It verifies whether all byte code instruction are proper or not. If it finds any
instruction suspicious then execution is terminated.
 If the byte code instructions are proper, then it allocates necessary memory to
execute the program.
 It allocates memory to static variables and sets the default value to static variables.

3
Java programming
DIFFERENCE BETWEEN C++ AND JAVA
C++ Java
1. C++ is not a pure object oriented 1. Java is a pure object oriented
programming programming
2. Pointers are used in C++ 2. No pointers are used in Java
3. The allocation and deallocation is 3. The Java Virtual Machine [JVM] will
responsible of programmer take care of allocation and
deallocation of memory
4. C++ has goto statement 4. Java has no goto statement
5. C++ is used in multiple inheritance 5. Java cannot be used in multiple
inheritance
6. Operator overloading can be used in 6. Operator overloading cannot be used
C++ in Java
7. In C++ having three types of access 7. In Java having four types of access
specifiers such as private, public and specifier default, private, public and
protected protected
8. In C++ both destructor and 8. In Java we use only constructor
constructor can be used
9. C++ supports global variables 9. No global variables are used in Java
10.C++ support structure and union 10.There is no structure and union
in Java
11. Supports template class in C++ 11. No templates class in Java

DIFFERENCE BETWEEN C AND JAVA


C Java
1. C is Procedure Oriented 1. Java is a pure object oriented
Programming programming
2. Pointers are used in C 2. No pointers are used in C++
3. The allocation and deallocation is 3. The Java Virtual Machine [JVM] will
responsible of programmer in C take care of allocation and
deallocation of memory
4. C has goto statement 4. Java has no goto statement
5. Header files are used in C 5. No header files are used in Java
6. C supports global variables 6. No global variables are used in Java
7. The storage classes in C are 7. There is no storage class
automatic, external, static and
register
8. C supports structure and union 8. There is no structure and union in
Java
9. The sizeof operator is used in C 9. There is no sizeof operator used in
Java
4
Java programming
TOKENS
It is the smallest individual unit in a programming language known as
tokens.
There are 6 types of tokens used in java;
1. Identifiers
2. Keywords
3. Operators
4. Separators
5. Literals
6. Comments

1. IDENTIFIERS
It is used to identify the name of the variables, methods,
classes, objects, arrays, and packages known as Identifiers.
RULES OF IDENTIFIERS
 The Identifiers should be start with an alphabetical letter or underscore or
$(dollar).
 The uppercase and lowercase letter both are distinct.
 There must be no blank space between an identifier.
 The reserved word or keyword should not be taken as the name of an identifier.
 There is no limit to declare an identifier but it is case sensitive.

Examples for an Identifier:


sum xyz a
avg x z

2. KEYWORDS OR RESERVE WORDS


It is a pre-defined in a java compiler known as keywords.
List of keywords:
boolean final break catch case
byte new continue finally if
char private do throw else
double public while throws try
float switch for static int
mod long short void default

5
Java programming
1.2. DATATYPES
DATA TYPES
It refers to the type of data in a Programming language is
called as Data type

The Primitive Data types used in the Java are byte, short, int, long, float, double,
char, boolean
1. byte:
byte is a keyword that is one of the data type in Java Programing and one byte or
8 bits of data can be stored. The Default value of byte is zero (0).

Example:
byte x;
Where x is a byte data type Variable

2. short:
short is a keyword that is one of data type in Java programming and stores 2 bytes
of data. Default value of the Short is Zero (0).

Example:
short x;
Where x is a short data type variable

3. int:
int is a keyword and also one of the data type in Java programming and that is
used to store whole numbers or integer values. And size of the int data type is 4
bytes of data. The Default value of int is zero (0).

Example:
int a;
Where a is an integer data type variable

4. long:
long is a keyword that is used to take the twice of the integer datatype & to store
8 bytes of data. The Default value of long is ‘OL’.
Example:
long x;
Where x is a long integer data type variable
6
Java programming
5. float:
float is a keyword, which is used to store Single Precision of numbers or Real
numbers and to Store 4 bytes of data. According to IEEE [Institute of Electrical
and Electronic Engineers] whenever we assign the floating point valve that should
end with “f”. The Default of float is 0.0

Example:
float x = 10.5f;

6. double:
double is a keyword and it is a twice of float data type, and to store 8 bytes of
data. The default value of double is 0.0

Example:
double x, y, z;
Where x, y, z is a double data type variables.

7. char:
char is a keyword that is used Store 2 bytes of data. The default value of char is.
‘\u0000’

Example:
char Sex = 'M';

8. boolean:
boolean is a keyword that is used to store only one bit of information and to check
whether the given expression is true or false. The default value of Boolean is false

Example:
boolean flag = true;

1.3. OPERATORS
3. OPERATORS
Operators are the special Symbols that are commonly used in expression.
List of Operators
a. Arithmetic operators a. Relational operators
b. Unary operators b. Logical operators
c. Assignment operators c. Conditional operators
d. Shorthand arithmetic assignment operators d. Bitwise and bit shift operators

7
a. Arithmetic operators
1. ADDITION (+):
It is used to take the addition of the numbers
Example
a=10;
b=20;
c=a+b;
We get the value of c = 30

2. SUBTRACTION (-):
It is used the take subtraction of numbers.
Example
a = 20;
b = 5;
c=a-b;
We get the value of c = 15

3. MULTIPLICATION (*):
It is used to take the multiplication of the numbers
Example:
a = 5;
b = 10;
c = a*b;
We get the value of c = 50

4. DIVISION ( / ) :
It is used to take the division of two numbers
Example:
a = 20;
b = 2;
c = a/b;
We get vale of c = 10

5. M O D U L U S ( % ) :
It is used to take the reminder of the number
Example:-
a = 20;
b = 5;
c = a % b;
We get value of c = 0
Java programming
b. Unary operators
Unary operator is an operator it is having only one operand
without assignment operator
1. Unary + operator
It takes only one operand or only one value by default the + value can be taken
in the programming.

Example: a = 10;
a = +10;

2. Unary - operator
This operator refers to negative value

Example: int a;
a = -10;

3. Unary ++ operator
It is incremented by one.

Example: int a = 12;


a++;

4. Unary -- operator:
It refers to Decrement by one.

Example: int a = 12;


a--;

c. Assignment operators (=)


It is used assign the valve to the variable but the valve can be changed.
Example:
a. b.
int x; int x, y, z;
x = 100; x = 10;
y = 20;
z = x + y:

6
Java programming
d. Shorthand arithmetic assignment operators
The combination of arithmetic and assignment operator is known as
shorthand arithmetic assignment operator
1. +=
x=10;
x+=15;
We get the result x = 25

2. -=
x = 20;
x - = 5;
We get the result x = 15

3. *=
x = 5;
x * = 10;
We get the result x = 50

4. /=
x = 10;
x / = 2;
We get the result x=5

5.  =
x = 10;
x % = 3;
We get the result x = 1

e. Relational operators ( < , > , < = , > = , != )


The relational operator is used for control statements and to evaluate
the comparison of the values
Example: if( a > b )
large = a;
else
large = b;

7
Java programming

f. Logical operators
Logical operator are used in two are more number of
condition
1. && Logical AND
2. || Logical OR
3. ! Logical NOT

g. Conditional operator (or) Ternary operator (? :)


If it evaluates expression 1 as true then the expression 2 is executed
otherwise expression 3 is executed

Syntax:
result = exp_1 ? exp_2 : exp_3;

Example: a = 10;
b = 5;
large = a > b ? a : b ;

Now we get the result of largest is 10

h. Bitwise and Bit shift operators


It is used to perform the evaluation of binary digits like addition,
subtraction, complements, shifting bits from left to right or right to left.
This type of operation can be implemented by using only numeric data
type such as int, long, short, float, and double.

1. Bitwise AND (&):


It is used to perform multiplication of each and every digits of binary
number.
Example: a = 10; 10 = 1010 1 0 1 0
b = 5; 5 = 0101 0 1 0 1
a & b = 0; 0 0 0 0

8
Java programming
2. Bitwise OR ( | ):
It is used to perform an addition of each and every digits of binary
number.
Example: a = 10; 10 = 1010 1 0 1 0
b = 5; 5 = 0101 0 1 0 1
a | b = 15; 1 1 1 1

3. Bitwise XOR ( ^ ):
We get the output as ‘1’ if the inputs are 0 and 1 / 1 and 0. And we get
the output as ‘0’ if both the inputs are same like 0 and 0 / 1 and 1.
Example: a = 11; 11 = 1011 1 0 1 1
b = 8; 8 = 1000 1 0 0 0
a ^ b = 3; 0 0 1 1
11 ^ 8 = 3
4. Bitwise NOT ( ~ ):

If the input is 1 then output becomes 0 and if the input is 0 then the
output becomes 1.
Example: 14 = 1110 0 0 0 0 1 1 1 0
~14 = 0001 1 1 1 1 0 0 0 1

0 0 0 0 1 1 1 0
+ 1
~14 = -15 0 0 0 0 1 1 1 1

Note: Complement of any value “n” is “-(n+1)”

5. Bitwise Left Shift ( << ):


Bitwise left shift operator moves the bits from right to left. This can be
done by adding specified number of bit (0) at right side and shifting the
bits of an integer from right to the left side.

Example: 741 << 1


Binary value of 741 is 1011100101

9
Java programming
1024 512 256 128 64 32 16 8 4 2 1
1 0 1 1 1 0 0 1 0 1

1 0 1 1 1 0 0 1 0 1 0
1024+ 0 + 256 + 128 + 64 + 0 + 0 + 8 + 0 + 2 + 0 =1482

6. Bitwise Right Shift ( >> ):


Bitwise right shift operator moves the bits from left to right. This can be
done by adding specified number of bit (0) at left side and shifting the
bits of an integer from left to the right side.

Example: 741 >> 1


Binary value of 741 is 1011100101
512 256 128 64 32 16 8 4 2 1
1 0 1 1 1 0 0 1 0 1

0 1 0 1 1 1 0 0 1 0
0 + 256 + 0 + 64 + 32 + 16 + 0 + 0 + 2 + 0
1.4. VARIABLES
VARIABLES
It is a value or quantity which does change during the program
execution.

Rules of variables
o The variables should start with an alphabetical letter or underscore or $(dollar).
o The uppercase and lowercase letter both are distinct.
o There should be no blank space between a variable.
o The reserved word or keyword should not be taken as name of a variable.
o There is no limit to declare an identifier but it is case sensitive.

DECLARATION OF VARIABLE:
Syntax:
datatype var_1, var_2…;
10
Java programming
The combination of the data type, name of the variable and scope of the variable.
Example: int a, b;
float x, y, z;

4. SEPARATORS OR PUNCTUATOR

It is used to define the function of the program separated by multiple


variable declaration, statement end with ‘;’ , methods enclosed with ‘( )’
and so on.

1.
Parentheses are used to group expressions, separate conditional expressions,
and indicate function calls and function parameters.

Example:
public static void main ( String args[] )
{
-----------------
-----------------
}

2.
It is used for array declaration / subscripts.

Example:
int a = new int [10];

3.
It is used for block of statements that means compound statements.

Example:
public static void main ( String args[] )
{
-----------------
-----------------
}

11
Java programming
4.
Semicolon is a separator, every statement is ended with semicolon.

Example:
System.out.println(“welcome to java”);

5.
It is used to separate a list of statements or a variables.

Example:
int x , y , z;

6.
It is used to take the declaration when we assign the floating point value and
accessing the methods with the help of object and dot operator.

Example:
X = 12.5;
a.show();

5. LITERALS
Literals are nothing but constants that means the value or quantity
which does not change during the program execution.
Types of Literals:
5.1. Integer Literals
5.2. Floating paint Literals
5.3. Character literals
5.4. Boolean literals
5.5. String literals

1. INTEGER LITERALS
The integer is used to represent only whole numbers such as 10, 20, 30, 40, 50
and so on.
The integer literals such as int, long, short. Long integers are specified suffix L.
Example:
100 L
4000 L

12
Java programming
2. FLOATING POINT LITERALS
It is used to represent the floating point values or real numbers such as 10.38f,
14.87f, 15.55f… the floating point literals such as float and double.

When we want to assign the floating point values for the float data type then it
should be followed by suffix f according to the rule of IEEE.s

3. CHARACTER LITERALS
It is used to represent single character. The character such as ‘A', 'b', 'c' ,'d', 'e', 'f'
and so on. The character must be enclosed with Single quotes ( ‘ ’ ).

4. BOOLEAN LITERALS
Boolean is also one of literals in Java programing that is used to check the given
expression is true or false.

5. STRING LITERALS
It is a sequence of character / collection of character. Here in string, we should
not take array of character, we can use string type directly.

Example:
"Manoj" "Abc" "xyz" and so on…

6. COMMENTS
It is a remarks of program code doubts or it is an explanatory part
(summary) of programming language known as comments.

There are 3 types of comments


1. Single lime comment.
2. Multi lime comment
3. Java document style comment

1. Single line comment


Single line comment is used to remark the single lime only that is
indicated by ‘//’

13
Java programming
Example:
int x,y,z; // x, y and z are the integer type variables

2. Multi-line comment
When we want to remark two or more number lines in the programming
language then it should be started with ‘/*’ and ended with ‘*/’

Example:
/* int x;
int y;
int z; */

3. Java document style comment


It is similar to multi-line comments. But in application programming interface in
Java it is used for the comment statement like document style. It starts with
‘/**’ and end with ‘*/’.

1.5. CONTROL STRUCTURE INCLUDING SELECTION


Control structure
It is used to perform conditional and unconditional statements
in a programming is known as control structure.

CONDITIONAL STATEMENTS UNCONDITIONAL STATEMENTS


1. if statement 1. Break
2. switch statement 2. Continue
3. looping statement 3. Return

i f statement
if statement is a bi-directional control structure that is used to execute
the given condition is true or false.

14
Java programming
There are 4 types of if statements:
1. Simple if statements.
2. If else statements.
3. If-else-if statements or ladder if statements.
4. Nested if statements.

1. SIMPLE IF
Syntax:
if ( test_condition )
{
statement_1;
statement_2;
:
:
}

Operation of simple if
It is use to check the test condition. If the condition is true then the statements are
executed otherwise the statements are ignored / skipped.
Example: a = 10;
b = 20;
c = 15;
large = a;
if ( b > large )
large = b;
if ( c > large )
large = c;

//program to show the use of simple if statements


import java.io.*;
class simp
{
public static void main(String args[])throws IOException
{
BufferedReader br = new BufferedReader(new
InputStreamReader (System.in));
int a, b, c, large;

15
Java programming
String s;
System.out.println ("enter the value of a,b,c");
s = br.readLine();
a = Integer.parseInt(s);
s = br.readLine();
b = Integer.parseInt(s);
s = br.readLine();
c = Integer.parseInt(s);
large = a;
if (b>large)
large = b;
if (c>large)
large = c;
System.out.println ("the largest value="+large);
}
}

2. IF-ELSE
Syntax:
if ( test_condition )
statement_A;
else
statement_B;

Operation of if-else
It evaluates the given test condition. If the condition is true then the statement_A
is executed and statement B is skipped otherwise the statement_B is executed and
statement A is skipped.

Example: if(n % 2 = = 0 )
System.out.println(“the given number is
even”);
else
System.out.println(“the given number is
odd”);

16
Java programming
//program to show the use of if else statements
import java.io.*;
class ifelse
{
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader
(System.in));
int n;
String s;
System.out.println(“enter the value of n”);
s = br.readLine();
n = Integer.parseInt(s);
if(n % 2 = = 0 )
System.out.println(“the given number is even”);
else
System.out.println(“the given number is odd”);
}
}
3. IF-ELSE-IF OR LADDER-IF STATEMENT
Syntax:
if ( test_condition_A )
statement_1;
else if ( test_condition_B )
statement_2;
:
:
:
else if ( test_condition_N )
statement_N;
else

default statement;
17
Java programming
Operation of if-else-if / ladder-if
It is used to check two or more conditions. Here, which condition results true that
particular the statement is executed and the remaining statements are ignored /
skipped. If all the conditions results false then the default statement is executed.

Example:
if( p > = 8 5 )
System.out.println(“DISTINCTION”);
else if( p > = 6 0 )
System.out.println(“FIRST CLASS”);
else if( p > = 5 0 )
System.out.println(“SECOND CLASS”);
else if( p > = 3 5 )
System.out.println(“PASS”);
else
System.out.println(“FAIL”);

//program to show the use of ladder if statements


import java.io.*;
class ladder
{
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new
InputStreamReader (System.in));
double p;
String s;
System.out.println("enter your percentage");
s = br.readLine();
p = Double.parseDouble(s);
if( p > = 8 5 )
System.out.println(“distinction”);
18
Java programming
else if( p > = 6 0 )
System.out.println(“first class”);
else if( p > = 5 0 )
System.out.println(“second class”);
else if( p > = 3 5 )
System.out.println(“pass”);
else
System.out.println(“fail”);
}
}

4. NESTED-IF STATEMENT
Syntax:
if ( test_condition_X )
{
if ( test_condition_A )
statement_A1;
else
statement_A2;
}
else if ( test_condition_B )
statement_B1;
else
statement_B2;

Operation of nested-if
If the main test_condition_X is true, then it checks test_condition_A. If the
test_condition_A is true then statement_A1 is executed otherwise the
statement_A2 is executed.

If the main test_condition_X is false then it checks the test_condition_B. If


the test_condition_B is true then statement_B1 is executed otherwise
statement_B2 is executed.
19
Java programming
Example: if ( a < b )
if ( a < c )
small = a;
else
small = c;
else if ( b < c )
small = b;
else
small = c;

//program to show the use of nested-if statements


import java.io.*;
class nested
{
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader
(System.in));
int a,b,c,small;
String s;
System.out.println("enter the value of a,b,c");
s=br.readLine();
a=Integer.parseInt(s);
s=br.readLine();
b=Integer.parseInt(s);
s=br.readLine();
c=Integer.parseInt(s);
if( a < b )
if( a < c )
small = a;
else
small = c;
else if( b < c )
small = b;
else
small = c;

20
Java programming
System.out.println("the smallest value="+small);
}
}

5. 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;
break;
}

Operation of Switch statement


It is a multi-directional control structure that is used to execute the expression
matching case statement only. This process continues till the end of the cases. If the
expression is not matched with any of the case of switch statement then the default
statement is executed.

Example:
switch ( day )
{
case 1:
System.out.println(“SUNDAY”);
break;
case 2:
System.out.println(“MONDAY”);
break;
case 3:
21
Java programming
System.out.println(“TUESDAY”);
break;
case 4:
System.out.println(“WEDNESDAY”);
break;
case 5:
System.out.println(“THURSDAY”);
break;
case 6:
System.out.println(“FRIDAY”);
break;
case 7:
System.out.println(“SATURDAY”);
break;
default:
System.out.println(“INVALID”);
break;
}

//program to show the use of switch statement


import java.io.*;
class swt
{
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader
(System.in));
String s;
int day;
System.out.println("enter the day number");
s = br.readLine();
day = Integer.parseInt(s);
switch(day)
{
case 1: System.out.println(“SUNDAY”);
break;
case 2: System.out.println(“MONDAY”);
break;
22
Java programming
case 3: System.out.println(“TUESDAY”);
break;
case 4: System.out.println(“WEDNESDAY”);
break;
case 5: System.out.println(“THURSDAY”);
break;
case 6: System.out.println(“FRIDAY”);
break;
case 7: System.out.println(“SATURDAY”);
break;
default: System.out.println(“INVALID DAY NUMBER”);
break;
}
}
}

1.6. LOOPING STATEMENT


The process of executing the statement again and again from
beginning to end until the condition is satisfied.

Looping mainly depends on 3 type of expression;


1. Initial expression
2. Final expression
3. Increment/decrement expression

1. I NITIAL EXPRESSION
It is used to take beginning value of the expression.
Example: i = 1;

2. F INAL EXPRESSION
It is used to take final value or end of the value in a given expression.
Example: i > = 10;

23
Java programming
3. I NCREMENT / DECREMENT EXPRESSIO N
It is used to increment / decrement the value of the variable from initial value to
final value.
Example: i++ / i--;

TYPES OF LOOPING
Basically there are 3 types of looping. Such as;
 while loop
 do while loop
 for loop

1. WHILE LOOP
Syntax:
while ( test_condition )
{
statement_1;
statement_2;
:
:
:
statement_N;
}
Operation
While loop is a pre-tested loop that is used to evaluate the test_condition first, if
the test_condition is true then it enters the loop and executes the statements
again and again until the condition is satisfied otherwise it does not enters the loop
that means all the statements are ignored / skipped.

Example: i = 1;
while ( i < = 10 )
{
System.out.println(i);
i++;
}

24
Java programming

//program to show the use of while loop


class whl
{
public static void main(String args[])
{
int i;
System.out.println("to display the number from 1 to 100");
i = 1;
while(i < = 1 0 )
{
System.out.println(i);
i++;
}
}
}

//program to find the factorial of a given number using while


loop
import java.io.*;
class fact
{
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader
(System.in));
String s;
long n,i,fact;
System.out.println("enter the val of n");
s = br.readLine();
n = Long.parseLong(s);
fact = 1;
i = 1;
while(i < = n )
{
25
Java programming
fact = fact * i;
i++;
}
System.out.println("the fact("+n+")="+fact);
}
}

2. DO-WHILE LOOP
Syntax:
do
{
statement_1;
statement_2;
:
:
:
statement_N;
} while ( condition );

Operation
It is a post-tested loop that is used to check condition after the execution of one
statement suppose if the condition is true then it executes the statement again and
again until the condition is satisfied. If the condition is false the initial value is
executed as it is a post-tested loop. It executes the statement first then it checks the
condition.

Example: i = 1;
do
{
System.out.println(i);
i++;
} while ( i < = 10 );

//program to show the use of do while loop


class dowhl
{

26
Java programming
public static void main (String args[])
{
int i;
System.out.println("to display the number from 1 to 10");
i=1;
do
{
System.out.println(i);
i++;
}
while( i < = 1 0 );
}
}

//program to find the sum of natural number using do while


loop
import java.io.*;
class natural
{
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader
(System.in));
long n,i,sum;
String s;
System.out.println("enter the value for n");
s=br.readLine();
n=Long.parseLong(s);
sum=0;
i=1;
do
{
sum=sum+i;
i++;
}

27
Java programming
while(i<=n);
System.out.println("the sum="+sum);
}
}

3. FOR LOOP
Syntax:
for ( exp_1 ; exp_2 ; exp_3 )
{
statement_1;
statement_2;
:
:
:
statement_N;
}

exp_1 -> initial expression


exp_2 -> final expression
exp_3 -> increment or decrement

Operation
It is a fixed loop execution if the condition is true then it executes the statement
from initial value to final value until the condition is satisfied.

//program to show the use to for loop.


class forloop
{
public static void main(String args[])
{
int i;
System.out.println("to display the numbers from 1 to 10");
for(i=1;i<=10;i++)
{
28
Java programming
System.out.println(i);
}
}
}

//program to display n numbers but it is divisible by 5.


import java.io.*;
class div5
{
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader
(System.in));
long n,i;
String s;
System.out.println("enter the value for n");
s=br.readLine();
n=Long.parseLong(s);
System.out.println("to display the numbers that is
divisible by 5");
for(i=1;i<=n;i++)
{
if(i%5==0)
System.out.println(i);
}
}
}

4. NESTED-FOR LOOP
It is for loop within another for loop.
Example:
//displaying the table
class nestfor
{
public static void main(String args[])
{
int i,j;
29
Java programming
System.out.println("to display the tables from 1 to 10");
for(i=1;i<=10;i++)
{
for(j=1;j<=10;j++)
{
System.out.print(" "+(i*j));
}
System.out.println( );
}
}
}

//program to display the following pattern.


1
2 2
3 3 3
4 4 4 4

class pattren
{
public static void main(String args[])
{
int i,j;
System.out.println("to display the pattren");
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
System.out.print(" "+i);
}
System.out.println( );
}
}
}

BREAK STATEMENT
It is used to terminate the statements, looping and conditions in a java
program.
30
Java programming

General syntax:
break;

//program to show the use of break statement.


class brk
{
public static void main(String args[])
{
int i;
System.out.println("to display the numbers");
for(i=1;i<=100;i++)
{
if(i==6)
break;
else
System.out.println(i);
}
}
}

CONTINUE STATEMENT
It is used to continue the statements, looping and conditions in a java
program.

General syntax:
continue;

//program to show the use of continue statement.


class conti
{
public static void main(String args[])
{
int i;
System.out.println("to display the numbers");

31
Java programming
for(i=1;i<=10;i++)
{
if(i<6)
continue;
else
System.out.println(i);
}
}
}

RETURN STATEMENT
It is used to return the value of the variable or to return an expression
inside the method in java.
General syntax:
return;

Example:
int add(int x, int y)
{
return x+y;
}

//program to show the use of return statement.


class retu
{
int add(int x, int y)
{
return x+y;
}
public static void main(String args[])
{
retu br=new retu();
int a,b,c;
a=10;
b=30;

32
Java programming
c=br.add(a,b);
System.out.println("the value of a="+a);
System.out.println("the value of b="+b);
System.out.println("the value of c="+c);
}
}

1.7. JAVA METHODS


The large type of program that is divided into smaller sub program, each
sub program is nothing but a method. The method in java is used to
return a value, passing a parameters and by manipulating the sub
program.

General Syntax:
[modifier][return_type] method_name (datatype arg1, datatype arg2…)
{
declarations and statements;
:
:
return expression;
}

According to the General Syntax


• modifier is nothing but public, private and protected.
• The return_type is used to return a value such as int, float, long, double……
• method_name is a name of the method.

RULES OF METHOD
1. It should start from alphabetic letter and followed by digits.
2. The upper case and lower case both are distinct.
3. The name of method should not be a reserve word or key word.
4. The method is used to calculate any operations and stores it in return statement.
5. The methods are overloading.
6. The methods are used in static.
7. The methods are used in before class or after class.

33
Java programming
The methods declare without using static:
The methods are used declare or used to return the value of the variable and so on. If
the method is not declared using static keyword, we should access the method with
the help of an object.

//Program to show the method without using static


class ABC
{
public void show()
{
System.out.println("This is without static method");
}
public static void main(String args[])
{
ABC x=new ABC();
x.show();
}
}

//Program to show the use of with using static


class ABC
{
public static void show()
{
System.out.println("This is with static method");
}

public static void main(String args[])


{
show();
}
}

STATIC METHOD
Static method is a method it should be used with a static keyword in
a method declaration and executes various number of coding without
using any object in a main program.

34
Java programming
1.8. OVERLOADING
OVERLOADING
Overloading means the same method name to declare two or more
number of time in a same class with different number of arguments or
different type of data.
Example:
int add(int x, int y)
{
return x+y;
}

int add (int x, int y, int z)


{
return x+y+z;
}

//Program
class overloading
{
int add(int x,int Y)
{
return x+y;
}

int add (int x, int y, int z)


{
return x+y+z;
}

public static void main(String args[])


{
overloading m=new overloading();
int a, b, c, s1, s2;
a = 100;
b = 200;
c = 50;
s1 = m.add(a,b);
s2 = m.add(a,b,c);
System.out.println("Sum of 2 args=" +s1);
35
Java programming
System.out.println("Sum of 3 args=" +s2);
}
}

1.9. MATH CLASS


It is used to implement the methods of mathematical operations
such as sqrt( ), pow( ), min( ), max( ), avg( ) ,floor( ), ceil( ) ,abs( ).
Math is a built-in class in java that is used to calculate all
mathematical methods as shown by the following;
Example:
1. x = Math.sqrt(81);
x = 9

2. P = Math.pow(10,2);
P = 100

3. mi = Math.min(10,5);
mi = 5

4. mx = Math.max(10,50);
mx = 50

//Program
class maths
{
public static void main(String args[])
{
System.out.println("Square root of 100="+Math.sqrt(100));
System.out.println("10 to the power of
2="+Math.pow(10,2));
System.out.println("Minimum of two
number="+Math.min(10,2));
System.out.println("Maximum of 2 number="+Math.max(10,2));
System.out.println("Round of
method="+Math.round(10.994567));

36
Java programming
System.out.println("Absolute value="+Math.abs(-35));
System.out.println("log(20)="+Math.log(20));
}
}

1. sqrt() : It is used calculate the square root of the number.

2. pow(): It is used to find power of the value that means


p = Math.pow(10,2);
We get the value of p = 100.

3. min(): Find the minimum of two values.


mi = Math.min(10,50);
We get the value of mi = 10.
4. max(): Find the maximum of two value that means;
mx = Math.max(10,50);
We get the value of mx = 50.

5. abs(): It is used to find absolute value .


X = Math.abs(-35);
X = 35

6. round(): It is used to find the round of value.


N = Math.round(10.9985);
N = 11

7. log(): It is used to find logarithm value.


X = Math.log(20);
X = 2.9957322735

37
Java programming
1.10. ARRAYS IN JAVA
ARRAY
Array is a collection of data items that shares a common name
with same data type.

RULES OF AN ARRAY
 The size of array must be integer value or an integer expression.
 Size of an array do not take negative value or floating point.
 Size of an array must be used for [ ].

TYPES OF AN ARRAY
1. One Dimensional Array
2. Multi-Dimensional Array

O NE D IMENSIONAL A RRAY
It is a type of an array that contains only one dimension.
General Syntax:
Data_type[ ] Array_name = new Data_type[size];

Example:
int[ ] a = new int[5];
Where integer datatype and a is an array variable that contains contiguous memory
allocations of an array like a[0], a[1], a[2], a[3]……a[N].

//Write a program to show the use of one dimensional array


import java.io.*;
class arr
{
public static void main(String args[ ])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader
(System.in));
String s;
38
Java programming
int[ ] a = new int[5];
int i;
System.out.println(“enter the elements”);
for(i = 0 ; i < 5 ; i + + )
{
s = br.readLine();
a[i] = Integer.parseInt(s);
}
System.out.println(“To display the elements as follows”);
for(i = 0 ; i < 5 ; i + + )
System.out.println(a[i]);
}
}

INITIALIZATION OF AN A RRAY
When we declare an array variables followed by the assignment
operator and it takes the list of data items, in which each item is
separated by comma operator (,) and enclosed with pair of braces.

int[ ] a = {10,20,30,40,50,60};

We may declare by another method of individual elements as follows;


int[ ] a = new int[5];
a[0] = 20;
a[1] = 30;
a[2] = 40;
a[3] = 50;
a[4] = 60;

//Write a program to show use of array initialization


class Arrin
{
public static void main(String args[ ])
{
int[ ] a = {20,30,40,50,60};
int i;
39
Java programming
System.out.println(“To display the elements as follows”);
for(i = 0 ; i < 5 ; i + + )
System.out.println(“a[“+i+”]=”+a[i]);
}
}

Default values for array elements


Array element type Default values
1. Object reference NULL
2. Byte 0
3. Short 0
4. Int 0
5. Long 0L
6. Float 0.0f
7. Double 0.0
8. Boolean False
9. Char \u0000

Arrays of Object references


An Array of object reference type is created by specifying the object type
and the size of the array.
Example:
Date[ ] birthdate = new Date[5];

How to find length of an array?


To find of the length of an array, we can use the length instance
variables, it’s available for all array object, regardless of type.
Example:
int i;
int[] a = {4, 6, 34, 890, 232, 656, 23, 67, 689, 4576, 6880};
System.out.println(“To display the elements as follows”);
for(i = 0 ; i < ;i++)
System.out.println(“a[“+i+”]=”+a[i]);

40
Java programming
Memory representation of one dimensional array
Suppose the following example;
int[] a = new int[5];

This memory representation has shown below by the following;


10 20 30 40 50
a[0] a[1] a[2] a[3] a[4]
The elements of an array that is represented as follows ;
a[0] = 10
a[1] = 20
a[2] = 30
a[3] = 40
a[4] = 50

//Program to show the length of the array


class init
{
public static void main(String args[])
{
int[] a={34,67,45,33,13,84,23};
int i;
System.out.println(“to display the elements are as
follows”);
for(i = 0 ; i < a.length;i + + )
System.out.println(“a[“+i+”]=”+a[i]);
}
}

M ULTI -DIMENSIONAL A RRAY


It is a type of an array that contains more than one dimension.

General Syntax:
Data_type[ ][ ] array_name = new data_type[s1][s2];

Example:
int[ ][ ] a = new int[3][3];

41
Java programming
 int is a data type;
 a is an array variable that contains 3x3 cells of an array and to produce 9 elements
of memory allocations such as elements of memory allocation.

//Program to show the use of multi-dimensional array.


import java.io.*;
class mult
{
public static void main(String args[ ])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader
(System.in));
String s;
int[ ][ ] a = new int[3][3];
int i,j;
System.out.println(“enter the elements”);
for(i=0;i<3;i++)
{
for(j = 0 ; j < 3 ; j + + )
{
s = br.readLine();
a[i][j] = Integer.parseInt(s);
}
}
System.out.println(“To display the mat A as follows”);
for(i = 0 ; i < 3 ; i + + )
{
for(j = 0 ; j < 3 ; j + + )
{
System.out.print(“ ” +a[i][j]);
}
System.out.println(“ ”);
}
}
}

I NITIALIZATION OF M ULTI - DIMENSIONAL A RRAY


When we declare the multi-dimensional array followed by the
assignment operator and take the list of data items each item separated
by comma(,) operator and enclosed with pair of braces.
42
Java programming
Example:
int [ ][ ] a ={{1,2,3},{4,5,6},{7,8,9}};

Command line Arguments


A command line arguments represents value passed to main method to
receive and store the values. Main( ) method provides the arguments
called as string arg[ ].

int a, b;
The a and b are inputting the value using the command line arguments as follows;

a = Integer.parseInt(args[0]);
b = Integer.parseInt(args[1]);
sum = a+b;
System.out.println(“The val of a=”+a);
System.out.println(“The val of b=”+b);
System.out.println(“sum=”+sum);

//Programing example
class comm
{
public static void main(String args[])
{
int x, y, sum;
x = Integer.parseInt(args[0]);
y = Integer.parseInt(args[1]);
sum = x+y;
System.out.println(“The val of x=”+x);
System.out.println(“The val of y=”+y);
System.out.println(“sum=”+sum);
}
}
How do you input the values in command line arguments……

D:\Folder_name>javac comm.java

D:\Folder_name>java comm 100 200


The val of x=100
The val of y=200
Sum=300

43
Java programming

UNIT 02. Objects and classes


1

2.1. OBJECTS AND CLASSES

Introduction
The classes and objects are core part of Java programming language. The class is the
essence of Java. It is the foundation upon which the entire Java language is built
because the class defines the nature of an object. The class forms the basis for object
oriented programming in Java. The data and methods are defined inside a class.

2.2. BASICS OF OBJECTS AND CLASSES IN JAVA


What is Class?
A class is a collection of an objects. Objects are instances of a
class.

There are just two kinds of things that we can include in a class definition:
1. Data Members: These are variables that store data items that typically
differentiate one object of the class from another.

2. Methods: These define the operations that you can perform for the class-so they
determine what you can do to, or with, objects of the class.

Defining a Class
A class is created by using the keyword class. The general form of a class definition
is shown here:

[access_Modifier][class_Modifier] class Class_Name [extends


Super_Class _Name] [Implements Interface_List]
{
[Variable declarations]
[Method declarations]
}

44
Java programming
Rules for defining the class
a) The definition of class should start with class keyword
b) Class name should start with an alphabetical letter
c) Class can be instantiated
d) The class can be inherited with another class
e) The class is used to declare static and non-static variables
f) The class can pass final variables and final methods.
g) The method can be overloaded inside the class

Adding Variables to Class


We can declare the variables inside the class. The variables inside a class are of two
types.
1. Class variables
2. Instance variables

1. Class variables
The class variables will always have the modifier-static in front of them. The class
variables are also called Static variables.

Example:
static int age = 30;

2. Instance variables
The same variable defined as an instance variable would be:

Example:
int age = 30;

The below class shows how to declare a variable inside a class:


public class Variable_Demo
{
int age;
int regno;
float percentage;
static int collegeCode;
char sex = ‘M’;
static double fees = 30000.00;
}
45
Java programming
ADDING METHODS TO CLASS
1. A method contains one or more statements. In well-written Java code, each method
performs only one task. Each method has a name, and it is this name that is used
to call the method.

2. In general, we can give a method whatever name we like. However, remember that
main() is reserved for entry point program execution.

3. We should not use Java’s keywords for method names.


4. The general form of a method is shown here:

[modifiers] return_type method_name (parameter_list)


{
body_of_method
}

//The following program creates two instance variables and


perform addition and subtractions.
public class MethodsDemo
{
int num1,num2;
int sum(int a, int b)
{
num1 = a;
num2 = b;
return num1 + num2;
}

void subtract(int a, int b)


{
num1 = a;
num2 = b;
int c = num1 - num2;
System.out.println("Subtract of two numbers is "+c);
}

public static void main(String args[])


{
MethodsDemo m = new MethodsDemo();
int s=m.sum(20,40);

46
Java programming
System.out.println("Sum : "+s);
m.subtract(10,20);
}
}

CREATING OBJECTS
An object is created by instantiating a class. The process of creating an object of a class
is called as instantiation and the Java uses the new keyword.

The objects are created using the new operator with the name of the class we want
to create an instance of, then parentheses after that. The general form of creating an
object is shown below:

class_name object_name = new class_name();

Example:
class student
{
int a,b;
void show()
{
-----------
-----------
}
}
student s=new student();
s.show();

ACCESSING CLASS MEMBERS


The class consists of variables (data members) and methods. Once an object is
created, we can access the members of the class using dot (.) operator.

The general form of the dot operator is shown below:


1. To access Variable:
object.variable
2. To access Methods:
object.method()

47
Java programming
//Program to declare the Instance variables:
class A
{
int i;
int j;
public static void main(String args[])
{
A a1 = new A();
a1.i = 10;
a1.j = 20;
A a2 = new A();
a2.i = 11;
a2.j = 22;
}
}

//Program to demonstrate the accessing methods using dot


operator
class ABC
{
int i = 10, j = 20;
void function1()
{
i = i + 1;
j = j + 1;
function2();
System.out.println(“Inside function1() “);
}

void function2()
{
System.out.println(i);
System.out.println(j);
System.out.println(“Inside function2() “);
}

public static void main(String args[])


{
ABC a1 = new ABC();
a1.function();
System.out.println(“End of main”);
}
}
48
Java programming
2.3. CONSTRUCTORS
Constructor is a special member of method of class, when the
method is invoked the instance of the class is initialized
automatically.
The constructors are of two types:
1. Default constructor
2. Parameterized contractor

General syntax:
class classname
{
classname()
{
Declarations;
Executable statements;
}
}

DEFAULT CONSTRUCTOR
It is a constructor that accepts no parameters.

Example:
class A
{
A()
{
System.out.println(“Default Constructor”);
}
}

PARAMETERIZED CONSTRUCTOR
It is a type of constructor that have to pass few number of parameters
inside the constructor.

49
Java programming
Example:
Def(int a, int b, int c)
{
x = a;
y = b;
z = c;
}

RULES FOR CONSTRUCTORS


1. The constructor name must match the name of the class.
2. The constructor must not have a return type.
3. The constructor can use any access modifiers like public, protected and private.
4. The static keyword cannot be applied to constructors.
5. The constructor can be overloaded.
6. The constructor is not compulsory for any class.
7. The constructor cannot be called from methods.
8. We can call constructors from other constructors.

Overloaded Constructors / Constructor Overloading


Constructor that have two or more number of constructors with
different arguments in the same class called as Overloaded
constructor.
Example:
class A
{
int x,y,z;
A()
{
x = 10;
y = 20;
z = 30;
System.out.println(“x=”+x);
System.out.println(“y=”+y);
System.out.println(“z=”+z);
}
A(int a, int b)
{
x = a;
50
Java programming
y = b;
System.out.println(“x=”+x);
System.out.println(“y=”+y);
}
A(int a, int b, int c)
{
x = a;
y = b;
z = c;
System.out.println(“x=”+x);
System.out.println(“y=”+y);
System.out.println(“z=”+z);
}
}

//Programing example of overloading constructor


class over
{
int x, y, z;
over()
{
x = 10;
y = 20;
z = 30;
System.out.println(“x=”+x);
System.out.println(“y=”+y);
System.out.println(“z=”+z);
}
over(int a)
{
x=a;
y=20;
z=30;
int sum = x + y + z;
System.out.println(“sum=”+sum);
}
over(int a,int b)
{
x=a;
y=b;
z=30;
51
Java programming
int sum = x + y +z;
System.out.println(“sum=”+sum);
}
over(int a, int b, int c)
{
x=a;
y=b;
z=c;
int sum = x + y + z;
System.out.println(“sum=”+sum);
}
public static void main(String args[])
{
over c1 = new over();
over c2 = new over(10);
over c3 = new over(15,30);
over c4 = new over(33,44,55);
}
}

Using this Constructor


this is a keyword and it is an object that pass the values from one
constructor method to another method like chain linked system using
this keyword.

Example:
class A
{
int i,j;

A()
{
this(100);
}

A(int a)
{
this(a,200);
}

52
Java programming
A(int a, int b)
{
i=a;
j=b;
}
}

//Program for this constructor


class this
{
int x, y, z;

ths()
{
this(100);
}

ths(int a)
{
this(a,200);
}

ths(int a, int b)
{
this(a,b,300);
}

ths(int a,int b,int c)


{
x=a;
y=b;
z=c;
}
void display()
{
System.out.println("The val of x = "+x);
System.out.println("The val of y = "+y);
System.out.println("The val of z = "+z);
}

public static void main(String args[])


{

53
Java programming
ths t=new ths();
t.display();
}
}

Method Overloading
The connection of two or more methods and the same method is
used two or more number of times in the same class with different
number of arguments or different types of data known as Method
overloading.
Example:
class Meth
{
int x,y,z;
void sum()
{
x=10;
y=20;
z=x+y;
System.out.println("The val of x = "+x);
System.out.println("The val of y = "+y);
System.out.println("The val of z = "+z);
}

int sum(int a, int b)


{
x=a;
y=b;
return x+y;
}

int sum(int a, int b, int c)


{
x=a;
y=b;
z=c;
return x+y+z;
}

54
Java programming
public static void main(String args[])
{
int s1,s2;
Meth m1 = new Meth();
m1.sum();
Meth m2 = new Meth();
s1 = m2.sum(10,20);
System.out.println("Sum of Two numbers = "+s1);
Meth m3 = new Meth();
s2 = m3.sum(10,20,30);
System.out.println("Sum of Three numbers = "+s2);
}
}

Static Variables and Methods


static is a keyword. This word is used in three scenarios in Java Programming.
1. Static variable
2. Static methods
3. Static blocks of code

1. STATIC VARIABLE
The static variable is also known as class variables and these
variables can be accessed without creating an object.

Example:
class Static
{
static int x, y;
public static void main(String args[])
{
Static.x = 100;
Static.y = 200;
System.out.println("The Val Of X = "+x);
System.out.println("The Val Of Y = "+y);
}
}

55
Java programming
2. STATIC METHODS
This method can access static variable directly and without
creating an objects the static methods are called in main method.
Example:
class StatMethod
{
static int x,y;
static void show()
{
x=100;
y=200;
System.out.println("The Val Of X = "+x);
System.out.println("The Val Of Y = "+y);
}
public static void main(String args[])
{
show();
}
}

3. STATIC BLOCKS
Static block is used to declare only static but this block is executed
first without creating an object.
Example: class StatBlock
{
void show()
{
System.out.println("Non Static Method");
}
static
{
System.out.println("This Is Static Block");
}
public static void main(String args[])
{
StatBlock s = new StatBlock();
s.show();
}
}

56

You might also like