basic introductions

Download Report

Transcript basic introductions

Data types:
•A data type is a scheme for representing values. An example is int which
is the Integer, a data type
•Values are not just numbers, but any manner of data that a computer can
process.
•The data type defines the kind of data that is represented by a variable.
•As with the keyword class, Java data types are case sensitive.
There are two types of data types
primitive data type
non-pimitive data type
In primitive data types, there are two categories
numeric means Integer, Floating points
Non-numeric means Character and Boolean
In non-pimitive types, there are three categories
classes
arrays
interface
Following table shows the datatypes with their size and ranges.
Data type
Size (byte)
Range
byte
1
-128 to 127
boolean
1
True or false
char
2
A-Z,a-z,0-9,etc.
short
2
-32768 to 32767
Int
4
(about) -2 million to 2 million
long
8
(about) -10E18 to 10E18
float
4
-3.4E38 to 3.4E18
double
8
-1.7E308 to 1.7E308
Integer data type:
Integer datatype can hold the numbers (the number can be positive
number or negative number). In Java, there are four types of integer as
follows:
byte
short
int
long
We can make ineger long by adding 'l‘ or 'L‘ at the end of the number.
Floating point data type:
It is also called as Real number and when we require accuracy then we
can use it.
There are two types of floating point data type.
float
double
It is represent single and double precision numbers. The float type is
used for single precision and it uses 4 bytes for storage space. It is very
useful when we require accuracy with small degree of precision. But in
double type, it is used for double precision and uses 8 bytes of starage
space. It is useful for large degree of precision.
Character data type:
It is used to store single character in memory. It uses 2 bytes storage
space.
Boolean data type:
It is used when we want to test a particular condition during the excution
of the program. There are only two values that a boolean type can hold:
true and false.
Boolean type is denoted by the keyword boolean and uses only one bit of
storage.
Following program shows the use of datatypes.
Program:
import java.io.DataInputStream;
class cc2
{
public static void main(String args[]) throws Exception
{
DataInputStream s1=new DataInputStream(System.in);
byte rollno;
int marks1,marks2,marks3;
float avg;
System.out.println("Enter roll number:");
rollno=Byte.parseByte(s1.readLine());
System.out.println("Enter marks m1, m2,m3:");
marks1=Integer.parseInt(s1.readLine());
marks2=Integer.parseInt(s1.readLine());
marks3=Integer.parseInt(s1.readLine());
avg = (marks1+marks2+marks3)/3;
System.out.println("Roll number is="+rollno);
System.out.println("Average is="+avg);
}
}
Output: C:\cc>java cc2
Enter roll number:
07
Enter marks m1, m2,m3:
66
77
88
Roll number is=7
Average is=77.0
Mixing Data types:
Java allows mixing of constants and variables of different types in an
expression, but during assessment it hold to very strict rules of type
conversion.
When computer consider operand and operator and if operands are
different types then type is automatically convert in higher type.
Following table shows the automatic type conversion.
char
byte
short
int
long
float
double
Char
int
int
int
int
long
float
double
Byte
int
int
int
int
long
float
double
Short
int
int
int
int
long
float
double
Int
int
int
int
int
long
float
double
Long
long
long
long
long
long
float
double
Float
float
float
float
float
float
float
double
double
double
double
double
double
double
double
double
Variables:
Variables are labels that express a particular position in memory and
connect it with a data type.
The first way to declare a variable: This specifies its data type, and
reserves memory for it. It assigns zero to primitive types and null to
objects.
dataType variableName;
The second way to declare a variable: This specifies its data type,
reserves memory for it, and puts an initial value into that memory. The
initial value must be of the correct data type.
dataType variableName = initialValue;
The first way to declare two variables: all of the same data type, reserves
memory for each.
dataType variableNameOne, variableNameTwo;
The second way to declare two variables: both of the same data type,
reserves memory, and puts an initial value in each variable.
dataType variableNameI = initialValueI, variableNameII=initialValueII;
Variable name:
•Use only the characters 'a‘ through 'z‘, 'A‘ through 'Z‘, '0‘ through '9‘,
character '_‘, and character '$‘.
•A name cannot include the space character.
•Do not begin with a digit.
•A name can be of any realistic length.
•Upper and lower case count as different characters.
•A name cannot be a reserved word (keyword).
•A name must not previously be in utilized in this block of the program.
Constant:
Constant means fixed value which is not change at the time of execution
of program. In Java, there are two types of constant as follows:
Numeric Constants
Integer constant
Real constant
Character Constants
Character constant
String constant
Integer Constant:
An Integer constant refers to a series of digits. There are three types of
integer as follows:
a) Decimal integer
Embedded spaces, commas and characters are not alloed in between
digits.
For example:
23 411
7,00,000
17.33
b) Octal integer
It allows us any sequence of numbers or digits from 0 to 7 with leading 0
and it is called as Octal integer.
For example:
011
00
0425
c) Hexadecimal integer
It allows the sequence which is preceded by 0X or 0x and it also allows
alphabets from 'A‘ to 'F‘ or 'a‘ to 'f‘ ('A‘ to 'F‘ stands for the numbers
'10‘ to '15‘) it is called as Hexadecimal integer.
For example:
0x7
00X
0A2B
Real Constant
It allows us fractional data and it is also called as folating point constant.
It is used for percentage, height and so on.
For example:
0.0234
0.777
-1.23
Character Constant
It allows us single character within pair of single coute.
For example:
'A‘
'7‘
'\‘
String Constant
It allows us the series of characters within pair of double coute.
For example:
“WELCOME”
“END OF PROGRAM”
“BYE …BYE”
“A”
Symbolic constant:
In Java program, there are many things which is requires repeatedly and
if we want to make changes then we have to make these changes in
whole program where this variable is used.
For this purpose, Java provides ‘final‘ keyword to declare the value of
variable as follows:
Syntax:
final type Symbolic_name=value;
For example:
If I want to declare the value of ‘PI‘ then:
final float PI=3.1459
the condition is, Symbolic_name will be in capital letter( it shows the
difference between normal variable and symblic name) and do not
declare in method.
Backslash character constant:
Java support some special character constant which are given in
following table.
Constant
‘\b‘
Importance
Back space
‘\t‘
Tab
‘\n‘
New line
‘\\‘
Backslash
‘\”
Single coute
‘\”‘
Double coute
Command line arguments:
Command line arguments are parameters that are supplied to the
application program at the time of invoking its execution. They must be
supplied at the time of its execution following the file name.
In the main () method, the args is confirmed as an array of string known
as string objects. Any argument provided in the command line at the time
of program execution, are accepted to the array args as its elements.
Using index or subscripted entry can access the individual elements of an
array. The number of element in the array args can be getting with the
length parameter.
For example:
class Add
{
public static void main(String args[])
{
int a=Integer.parseInt(args[0]);
int b=Integer.parseInt(args[1]);
int c=a+b;
System.out.println(―Addition is=‖+c);
}
}
output:
c:\javac Add.java
c:\java Add 5 2
7
Introduction:
A Java program is basically a set of classes. A class is defined by a set of
declaration statements and methods or functions. Most statements
contain expressions, which express the actions carried out on information
or data. Smallest indivisual thing in a program are known as tokens. The
compiler recognizes them for building up expression and statements.
Tokens in Java:
There are five types of token as follows:
1. Literals
2. Identifiers
3. Operators
4. Separators
Literals:
Literals in Java are a sequence of characters (digits, letters and other
characters) that characterize constant values to be stored in variables.
Java language specifies five major types of literals are as follows:
1. Integer literals
2. Floating point literals
3. Character literals
4. String literals
5. Boolean literals
Identifiers:
Identifiers are programmer-created tokens. They are used for naming
classes, methods, variables, objects, labels, packages and interfaces in a
program. Java identifiers follow the following rules:
1. They can have alphabets, digits, and the underscore and dollar sign
characters.
2. They must not start with a digit.
3. Uppercase and lowercase letters are individual.
4. They can be of any length.
Identifier must be meaningful, easily understandable and descriptive.
For example:
Private and local variables like “length”.
Name of public methods and instance variables begin with lowercase
letter like “addition”
Keywords:
Keywords are important part of Java. Java language has reserved 50
words as keywords. Keywords have specific meaning in Java. We cannot
use them as variable, classes and method. Following table shows
keywords.
abstract
default
if
package
this
class
float
native
int
return
interface
short
assert
char
finally
long
static
volatile
throws
final
instanceof
null
try
void
continue
const
catch
do
throw
break
import
byte
public
case
const
for
while
goto
boolean
implements
private
double
protected
else
transient
extends
new
switch
synchronized
super
Operator:
Java carries a broad range of operators. An operator is symbols that
specify operation to be performed may be certain mathematical and
logical operation. Operators are used in programs to operate data and
variables. They frequently form a part of mathematical or logical
expressions.
Categories of operators are as follows:
1. Arithmetic operators
2. Logical operators
3. Relational operators
4. Assignment operators
5. Conditional operators
6. Increment and decrement operators
7. Bit wise operators
Arithmetic operators:
Arithmetic operators are used to make mathematical expressions and the
working out as same in algebra. Java provides the fundamental
arithmetic operators. These can operate on built in data type of Java.
Following table shows the details of operators.
Operator
+
/
*
%
Importance/ significance
Addition
Subtraction
Division
Multiplication
Modulo division or remainder
“+” operator in Java:
In this program, we have to add two integer numbers and display the
result.
class AdditionInt
{
public static void main (String args[])
{
int a = 6;
int b = 3;
System.out.println("a = " + a);
System.out.println("b =" + b);
int c = a + b;
System.out.println("Addition = " + c);
}
}
Output:
a= 6
b= 3
Addition=9
Logical operators:
When we want to form compound conditions by combining two or more
relations, then we can use logical operators.
Following table shows the details of operators.
Operators
||
&&
!
Importance/ significance
Logical – OR
Logical –AND
Logical –NOT
The logical expression defer a value of true or false. Following table
shows the truth table of Logical – OR and Logical – AND.
Truth table for Logical – OR operator:
Operand1
T
T
F
F
Operand3
T
F
T
F
Operand1 || Operand3
T
T
T
F
T – True
F - False
Truth table for Logical – AND operator:
Operand1
T
T
F
F
Operand3
T
F
T
F
Operand1 && Operand3
T
F
F
F
Now the following program shows the use of Logical operators.
class LogicalOptr
{
public static void main (String args[])
{
boolean a = true;
boolean b = false;
System.out.println("a||b = " +(a||b));
System.out.println("a&&b = "+(a&&b));
System.out.println("a! = "+(!a));
}
}
Output:
a||b = true
a&&b = false
a! = false
Relational Operators:
When evaluation of two numbers is performed depending upon their
relation, assured decisions are made.
The value of relational expression is either true or false.
If A=7 and A < 10 is true while 10 < A is false.
Following table shows the details of operators.
Operator
>
<
!=
>=
<=
Importance/ significance
Greater than
Less than
Not equal to
Greater than or equal to
Less than or equal to
Now, following examples show the actual use of operators.
1) If 10 > 30 then result is false
2) If 40 > 17 then result is true
3) If 10 >= 300 then result is false
4) If 10 <= 10 then result is true
Now the following program shows the use of operators.
class Reloptr1
{
public static void main (String args[])
{
int a = 10;
int b = 30;
System.out.println("a>b = " +(a>b));
System.out.println("a<b = "+(a<b));
System.out.println("a<=b = "+(a<=b));
}
}
Output:
a>b = false
a<b = true
a<=b = true
Program :
class Reloptr3
{
public static void main (String args[])
{ int a = 10;
int b = 30;
int c = 30;
System.out.println("a>b = " +(a>b));
System.out.println("a<b = "+(a<b));
System.out.println("a<=c = "+(a<=c));
System.out.println("c>b = " +(c>b));
System.out.println("a<c = "+(a<c));
System.out.println("b<=c = "+(b<=c));
}
}
Output:
a>b = false
a<b = true
a<=c = true
c>b = true
a<c = true
b<=c = true
Assignment Operators:
Assignment Operators is used to assign the value of an expression to a
variable and is also called as Shorthand operators.
Variable_name binary operator = expression
Following table show the use of assignment operators.
Simple Assignment
Operator
A=A+1
A=A-1
A=A/(B+1)
A=A*(B+1)
A=A/C
A=A%C
Statement with shorthand
Operators
A+=1
A-=1
A/=(B+1)
A*=(B+1)
A/=C
A%=C
These operators avoid repetition, easier to read and write.
Now the following program shows the use of operators.
class Assoptr
{
public static void main (String args[])
{
int a = 10;
int b = 30;
int c = 30;
a+=1;
b-=3;
c*=7;
System.out.println("a = " +a);
System.out.println("b = "+b);
System.out.println("c = "+c);
}
}
Output:
a = 11
b = 18
c = 310
Conditional Operators:
The character pair ?: is a ternary operator of Java, which is used to
construct conditional expressions of the following form:
Expression1 ? Expression3 : Expression3
The operator ? :
works as follows:
Expression1 is evaluated if it is true then Expression3 is evaluated and
becomes the value of the conditional expression. If Expression1 is false
then Expression3 is evaluated and its value becomes the conditional
expression.
For example:
A=3;
B=4;
C=(A<B)?A:B;
C=(3<4)?3:4;
C=4
Now the following program shows the use of operators.
class Coptr
{
public static void main (String args[])
{
int a = 10;
int b = 30;
int c;
c=(a>b)?a:b;
System.out.println("c = " +c);
c=(a<b)?a:b;
System.out.println("c = " +c);
}
}
Output:
c = 30
c = 10
program3:Write a program to check whether number is positive or
negative.
class PosNeg
{
public static void main(String args[])
{
int a=10;
int flag=(a<0)?0:1;
if(flag==1)
System.out.println(“Number is positive”);
else
System.out.println(“Number is negative”);
}
}
Output:
Number is positive
Increment and Decrement Operators:
The increment operator ++ adds 1 to a variable. Usually the variable is
an integer type, but it can be a floating point type. The two plus signs
must not be split by any character. Usually they are written immediately
next to the variable
Expression
A++
++A
A---A
Process
Add 1 to a variable
after use.
Add 1 to a variable
before use.
Subtract 1 from a
variable after use.
Subtract 1 from a
variable before use.
Example
int A=10,B;
B=A++;
int A=10,B;
B=++A;
int A=10,B;
B=A--;
int A=10,B; B=-A;
end result
A=11 B=10
A=11 B=11
A=9 B=10
A=9 B=9
class IncDecOp
{
public static void main(String args[])
{
int x=1;
int y=3;
int u;
int z;
u=++y;
z=x++;
System.out.println(x);
System.out.println(y);
System.out.println(u);
System.out.println(z);
}
}
Output:
3
4
4
1
Bit Wise Operators:
Bit wise operator execute single bit of their operands. Following table
shows bit wise operator:
Operator
Importance/ significance
|
Bitwise OR
&
Bitwise AND
&=
Bitwise AND assignment
|=
Bitwise OR assignment
^
Bitwise Exclusive OR
<<
Left shift
>>
Right shift
~
One‘s complement
Now the following program shows the use of operators.
(1) Program 1
class Boptr1
{
public static void main (String args[])
{
int a = 4;
int b = a<<3;
System.out.println("a = " +a);
System.out.println("b = " +b);
}
}
Output:
a =4
b =16
Program 3
Class Boptr3
{
public static void main (String args[])
{
int a = 16;
int b = a>>3;
System.out.println("a = " +a);
System.out.println("b = " +b);
}
}
Output:
a = 16
b=3
356
38
138
37
64
36
33
35
16
34
8
33
4
33
3
31
1
30
Separator:
Separators are symbols. It shows the separated code.they describe
function of our code.
Name
Use
()
Parameter in method definition, containing statements for
conditions,etc.
{}
It is used for define a code for method and classes
[]
It is used for declaration of array
;
It is used to show the separate statement
,
It is used to show the separation in identifier in variable declarartion
.
It is used to show the separate package name from sub-packages and
classes, separate variable and method from reference variable.
Operator Precedence in Java:
An arithmetic expression without any parentheses will be calculated
from left to right using the rules of precedence of operators.
There are two priority levels of arithmetic operators are as follows:
(a) High priority (* / %)
(b) Low priority (+ -)
The evaluation process includes two left to right passes through the
expression. During the first pass, the high priority operators are applied
as they are encountered.
During the second pass, the low priority operators are applied as they are
encountered.
Operator
[]
()
.
++
-!
~
(type)
*
/
%
+
<<
>>
>>>
<
<=
>
>=
Instanceof
==
!=
&
^
|
&&
||
?:
=
Associativity
Left to right
Left to right
Left to right
Right to left
Right to left
Right to left
Right to left
Right to left
Right to left
Left to right
Left to right
Left to right
Left to right
Left to right
Left to right
Left to right
Left to right
Left to right
Left to right
Left to right
Left to right
Left to right
Left to right
Left to right
Left to right
Left to right
Left to right
Left to right
Left to right
Right to left
Right to left
Rank
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Control Structure
In java program, control structure is can divide in three parts:
Selection statement
Iteration statement
Jumps in statement
Selection Statement:
Selection statement is also called as Decision making statements
because it provides the decision making capabilities to the statements.
In selection statement, there are two types:
if statement
switch statement
These two statements are allows you to control the flow of a program
with their conditions.
if Statement:
The “if statement” is also called as conditional branch statement. It is
used to program execution through two paths. The syntax of “if
statement” is as follows:
Syntax:
if (condition)
{
Statement 1;
Statement 2;
...
}
else
{
Statement 3;
Statement 4;
... }
The “if statement” is a commanding decision making statement and is
used to manage the flow of execution of statements. The “if statement” is
the simplest one in decision statements. Above syntax is shows two ways
decision statement and is used in combination with statements.
Following figure shows the “if statement”
Condition
?
true
false
Simple if statement:
Syntax:
If (condition)
{
Statement block;
}
Statement-a;
In statement block, there may be single statement or multiple statements.
If the condition is true then statement block will be executed. If the
condition is false then statement block will omit and statement-a will be
executed.
The if…else statement:
Syntax:
If (condition)
{
True - Statement block;
}
else
{
False - Statement block;
}
Statement-a;
If the condition is true then True - statement block will be executed. If
the condition is false then False - statement block will be executed. In
both cases the statement-a will always executed.
Following figure shows the flow of statement.
Condition?
True –
Statement
Block
False–
Statement
Block
Statement ‘a’
Following program shows the use of if statement.
Program: write a program to check whether the number is positive or
negative.
import java.io.*;
class NumTest
{
public static void main (String[] args) throws IOException
{
int Result=11;
System.out.println("Number is"+Result);
if ( Result < 0 )
{
System.out.println("The number "+ Result +" is negative");
}
else
{
System.out.println("The number "+ Result +" is positive");
}
System.out.println("------- * ---------");
}}
Output:
C:\cse>java NumTest
Number is 11
The number 11 is positive
------- * ---------
(All conditional statements in Java require boolean values, and that's
what the ==, <, >, <=, and >= operators all return. A boolean is a value
that is either true or false. If you need to set a boolean variable in a Java
program, you have to use the constants true and false. Boolean values are
no more integers than are strings).
write a program to check whether the number is divisible by 2 or not.
import java.io.*;
class divisorDemo
{
public static void main(String[] args)
{
int a =11;
if(a%2==0)
{
System.out.println(a +" is divisible by 2");
}
else
{
System.out.println(a+" is not divisible by 2");
}
}
}
Output: C:\cse>java divisorDemo
11 is not divisible by 2
Nesting of if-else statement:
Syntax:
if (condition1)
{
If(condition2)
{
Statement block1;
}
else
{
Statement block2;
}
}
else
{
Statement block3;
}
Statement 4;
If the condition1 is true then it will be goes for condition2. If the
condition2 is true then statement block1 will be executed otherwise
statement2 will be executed. If the condition1 is false then statement
block3 will be executed. In both cases the statement4 will always
executed.
true
false
Condition1
false
true
Condition2
Statement3
Statement2
Statement4
Statement1
Write a program to find out greatest number from three numbers.
class greatest
{
public static void main(String args[])
{
int a=10;
int b=20;
int c=3;
if(a>b)
{
if(a>c)
{
System.out.println("a is greater number");
}
else
{
System.out.println("c is greater number");
}
else
{
if(c>b)
{
System.out.println("c is greater number");
}
else
{
System.out.println("b is greater number");
}
}
}
}
Output:
C:\CSE>java greatest
b is greater number
switch statement:
In Java, switch statement check the value of given variable or statement
against a list of case values and when the match is found a statementblock of that case is executed. Switch statement is also called as
multiway decision statement.
Syntax:
switch(condition)// condition means case value
{
case value-1:statement block1;break;
case value-2:statement block2;break;
case value-3:statement block3;break;
…
default:statement block-default;break;
}
statement a;
The condition is byte, short, character or an integer. value-1,value2,value-3,…are constant and is called as labels. Each of these values be
matchless or unique with the statement. Statement block1, Statement
block2, Statement block3,..are list of statements which contain one
statement or more than one statements. Case label is always end with “:”
(colon).
Program:write a program for bank account to perform following
operations.
-Check balance
-withdraw amount
-deposit amount
For example:
import java.io.*;
class bankac
{
public static void main(String args[]) throws Exception
{
int bal=20000;
int ch=Integer.parseInt(args[0]);
System.out.println("Menu");
System.out.println("1:check balance");
System.out.println("2:withdraw amount... plz enter choice and amount");
System.out.println("3:deposit amount... plz enter choice and amount");
System.out.println("4:exit");
switch(ch)
{
case 1:System.out.println("Balance is:"+bal);
break;
case 2:int w=Integer.parseInt(args[1]);
if(w>bal)
{
System.out.println("Not sufficient balance");
}
bal=bal-w;
System.out.println("Balance is"+bal);
break;
case 3:int d=Integer.parseInt(args[1]);
bal=bal+d;
System.out.println("Balance is"+bal);
break;
default:break;
}
}
}
Output:
C:\CSE>javac bankac.java
C:\CSE>java bankac 1
Menu
1:check balance
2:withdraw amount... plz enter choice and amount
3:deposit amount... plz enter choice and amount
4:exit
Balance is:20000
C:\CSE>java bankac 2 2000
Menu
1:check balance
2:withdraw amount... plz enter choice and amount
3:deposit amount... plz enter choice and amount
4:exit
Balance is18000
C:\CSE>java bankac 3 2000
Menu
1:check balance
2:withdraw amount... plz enter choice and amount
3:deposit amount... plz enter choice and amount
4:exit
Balance is22000
C:\CSE>java bankac 4
Menu
1:check balance
2:withdraw amount... plz enter choice and amount
3:deposit amount... plz enter choice and amount
4:exit
C:\CSE>java bankac
Iteration Statement:
The process of repeatedly executing a statements and is called as
looping. The statements may be executed multiple times (from zero to
infinite number). If a loop executing continuous then it is called as
Infinite loop. Looping is also called as iterations.
In Iteration statement, there are three types of operation:
•for loop
•while loop
•do-while loop
for loop:
The for loop is entry controlled loop. It means that it provide a more
concious loop control structure.
Syntax:
for(initialization;condition;iteration)//iteration means increment/decrement
{
Statement block;
}
import java.io.*;
class number
{
public static void main(String args[]) throws Exception
{
int i;
System.out.println("list of 1 to 10 numbers");
for(i=1;i<=10;i++)
{
System.out.println(i);
}
}
}
Output:
C:\CSE>javac number.java
C:\CSE>java number
list of 1 to 10 numbers
1
2
3
4
5
6
7
8
9
10
while loop:
The while loop is entry controlled loop statement. The condition is
evaluated, if the condition is true then the block of statements or
statement block is executed otherwise the block of statement is not
executed.
Syntax:
While(condition)
{
Statement block;
}
example:Write a program to display 1 to 10 numbers using while loop.
import java.io.*;
class number
{
public static void main(String args[]) throws Exception
{
int i=1;
System.out.println("list of 1 to 10 numbers");
while(i<=10)
{
System.out.println(i);
i++;
}
}
}
Output:
C:\CSE>javac number.java
C:\CSE>java number
list of 1 to 10 numbers
1
2
3
4
5
6
7
8
9
10
do-while loop:
In do-while loop, first attempt of loop should be execute then it check the
condition.
The benefit of do-while loop/statement is that we get entry in loop and
then condition will check for very first time. In while loop, condition will
check first and if condition will not satisfied then the loop will not
execute.
Syntax:
do
{
Statement block;
}
While(condition);
In program, when we use the do-while loop, then in very first attempt, it
allows us to get enter in loop and execute that loop and then check the
condition.
Write a program to display 1 to 10 numbers using do-while loop.
import java.io.*;
class number
{
public static void main(String args[]) throws Exception
{
int i=1;
System.out.println("list of 1 to 10 numbers");
do
{
System.out.println(i);
i++;
}while(i<=10);
}
}
Output:
C:\CSE>javac number.java
C:\CSE>java number
list of 1 to 10 numbers
1
2
3
4
5
6
7
8
9
10
Jumps in statement:
Statements or loops perform a set of operartions continually until the
control variable will not satisfy the condition. but if we want to break the
loop when condition will satisy then Java give a permission to jump from
one statement to end of loop or beginning of loop as well as jump out of
a loop.
“break” keyword use for exiting from loop and “continue” keyword use
for continuing the loop.
Following statements shows the exiting from loop by using “break”
statement.
do-while loop:
do
{
………………
………………
if(condition)
{
break;//exit from if loop and do-while loop
}
……………..
……………..
}
While(condition);
………..
………..
For loop:
for(…………)
{
……………
…………..
if(…………..)
break; ;//exit from if loop and for loop
……………
……………
}
……………
…………..
While loop:
while(…………)
{
……………
…………..
if(…………..)
break; ;//exit from if loop and while loop
……………
……………
}
Following statements shows the continuing the loop by using “continue”
statement.
do-while loop:
do
{
………………
………………
if(condition)
{
continue;//continue the do-while loop
}
……………..
……………..
}
While(condition);
………..
………..
For loop:
for(…………)
{
……………
…………..
if(…………..)
continue ;// continue the for loop
……………
……………
}
……………
…………..
While loop:
while(…………)
{
……………
…………..
if(…………..)
continue ;// continue the while loop
……………
……………
}
…………….
…………….
Labelled loop:
We can give label to a block of statements with any valid name.following
example shows the use of label, break and continue.
For example:
Import java.io.*;
class Demo
{
public static void main(String args[]) throws Exception
{
int j,i;
LOOP1: for(i=1;i<100;i++)
{
System.out.println(““);
if(i>=10)
{
break;
}
for(j=1;j<100;j++)
{
System.out.println(“$ ”);
if(i==j)
{
continue LOOP1;
}
}
}
System.out.println(“ End of program “);
}
}
Output:
$
$$
$$$
$$$$
$$$$$
$$$$$$
$$$$$$$
$$$$$$$$
$$$$$$$$$
End of program
INTRODUCTION TO ARRAYS
The following variable declarations each allocate enough storage to
hold one value of the specified data type.
int number;
double income;
char letter;
87
• An array is an object containing a list of elements of the
same data type.
88
• We can create an array by:
– Declaring an array reference variable to store the address of an
array object.
– Creating an array object using the new operator and assigning the
address of the array to the array reference variable.
89
Here is a statement that declares an array reference variable
named dailySales:
double[ ] dailySales;
The brackets after the key word double indicate that the
variable is an array reference variable. This variable can hold
the address of an array of values of type double. We say
the data type of dailySales is double array reference.
90
The second statement of the segment below creates an array
object that can store seven values of type double and assigns
the address of the array object to the reference variable named
dailySales:
double[ ] dailySales;
dailySales = new double[7];
• The operand of the new operator is the data type of the individual
array elements and a bracketed value that is the array size declarator.
• The array size declarator specifies the number of elements in the
array.
91
• It is possible to declare an array reference variable and
create the array object it references in a single statement.
Here is an example:
double[ ] dailySales = new double[7];
92
The statement below creates a reference variable named
dailySales and an array object that can store seven values of
type double as illustrated below:
double[ ] dailySales = new double[7];
dailySales address
1st value
2nd value
3rd value
4th value
5th value
6th value
7th value
93
• Arrays can be created to store values of any data type.
The following are valid Java statements that create arrays
that store values of various data types:
double[ ] measurements = new double[24];
char[ ] ratings = new char[100];
int[ ] points = new int[4];
94
• The array size declarator must be an integer expression
with a value greater than zero.
95
• It is common to use a named constant as the array size
declarator and then use this named constant whenever you
write statements that refer to the size of the array. This
makes it easier to maintain and modify the code that works
with an array.
The statements below define a named constant called
MAX_STUDENTS and an array with room for one hundred
elements of type int that is referenced by a variable named
testScores.
final int MAX_STUDENTS = 100;
int[ ] testScores = new int[MAX_STUDENTS];
96
Accessing Array Elements
• We can access the array elements and use them like
individual variables.
• Each array element has a subscript. This subscript can be
used to select/pinpoint a particular element in the array.
• Array subscripts are offsets from the first array element.
• The first array element is at offset/subscript 0, the second
array element is at offset/subscript 1, and so on.
• The subscript of the last element in the array is one less
than the number of elements in the array.
97
final int DAYS = 7;
double[ ] dailySales = new double[DAYS];
dailySales address
0
[0]
0
[1]
0
[2]
0
[3]
0
[4]
0
[5]
0
[6]
dailySales[0], pronounced dailySales sub zero, is the first element of the
array.
Subscripts
dailySales[1], pronounced
dailySales sub one, is the second element of
the array.
dailySales[6], pronounced dailySales sub six, is the last element of the
array.
98
• Array subscripts begin with zero and go up to n - 1, where n is
the number of elements in the array.
final int DAYS = 7;
double[ ] dailySales = new double[DAYS];
dailySales address
0
[0]
0
[1]
0
[2]
0
[3]
0
[4]
0
[5]
0
[6]
Subscripts
99
• The value inside the brackets when the array is created is
the array size declarator.
• The value inside the brackets of any other statement that
works with the contents of an array is the array subscript.
100
• Each element of an array, when accessed by its subscript,
can be used like an individual variable.
The individual elements of the dailySales array are variables
of type double, we can write statements like the following:
final int DAYS = 7;
double[ ] dailySales = new double[DAYS];
dailySales[0] = 9250.56; // Assigns 9250.56 to dailySales sub zero
dailySales[6] = 11943.78; // Assigns 11943.78 to the last element of the array
101
final int DAYS = 7;
double[ ] dailySales = new double[DAYS];
dailySales[0] = 9250.56; // Assigns 9250.56 to dailySales sub zero
dailySales[6] = 11943.78; // Assigns 11943.78 to the last element of the array
System.out.print("Enter the daily sales for Monday: ");
dailySales[1] = keyboard.nextDouble( ); // Stores the value entered in dailySales sub 1
double sum = dailySales[0] + dailySales[1]; // Adds the values of the first two elements
System.out.println("The sum of the daily sales for Sunday and Monday are " +
sum + ".");
System.out.println("The sales for Monday were: " + dailySales[1]);
dailySales address
9250.56
[0]
????
[1]
Subscripts
0
[2]
0
[3]
0
[4]
0
[5]
11943.78
[6]
102
INTRODUCTION TO ARRAYS
Accessing Array Elements
• The values stored in the array must be accessed via the
array subscripts.
103
The last statement in the segment below produces a logical
error. The value of dailySales is the address where the array
object is stored. This address is displayed in hexidecimal.
final int DAYS = 7;
double[ ] dailySales = new double[DAYS];
dailySales[0] = 9250.56; // Assigns 9250.56 to dailySales sub zero
dailySales[6] = 11943.78; // Assigns 11943.78 to the last element of the array
System.out.print("Enter the daily sales for Monday: ");
dailySales[1] = keyboard.nextDouble( ); // Stores the value entered in dailySales sub 1
System.out.println("The daily sales for each day of the week were " + dailySales); // Error
104
• Subscript numbers can be stored in variables.
• Typically, we use a loop to cycle through all the subscripts
in the array to process the data in the array.
105
Java Performs Bounds Checking
• Java performs bounds checking, which means it does not
allow a statement to use a subscript that is outside the
range 0 through n - 1, where n is the value of the array size
declarator.
106
The valid subscripts in the array referenced by dailySales are 0
through 6. Java will not allow a statement that uses a subscript
less than 0 or greater than 6. Notice the correct loop header in
the segment below:
final int DAYS = 7;
int counter;
double[ ] dailySales = new double[DAYS];
for (counter = 0; counter < DAYS; counter++)
{
System.out.print("Enter the sales for day " + (counter + 1) + ": ");
dailySales[counter] = keyboard.nextDouble( );
}
107
• Java does its bounds checking at runtime.
• The compiler does not display an error message when it
processes a statement that uses an invalid subscript.
• Instead, Java throws an exception and terminates the
program when a statement is executed that uses a
subscript outside the array bounds. This is not something
you want the user of your program to encounter, so be
careful when constructing a loop that cycles through the
subscripts of an array.
108
Array Initialization
• Like other variables, you may give array elements an initial
value when creating the array.
Example:
The statement below declares a reference variable named
temperatures, creates an array object with room for
exactly tens values of type double, and initializes the
array to contain the values specified in the initialization list.
double[ ] temperatures = {98.6, 112.3, 99.5, 96, 96.7, 32, 39, 18.1, 99,
111.5};
109
• A series comma-separated values inside braces is an
initialization list.
• The values specified are stored in the array in the order in
which they appear.
• Java determines the size of the array from the number of
elements in the initialization list.
double[ ] temperatures = {98.6, 112.3, 99.5, 96, 96.7, 32, 39, 18.1, 99,
111.5};
temperatures
address
98.6
[0]
112.3
[1]
99.5
[2]
96.0
[3]
96.7
[4]
32.0
[5]
39.0
[6]
18.1
[7]
99.0
[8]
111.5
[9]
110
• By default, Java initializes the array elements of a numeric
array with the value 0.
int[ ] attendance = new int[5] ;
attendance
address
0
[0]
0
[1]
0
[2]
0
[3]
0
[4]
111
Array Length
• Each array object has an attribute/field named length. This
attribute contains the number of elements in the array.
For example, in the segment below the variable named
size is assigned the value 5, since the array referenced by
values has 5 elements.
int size;
int[ ] values = {13, 21, 201, 3, 43};
size = values.length;
Notice, length is an
attribute of an array not
a method - hence no
parentheses.
112
To display the elements of the array referenced by values, we
could write:
int count;
int[ ] values = {13, 21, 201, 3, 43};
Notice, the valid
subscripts are zero
through values.length 1.
for (count = 0; count < values.length; count++)
{
System.out.println("Value #" + (count + 1) + " in the list of values is "
+ values[count]);
}
113
Reassigning Array Reference Variables
• The assignment operator does not copy the contents of
one array to another array.
114
The third statement in the segment below copies the address
stored in oldValues to the reference variable named
newValues. It does not make a copy of the contents of the
array referenced by oldValues.
short[ ] oldValues = {10, 100, 200, 300};
short[ ] newValues = new short[4];
newValues = oldValues; // Does not make a copy of the contents of the array ref.
// by oldValues
115
Reassigning Array Reference Variables
After the following statements execute, we have the situation illustrated
below:
short[ ] oldValues = {10, 100, 200, 300};
short[ ] newValues = new short[4];
oldValues
address
10
[0]
100
[1]
200
[2]
300
[3]
newValues
address
0
[0]
0
[1]
0
[2]
0
[3]
When the assignment statement below executes we will have:
newValues = oldValues; // Copies the address in oldValues into newValues
oldValues
address
newValues
address
10
[0]
100
[1]
200
[2]
300
[3]
116
Copying The Contents of One Array to Another Array
• To copy the contents of one array to another you must
copy the individual array elements.
117
To copy the contents of the array referenced by oldValues to the array
referenced by newValues we could write:
int count;
short[ ] oldValues = {10, 100, 200, 300};
short[ ] newValues = new short[4];
// If newValues is large enough to hold the values in oldValues
if (newValues.length >= oldValues.length)
{
for (count = 0; count < oldValues.length; count++)
{
newValues[count] = oldValues[count];
}
}
118
PASSING AN ARRAY AS AN ARGUMENT TO A METHOD
• An array can be passed as an argument to a method.
• To pass an array as an argument you include the name of
the variable that references the array in the method call.
• The parameter variable that receives the array must be
declared as an array reference variable.
119
• When an array is passed as an argument, the memory
address stored in the array reference variable is passed
into the method.
• The parameter variable that stores this address references
the array that was the argument.
• The method does not get a copy of the array.
• The method has access to the actual array that was the
argument and can modify the contents of the array.
120
SOME USEFUL ARRAY OPERATIONS
Comparing Arrays
The decision in the segment below does not correctly
determine if the contents of the two arrays are the same.
char[ ] array1 = {'A', 'B', 'C', 'D', 'A'};
char[ ] array2 = {'A', 'B', 'C', 'D', 'A'};
boolean equal = false;
if (array1 == array2) // This is a logical error
{
equal = true;
}
121
SOME USEFUL ARRAY OPERATIONS
Comparing Arrays
We are comparing the addresses stored in the reference
variables array1 and array2. The two arrays are not stored in
the same memory location so the conditional expression is
false and the value of equal stays at false.
char[ ] array1 = {'A', 'B', 'C', 'D', 'A'};
char[ ] array2 = {'A', 'B', 'C', 'D', 'A'};
boolean equal = false;
if (array1 == array2) // This is false - the addresses are not equal
{
equal = true;
}
122
• To compare the contents of two arrays, you must compare
the individual elements of the arrays.
• Write a loop that goes through the subscripts of the arrays
comparing the elements at the same subscript/offset in
the two arrays.
123
public static boolean equals(char[ ] firstArray, char[ ] secArray)
{
int subscript;
boolean sameSoFar = true;
if (firstArray.length != secArray.length)
{
sameSoFar = false;
}
subscript = 0;
while (sameSoFar && subscript < firstArray.length)
{
if (firstArray[subscript] != secArray[subscript])
{
sameSoFar = false;
}
subscript++; // Incr. the counter used to move through the subscripts
}
return sameSoFar;
}
124
SOME USEFUL ARRAY OPERATIONS
Finding the Sum of the Values in a Numeric Array
• To find the sum of the values in a numeric array, create a
loop to cycle through all the elements of the array adding
the value in each array element to an accumulator variable
that was initialized to zero before the loop.
125
SOME USEFUL ARRAY OPERATIONS
Finding the Sum of the Values in a Numeric Array
/** A method that finds and returns the sum of the values in the array of ints that is
passed into the method.
@param array The array of ints
@return The double value that is the sum of the values in the array.
*/
public static double getSum(int[ ] array)
{
int offset; // Loop counter used to cycle through all the subscripts in the array
double sum; // The accumulator variable - it is initialized in the header below
for (sum = 0, offset = 0; offset < array.length; offset++)
{
sum += array[offset];
}
return sum;
}
126
SOME USEFUL ARRAY OPERATIONS
Finding the Average of the Values in a Numeric Array
• To find the average of the values in a numeric array, first
find the sum of the values in the array. Then divide this
sum by the number of elements in the array.
127
SOME USEFUL ARRAY OPERATIONS
Finding the Average of the Values in a Numeric Array
/** A method that finds and returns the average of the values in the array of ints that
is passed into the method.
@param array The array of ints
@return The double value that is the average of the values in the array.
*/
public static double getAverage(int[ ] array)
{
int offset; // Loop counter used to cycle through all the subscripts in the array
double sum; // The accumulator variable - it is initialized in the header below
double average;
for (sum = 0, offset = 0; offset < array.length; offset++)
{
sum += array[offset];
}
average = sum / array.length;
return average;
}
128
SOME USEFUL ARRAY OPERATIONS
Finding the Highest and Lowest Values in a Numeric Array
• To find the highest value in a numeric array, copy the value
of the first element of the array into a variable called
highest. This variable holds a copy of the highest value
encountered so far in the array.
• Loop through the subscripts of each of the other elements
of the array. Compare each element to the value currently
in highest. If the value of the element is higher than the
value in highest, replace the value in highest with the value
of the element.
• When the loop is finished, highest contains a copy of the
highest value in the array.
129
SOME USEFUL ARRAY OPERATIONS
Finding the Highest and Lowest Values in a Numeric Array
/**A method that finds and returns the highest value in an array of doubles.
@param array An array of doubles
@return The double value that was the highest value in the array.
*/
public static double getHighest(double[ ] array)
{
int subscript;
double highest = array[0];
for (subscript = 1; subscript < array.length; subscript++)
{
if (array[subscript] > highest)
{
highest = array[subscript];
}
}
return highest;
130
SOME USEFUL ARRAY OPERATIONS
Finding the Highest and Lowest Values in a Numeric Array
• The lowest value in an array can be found using a method
that is very similar to the one for finding the highest value.
• Keep a copy of the lowest value encountered so far in the
array in a variable, say lowest.
• Compare the value of each element of the array with the
current value of lowest. If the value of the element is less
than the value in lowest, replace the value in lowest with
the value of the element.
• When the loop is finished, lowest contains a copy of the
lowest value in the array.
131
WORKING WITH PARTIALLY FILLED ARRAYS
• Quite often we do not know the exact number of items that we will
need to store when we write a program. When this is the case, we can
create an array that is large enough to hold the largest possible
number of items and keep track of the actual number of items stored
in the array.
• If the actual number of items stored in the array is less than the
number of elements, we say that the array is partially filled.
• When you process the items in a partially filled array you only want to
process array elements that contain valid data items.
• Keep a count of the actual number of items in the array in an integer
variable as the array is filled and use this value as the upper bound on
the array subscripts when processing the contents of the array.
132
WORKING WITH PARTIALLY FILLED ARRAYS
Suppose we wanted to get up to one hundred whole numbers
from the user and store them in an array and then do some
processing on the contents of the array.
*** See the program PartiallyFilledArray.java on webct
133
WORKING WITH PARTIALLY FILLED ARRAYS
Notice that it is not necessary, actually, it is wasteful to use an
array to get the functionality produced by the program
PartiallyFilledArray.java. We could instead add each number
to an accumulator as we read it and keep a count of the valid
numbers read and added to the accumulator. After all the
numbers are read we can calculate and display the average.
134
RETURNING AN ARRAY FROM A METHOD
• A method can return an array to the statement that made
the method call. Actually, it is a reference to the array (the
address of the array) that is returned.
• When a method returns an array reference, the return
type of the method must be specified as an array
reference.
• Return the address of an array from a method by putting
the name of the variable that references the array after the
key word return at the end of the method.
135
RETURNING AN ARRAY FROM A METHOD
/**A method that gets ten whole numbers from the user and stores them in an
array and returns the reference to the array to the calling method.
@return The array containing the integers entered by the user
*/
public static int[ ] getArrayOfInts( )
{
Scanner keyboard = new Scanner(System.in);
final int MAX_NUMBERS = 10;
int[ ] numbers = new int[MAX_NUMBERS];
int subscript;
for (subscript = 0; subscript < numbers.length; subscript++)
{
System.out.print("Enter number " + (subscript + 1) + ": ");
numbers[subscript] = keyboard.nextInt( );
}
return numbers;
} // End of the method getArrayOfInts
136
VISIBILITY CONTROL IN
JAVA
ACCESS MODIFIERS
• Visibility modifiers also known as access modifiers can be
applied to the instance variables and methods within a class.
• Java provides the following access modifiers
Public
Friendly/Package (default)
Private
Protected
PUBLIC ACCESS
• Any variable or method is visible to the entire class in which it
is defined.
• What is we want to make it visible to all classes outside
the current class??
• This is possible by simply declaring the variable as ‘public’
FRIENDLY ACCESS
• When no access modifier member defaults to a limited
version of public accessibility known as ‘friendly’ level of
access. This is also known as package access.
• So what is the difference between the public and the
friendly access???
• The difference between the public and the friendly access is
that public modifier makes the field visible in all classes
regardless of their package while the friendly access make
them visible only within the current package and not within
the other packages.
PROTECTED ACCESS
• The visibility level of the protected field lies between the
private and the package access.
• That is the protected access makes the field visible not only
to all classes and subclasses in the same package but also to
subclasses in other package
• Non subclasses in their packages cannot access the protected
members
PRIVATE ACCESS
• Enjoys high degree of protection.
• They are accessible only within their own class
• They cannot be inherited by their subclass and hence not
visible in it.
Access
Modifier
Public
Protected
Friendly
Private
Access
Location
Same class
Yes
Yes
Yes
Yes
Subclass in same
package
Yes
Yes
Yes
No
Other classes in same
package
Yes
Yes
Yes
No
Subclasses in other
package
Yes
Yes
No
No
Non subclasses in other
package
Yes
No
No
No
The Java Console
• The console or console screen is a screen
where the input and output is simple text.
– This is a term from the days when computer
terminals were only text input and output.
– Now when using the console for output, it is said
that you are using the standard output device.
• Thus when you print to the console, you are using
standard output.
• In Java, you can write to the console, using the
methods included in the Java API.
Java API
• The Java Application Programmer Interface (API) is a
standard library of prewritten classes for performing
specific operations.
– These classes are available to all Java programs.
• There are TONS of classes in the Java API. That do MANY
different tasks.
• If you want to perform an operation, try either Googling it
before implementing it from scratch.
– Often you will get a link to the Java API that will reference the
class and method/data attribute you need.
– Example: “Java Round”
– Other times, you will get an example
– Example: “Java Ceiling”
Print and Println
• Like stated before, you can perform output to the Java console using the
Java API.
• Two methods to do this are print, and println.
– print – print some text to the screen
– println – print some text to the screen and add a new line character at the
end (go to the next line).
– These two methods are methods in the out class, which itself is contained in
the System class.
• This creates a hierarchy of objects.
• System has member objects and methods for performing system level operations (such
as sending output to the console)
• out is a member of the System class and provides methods for sending output to the
screen.
• System, out, print, and println are all in the Java API.
• Because of this relationship of objects, something as simple as printing to
the screen is a relatively long line of code.
• We’ve seen this before…
Dissecting println
System.out.println(“Hello World!”);
• The dot operator here tells the compiler that we are going to use
something inside of the class/object preceding it.
• So System.out says that we are using the out object in the
System class.
• The text displayed is inside of the parentheses.
– This is called an argument
• We will talk more about arguments when we go over functions, but for now,
just know that whatever is in the parentheses will be printed to the console for
the print and println methods.
• The argument is inside of double quotes, this makes it a string
literal.
– A String is a type in Java that refers to a series of characters
• We will go over literals, types, and strings later
Console Output Examples 1 & 2
• New Topics:
– print
– println
Escape Sequences
• What would be the problem with this?:
System.out.println("He said "Hello" to me");
• The compiler does not know that the "s aren’t ending and starting
a new string literal.
• But, we want double quotes in our string…How do we fix this?
– Answer: Escape Sequences
• Escape Sequences allow a programmer to embed control characters
or reserved characters into a string. In Java they begin with a
backslash and then are followed by a character.
• Control Characters are characters that either cannot be typed with
a keyboard, but are used to control how the string is output on the
screen.
• Reserved Characters are characters that have special meaning in a
programming language and can only be used for that purpose.
IO Stream
Java performs I/O through Streams. A Stream is linked to a
physical layer by java I/O system to make input and output
operation in java. In general, a stream means continuous flow
of data. Streams are clean way to deal with input/output
without having every part of your code understand the
physical.
Java encapsulates Stream under java.io package. Java defines
two types of streams.
They are,
1.Byte Stream : It provides a convenient means for handling
input and output of byte.
2.Character Stream : It provides a convenient means for
handling input and output of characters. Character stream uses
Unicode and therefore can be internationalized.
Byte Stream Classes
Byte stream is defined by using two abstract class at the top of hierarchy,
they are InputStream and OutputStream.
These two abstract classes have several concrete classes that handle various devices
such as disk files, network connection etc.
Some important Byte stream classes.
Stream class
BufferedInputStream
BufferedOutputStream
Description
Used for Buffered Input Stream.
Used for Buffered Output Stream.
DataInputStream
Contains method for reading java standard datatype
FileInputStream
FileOutputStream
InputStream
OutputStream
An output stream that contain method for writing java
standard data type
Input stream that reads from a file
Output stream that write to a file.
Abstract class that describe stream input.
Abstract class that describe stream output.
PrintStream
Output Stream that contain print() and println() method
DataOutputStream
These classes define several key methods. Two most important are
1.read() : reads byte of data.
2.write() : Writes byte of data.
Character Stream Classes
Character stream is also defined by using two abstract class at the top of hierarchy, they
are Reader and Writer.
These two abstract classes have several concrete classes that handle unicode character.
Some important Charcter stream classes.
Stream class
BufferedReader
BufferedWriter
FileReader
FileWriter
InputStreamReader
OutputStreamReader
PrintWriter
Reader
Writer
Description
Handles buffered input stream.
Handles buffered output stream.
Input stream that reads from file.
Output stream that writes to file.
Input stream that translate byte to character
Output stream that translate character to byte.
Output Stream that contain print() and println() method.
Abstract class that define character stream input
Abstract class that define character stream output
Reading Console Input
We use the object of BufferedReader class to take inputs from the keyboard.
Reading Characters
read() method is used with BufferedReader object to
read characters. As this function returns integer type
value has we need to use typecasting to convert it into
char type.
Int read() throws IOException
Below is a simple example explaining character input.
Class CharRead
{
public static void main( String args[])
{
BufferedReader br = new BufferedReader(new InputstreamReader(System.in));
char c = (char)br.read();
//Reading character
}
}
Reading Strings
To read string we have to use readLine() function with BufferedReader
class's object.
String readLine() throws IOException
Program to take String input from Keyboard in Java
import java.io.*;
classMyInput
{
public static void main(String[] args)
{
String text;
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
text = br.readLine();
System.out.println(text);
}
}
//Reading String
Program to read from a file using BufferedReader class
import java. io *;
Class ReadTest
{
public static void main(String[] args)
{
try
{
File fl = new File("d:/myfile.txt");
BufferedReader br = new BufferedReader (new FileReader(fl)) ;
String str;
while ((str=br.readLine())!=null)
{
System.out.println(str);
}
br.close();
fl.close();
}
catch (IOException e)
{ e.printStackTrace(); }
}
}
Program to write to a File using FileWriter class
import java. io *;
Class WriteTest
{
public static void main(String[] args)
{
try
{
File fl = new File("d:/myfile.txt");
String str="Write this string to my file";
FileWriterfw = new FileWriter(fl) ;
fw.write(str);
fw.close();
fl.close();
}
catch (IOException e)
{ e.printStackTrace(); }
}}
Object and Class in Java
we will learn about java objects and classes. In object-oriented programming
technique, we design a program using objects and classes.
Object is the physical as well as logical entity whereas class is the logical entity only.
Object in Java
An entity that has state and behavior is known as an object e.g. chair, bike, marker, pen, table,
car etc.
It can be physical or logical (tengible and intengible). The example of integible object is
banking system.
An object has three characteristics:


state: represents data (value) of an object.
behavior: represents the behavior (functionality) of an object such as deposit, withdraw
etc.
 identity: Object identity is typically implemented via a unique ID. The value of the ID is
not visible to the external user. But,it is used internally by the JVM to identify each
object uniquely.
For Example: Pen is an object. Its name is Reynolds, color is white etc. known as its state. It is
used to write, so writing is its behavior.
Object is an instance of a class. Class is a template or blueprint from which objects are
created. So object is the instance(result) of a class.
Class in Java
A class is a group of objects that has common properties. It is a template or blueprint from
which objects are created.
A class in java can contain:





data member
method
constructor
block
class and interface
Syntax to declare a class:
1. class <class_name>{
2. data member;
3. method;
4. }
Simple Example of Object and Class
In this example, we have created a Student class that have two data members id and name. We
are creating the object of the Student class by new keyword and printing the objects value.
1. class Student1{
2. int id;//data member (also instance variable)
3. String name;//data member(also instance variable)
4.
5. public static void main(String args[]){
6. Student1 s1=new Student1();//creating an object of Student
7. System.out.println(s1.id);
8. System.out.println(s1.name);
9. }
10. }
Test it Now
Output:0 null
Instance variable in Java
A variable that is created inside the class but outside the method, is known as instance
variable.Instance variable doesn't get memory at compile time.It gets memory at runtime when
object(instance) is created.That is why, it is known as instance variable.
Method in Java
In java, a method is like function i.e. used to expose behaviour of an object.
Advantage of Method


Code Reusability
Code Optimization
new keyword
The new keyword is used to allocate memory at runtime.
Example of Object and class that maintains the records of students
In this example, we are creating the two objects of Student class and initializing the value to
these objects by invoking the insertRecord method on it. Here, we are displaying the state (data)
of the objects by invoking the displayInformation method.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
class Student2{
int rollno;
String name;
void insertRecord(int r, String n){ //method
rollno=r;
name=n;
}
void displayInformation(){System.out.println(rollno+" "+name);}//method
public static void main(String args[]){
Student2 s1=new Student2();
Student2 s2=new Student2();
s1.insertRecord(111,"Karan");
s2.insertRecord(222,"Aryan");
s1.displayInformation();
s2.displayInformation();
}
}
Output:111 Karan
222 Aryan
As you see in the above figure, object gets the memory in Heap area and reference variable
refers to the object allocated in the Heap memory area. Here, s1 and s2 both are reference
variables that refer to the objects allocated in memory.
Another Example of Object and Class
There is given another example that maintains the records of Rectangle class. Its exaplanation is
same as in the above Student class example.
1. class Rectangle{
2. int length;
3. int width;
4.
5. void insert(int l,int w){
6. length=l;
7. width=w;
8. }
9.
10. void calculateArea(){System.out.println(length*width);}
11.
12. public static void main(String args[]){
13. Rectangle r1=new Rectangle();
14. Rectangle r2=new Rectangle();
15.
16. r1.insert(11,5);
17. r2.insert(3,15);
18.
19. r1.calculateArea();
20. r2.calculateArea();
21. }
22. }
Output:55
45
What are the different ways to create an object in Java?
There are many ways to create an object in java. They are:




By new keyword
By newInstance() method
By clone() method
By factory method etc.
We will learn, these ways to create the object later.
Annonymous object
Annonymous simply means nameless.An object that have no reference is known as
annonymous object.
If you have to use an object only once, annonymous object is a good approach.
1. class Calculation{
2.
3. void fact(int n){
4. int fact=1;
5. for(int i=1;i<=n;i++){
6. fact=fact*i;
7. }
8. System.out.println("factorial is "+fact);
9. }
10.
11. public static void main(String args[]){
12. new Calculation().fact(5);//calling method with annonymous object
13. }
14. }
Output:Factorial is 120
Creating multiple objects by one type only
We can create multiple objects by one type only as we do in case of primitives.
1. Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two objects
Let's see the example:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
class Rectangle{
int length;
int width;
void insert(int l,int w){
length=l;
width=w;
}
void calculateArea(){System.out.println(length*width);}
public static void main(String args[]){
Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two objects
r1.insert(11,5);
r2.insert(3,15);
r1.calculateArea();
r2.calculateArea();
}
}
Output:55
45
class
Definition: A class is a collection of objects of similar type. Once a
class is defined, any number of objects can be produced which belong
to that class.
Class Declaration
class classname
{
…
ClassBody
…
}
Objects are instances of the Class. Classes and Objects are very much
related to each other. Without objects you can't use a class.
A general class declaration:
class name1
{
//public variable declaration
void methodname()
{
//body of method…
//Anything
}
}
Now following example shows the use of method.
class Demo
{
private int x,y,z;
public void input()
{
x=10;
y=15;
}
public void sum()
{
z=x+y;
}
public void print_data()
{
System.out.println(―Answer is =‖ +z);
}
public static void main(String args[])
{
Demo object=new Demo();
object.input();
object.sum();
object.print_data();
}
}
In program,
Demo object=new Demo();
object.input();
object.sum();
object.print_data();
In the first line we created an object.
The three methods are called by using the dot operator. When we call a
method the code inside its block is executed.
The dot operator is used to call methods or access them.
Creating “main” in a separate class
We can create the main method in a separate class, but during
compilation we need to make sure that you compile the class with the
main method.
class Demo
{
private int x,y,z;
public void input() {
x=10;
y=15;
}
public void sum()
{
z=x+y;
}
public void print_data()
{
System.out.println(“Answer is =“ +z);
}}
class SumDemo
{
public static void main(String args[])
{
Demo object=new Demo();
object.input();
object.sum();
object.print_data();
}
}
use of dot operator
We can access the variables by using dot operator.
Following program shows the use of dot operator.
class DotDemo
{
int x,y,z;
public void sum(){
z=x+y;
}
public void show(){
System.out.println("The Answer is "+z);
}
}
class Demo1
{
public static void main(String args[]){
DotDemo object=new DotDemo();
DotDemo object2=new DotDemo();
object.x=10;
object.y=15;
object2.x=5;
object2.y=10;
object.sum();
object.show();
object2.sum();
object2.show();
}}
output:
C:\cc>javac Demo1.java
C:\cc>java Demo1
The Answer is 25
The Answer is 15
Instance Variable
All variables are also known as instance variable. This is because of
the fact that each instance or object has its own copy of values for the
variables.
Hence other use of the ―dot” operator is to initialize the value of
variable for that instance.
Methods with parameters
Following program shows the method with passing parameter.
class prg
{
int n,n2,sum;
public void take(int x,int y)
{
n=x;
n2=y;
}
public void sum()
{
sum=n+n2;
}
public void print()
{
System.out.println("The Sum is"+sum);
}
}
}
class prg1
{
public static void main(String args[])
{
prg obj=new prg();
obj.take(10,15);
obj.sum();
obj.print();
}
Methods with a Return Type
When method return some value that is the type of that method.
For Example: some methods are with parameter but that method did not
return any value that means type of method is void. And if method return
integer value then the type of method is an integer.
Following program shows the method with their return type.
class Demo1
{
int n,n2;
public void take( int x,int y)
{
n=x;
n=y;
}
public int process()
{
return (n+n2);
}
}
class prg
{
public static void main(String args[])
{
int sum;
Demo1 obj=new Demo1();
obj.take(15,25);
sum=obj.process();
System.out.println("The sum is"+sum);
}
}
Output:
The sum is25
Method Overloading
Method overloading means method name will be same but each method
should be different parameter list.
class prg1
{
int x=5,y=5,z=0;
public void sum()
{
z=x+y;
System.out.println("Sum is "+z);
}
public void sum(int a,int b)
{
x=a;
y=b;
z=x+y;
System.out.println("Sum is "+z);
}
public int sum(int a)
{
x=a;
z=x+y;
return z;
}
}
class Demo
{
public static void main(String args[])
{
prg1 obj=new prg1();
obj.sum();
obj.sum(10,12);
System.out.println(+obj.sum(15));
}
}
Output:
sum is 10
sum is 22
27
Method Overloading in Java
If a class have multiple methods by same name but different parameters,
it is known as Method Overloading.
If we have to perform only one operation, having same name of the
methods increases the readability of the program.
Suppose you have to perform addition of the given numbers but there
can be any number of arguments, if you write the method such as
a(int,int) for two parameters, and b(int,int,int) for three parameters then it
may be difficult for you as well as other programmers to understand the
behaviour of the method because its name differs.
So, we perform method overloading to figure out the program quickly.
Advantage of method overloading?
Method overloading increases the readability of the program.
Different ways to overload the method
•In java, Methood Overloading is not possible by changing the return
type of the method.
1. By changing number of arguments
2. By changing the data type
There are two ways to overload the method in java
Example of Method Overloading by changing the no. of arguments
In this example, we have created two overloaded methods,
first sum method performs addition of two numbers and
second sum method performs addition of three numbers.
1.class Calculation{
2. void sum(int a,int b){System.out.println(a+b);}
3. void sum(int a,int b,int c){System.out.println(a+b+c);}
4. public static void main(String args[]){
5. Calculation obj=new Calculation();
6. obj.sum(10,10,10);
7. obj.sum(20,20);
8. }
9.}
Output:30
40
Example of Method Overloading by changing data type of argument
In this example, we have created two overloaded methods that
differs in data type. The first sum method receives two integer
arguments and second sum method receives two double
arguments.
1.class Calculation2{
2. void sum(int a,int b){System.out.println(a+b);}
3. void sum(double a,double b){System.out.println(a+b);}
4. public static void main(String args[]){
5. Calculation2 obj=new Calculation2();
6. obj.sum(10.5,10.5);
7. obj.sum(20,20);
8. }
9.}
Output:21.0
Why Method Overloaing is not possible by changing the return type
of method?
In java, method overloading is not possible by changing the return type
of the method because there may occur ambiguity. Let's see how
ambiguity may occur:
because there was problem:
1.class Calculation3{
2. int sum(int a,int b){System.out.println(a+b);}
3. double sum(int a,int b){System.out.println(a+b);}
4.
5. public static void main(String args[]){
6. Calculation3 obj=new Calculation3();
7. int result=obj.sum(20,20); //Compile Time Error
8.
9. }
10.}
int result=obj.sum(20,20); //Here how can java determine which sum()
method should be called
Can we overload main() method?
Yes, by method overloading. You can have any number of
main methods in a class by method overloading. Let's see the
simple example:
1.class Overloading1{
2. public static void main(int a){
3. System.out.println(a);
4. }
5.
6. public static void main(String args[]){
7. System.out.println("main() method invoked");
8. main(10);
9. }
10.}
Output:main() method invoked
10
Constructor in Java
Constructor in java is a special type of method that is used to initialize the object.
Java constructor is invoked at the time of object creation. It constructs the values i.e.
provides data for the object that is why it is known as constructor.
Rules for creating java constructor
There are basically two rules defined for the constructor.
1.Constructor name must be same as its class name
2.Constructor must have no explicit return type
Types of java constructors
There are two types of constructors:
1.Default constructor (no-arg constructor)
2.Parameterized constructor
A constructor that have no parameter is known as default constructor.
In this example, we are creating the no-arg constructor in the Bike class. It will be
invoked at the time of object creation.
Java Default Constructor
Syntax of default constructor:
1.<class_name>(){}
Example of default constructor
1.class Bike1{
2.Bike1(){System.out.println("Bike is created");}
3.public static void main(String args[]){
4.Bike1 b=new Bike1();
5.}
6.}
Output:
Bike is created
Rule: If there is no constructor in a class, compiler automatically creates a default
constructor.
What is the purpose of default constructor?
Default constructor provides the default values to the object like 0, null etc. depending
on the type.
Example of default constructor that displays the default values
1.class Student3{
2.int id;
3.String name;
4.
5.void display(){System.out.println(id+" "+name);}
6.
7.public static void main(String args[]){
8.Student3 s1=new Student3();
9.Student3 s2=new Student3();
10.s1.display();
11.s2.display();
12.}
13.}
Output:
0 null
0 null
Explanation:In the above class,you are not creating any constructor so compiler
provides you a default constructor.Here 0 and null values are provided by default
constructor.
A constructor that have parameters is known as parameterized constructor. Parameterized constructor
is used to provide different values to the distinct objects.
Java parameterized constructor
Why use parameterized constructor?
Example of parameterized constructor
1.class Student4{
2. int id;
3. String name;
4.
5. Student4(int i,String n){
6. id = i;
7. name = n;
8. }
9. void display(){System.out.println(id+" "+name);}
10.
public static void main(String args[]){
11. Student4 s1 = new Student4(111,"Karan");
12. Student4 s2 = new Student4(222,"Aryan");
13. s1.display();
14. s2.display();
15. }
16.}
Output:
111 Karan
222 Aryan
In this example, we have created the constructor of Student class that have two parameters. We can have any number of
parameters in the constructor.
Constructor Overloading in Java
Constructor overloading is a technique in Java in which a class can have any number of
constructors that differ in parameter lists. The compiler differentiates these constructors by taking
into account the number of parameters in the list and their type.
Example of Constructor Overloading
1.class Student5{
2. int id;
3. String name;
4. int age;
5. Student5(int i,String n){
6. id = i;
7. name = n;
8. }
9. Student5(int i,String n,int a){
10. id = i;
11. name = n;
12. age=a;
13. }
14. void display(){System.out.println(id+" "+name+" "+age);
15.}
1.public static void main(String args[]){
2. Student5 s1 = new Student5(111,"Karan");
3. Student5 s2 = new Student5(222,"Aryan",25);
4. s1.display();
5. s2.display();
6. }
7.}
Output:
111 Karan 0
222 Aryan 25
Difference between constructor and method in java
There are many differences between constructors and methods. They are given below.
Java Constructor
Java Method
Constructor is used to initialize the state of Method is used to expose behaviour of an
an object.
object.
Constructor must not have return type.
Method must have return type.
Constructor is invoked implicitly.
Method is invoked explicitly.
The java compiler provides a default
constructor if you don't have any
constructor.
Method is not provided by compiler in any
case.
Constructor name must be same as the
class name.
Method name may or may not be same as
class name.
Java Copy Constructor
There is no copy constructor in java. But, we can copy
the values of one object to another like copy
constructor in C++.
There are many ways to copy the values of one object
into another in java.
They are:
•By constructor
•By assigning the values of one object into another
•By clone() method of Object class
we are going to copy the values of one object into another using java
constructor.
class Student6{
int id;
String name;
Student6(int i,String n)
{
id = i;
name = n;
}
Student6(Student6 s){
id = s.id;
name =s.name;
}
void display(){System.out.println(id+" "+name);
}
public static void main(String args[]){
Student6 s1 = new Student6(111,"Karan");
Student6 s2 = new Student6(s1);
s1.display();
s2.display();
}
}
Output:
111 Karan
111 Karan
Copying values without constructor
We can copy the values of one object into another by assigning the objects values to another
object. In this case, there is no need to create the constructor.
1. class Student7
2. {
3. int id;
4. String name;
5. Student7(int i,String n)
6.{
7. id = i;
8. name = n;
9. }
10. Student7(){}
11. void display()
12.{
13.System.out.println(id+" "+name);
14.}
15.public static void main(String args[]){
16. Student7 s1 = new Student7(111,"Karan");
17. Student7 s2 = new Student7();
18. s2.id=s1.id;
19. s2.name=s1.name;
20. s1.display();
21. s2.display();
22. }
23.}
Output:
111 Karan
111 Karan
Does constructor return any value?
yes, that is current class instance (You cannot use return type yet it
returns a value).
Can constructor perform other tasks instead of initialization?
Yes, like object creation, starting a thread, calling method etc. You
can perform any operation in the constructor as you perform in
the method.
Java static keyword
The static keyword in java is used for memory management
mainly. We can apply java static keyword with variables,
methods, blocks and nested class. The static keyword belongs
to the class than instance of the class.
The static can be:
1.variable (also known as class variable)
2.method (also known as class method)
3.block
4.nested class
Java static variable
If you declare any variable as static, it is known static variable.
•The static variable can be used to refer the common property of all
objects (that is not unique for each object) e.g. company name of
employees,college name of students etc.
•The static variable gets memory only once in class area at the time of
class loading.
Advantage of static variable
It makes your program memory efficient (i.e it saves memory).
Understanding problem without static variable
1.class Student{
2. int rollno;
3. String name;
4. String college="ITS";
5.}
Suppose there are 500 students in my college, now all
instance data members will get memory each time
when object is created. All student have its unique
rollno and name so instance data member is good.
Here, college refers to the common property of all
objects. If we make it static,this field will get memory
only once.
Java static property is shared to all objects.
Example of static variable
1.//Program of static variable
2.
3.class Student8{
4. int rollno;
5. String name;
6. static String college ="ITS";
7.
8. Student8(int r,String n){
9. rollno = r;
10. name = n;
11. }
12. void display (){System.out.println(rollno+" "+name+" "+college);}
13.
14. public static void main(String args[]){
15. Student8 s1 = new Student8(111,"Karan");
16. Student8 s2 = new Student8(222,"Aryan");
17.
18. s1.display();
19. s2.display();
20. }
21.}
Output:111 Karan ITS
222 Aryan ITS
Program of counter without static variable
In this example, we have created an instance variable named count which is incremented in the
constructor. Since instance variable gets the memory at the time of object creation, each object
will have the copy of the instance variable, if it is incremented, it won't reflect to other objects.
So each objects will have the value 1 in the count variable.
1.class Counter{
2.int count=0;//will get memory when instance is created
3.
4.Counter(){
5.count++;
6.System.out.println(count);
7.}
8.
9.public static void main(String args[]){
10.
11.Counter c1=new Counter();
12.Counter c2=new Counter();
13.Counter c3=new Counter();
14.
15. }
16.}
Output:1
1
1
As we have mentioned above, static variable will get the memory only once, if any object changes the value of th
static variable, it will retain its value.
Program of counter by static variable
1.class Counter2{
2.static int count=0;//will get memory only once and retain its value
3.
4.Counter2(){
5.count++;
6.System.out.println(count);
7.}
8.
9.public static void main(String args[]){
10.
11.Counter2 c1=new Counter2();
12.Counter2 c2=new Counter2();
13.Counter2 c3=new Counter2();
14.
15. }
16.}
Output:1
2
3
Java static method
If you apply static keyword with any method, it is known as static method.
•A static method belongs to the class rather than object of a class.
•A static method can be invoked without the need for creating an instance of a class.
•static method can access static data member and can change the value of it.
Example of static method
1.//Program of changing the common property of all objects(static field).
2.
3.class Student9{
4. int rollno;
5. String name;
6. static String college = "ITS";
7.
8. static void change(){
9. college = "BBDIT";
10. }
11.
12. Student9(int r, String n){
13. rollno = r;
14. name = n;
15. }
16.
void display (){System.out.println(rollno+" "+name+" "+college);
}
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29. }
public static void main(String args[]){
Student9.change();
Student9 s1 = new Student9 (111,"Karan");
Student9 s2 = new Student9 (222,"Aryan");
Student9 s3 = new Student9 (333,"Sonoo");
s1.display();
s2.display();
s3.display();
}
Output:111 Karan BBDIT
222 Aryan BBDIT
333 Sonoo BBDIT
Another example of static method that performs normal calculation
1.//Program to get cube of a given number by static method
2.
3.class Calculate
4.{
5. static int cube(int x)
6.{
7. return x*x*x;
8. }
9.
10. public static void main(String args[])
11.{
12. int result=Calculate.cube(5);
13. System.out.println(result);
14. }
15.}
Output:125
There are two main restrictions for the static method. They are:
1. The static method can not use non static data member or call non-static method directly.
2. this and super cannot be used in static context.
Restrictions for static method
1.class A{
2. int a=40;//non static
3.
4. public static void main(String args[]){
5. System.out.println(a);
6. }
7.}
Output:Compile Time Error
why java main method is static?
Ans) because object is not required to call static method if it were non-static method, jvm create
object first then call main() method that will lead the problem of extra memory allocation.
Java static block
•Is used to initialize the static data member.
•It is executed before main method at the time of classloading.
Example of static block
1.class A2{
2. static{System.out.println("static block is invoked");}
3. public static void main(String args[]){
4. System.out.println("Hello main");
5. }
6.}
Output:static block is invoked
Hello main
Can we execute a program without main() method?
Ans) Yes, one of the way is static block but in previous
version of JDK not in JDK 1.7.
1.class A3
2.{
3. static
4.{
5. System.out.println("static block is invoked");
6. System.exit(0);
7. }
8.}
Output:static block is invoked (if not JDK7)
In JDK7 and above, output will be:
Output:Error: Main method not found in class A3, please define the main method as:
public static void main(String[] args)
this keyword in java
There can be a lot of usage of java this keyword. In java, this is a
reference variable that refers to the current object.
Usage of java this keyword
Here is given the 6 usage of java this keyword.
1.this keyword can be used to refer current class instance variable.
2.this() can be used to invoke current class constructor.
3.this keyword can be used to invoke current class method (implicitly)
4.this can be passed as an argument in the method call.
5.this can be passed as argument in the constructor call.
6.this keyword can also be used to return the current class instance.
Suggestion: If you are beginner to java, lookup only two usage of this
keyword.
The this keyword can be used to refer current class instance variable.
If there is ambiguity between the instance variable and parameter, this keyword resolves
the problem of ambiguity.
Understanding the problem without this keyword
1.class Student10{
2. int id;
3. String name;
4.
5. student(int id,String name){
6. id = id;
7. name = name;
8. }
9. void display(){System.out.println(id+" "+name);}
10.
11. public static void main(String args[]){
12. Student10 s1 = new Student10(111,"Karan");
13. Student10 s2 = new Student10(321,"Aryan");
14. s1.display();
15. s2.display();
16. }
17.}
Output:0 null
0 null
Let's understand the problem if we don't use this keyword by the example given below:
Solution of the above problem by this keyword
1.//example of this keyword
2.class Student11{
3. int id;
4. String name;
5.
6. Student11(int id,String name){
7. this.id = id;
8. this.name = name;
9. }
10. void display(){System.out.println(id+" "+name);}
11. public static void main(String args[]){
12. Student11 s1 = new Student11(111,"Karan");
13. Student11 s2 = new Student11(222,"Aryan");
14. s1.display();
15. s2.display();
16.}
17.}
Output111 Karan
222 Aryan
In the above example, parameter (formal arguments) and instance variables are same that is why we are using this keyword to
distinguish between local variable and instance variable.
Program where this keyword is not required
1.class Student12{
2. int id;
3. String name;
4.
5. Student12(int i,String n){
6. id = i;
7. name = n;
8. }
9. void display(){System.out.println(id+" "+name);}
10. public static void main(String args[]){
11. Student12 e1 = new Student12(111,"karan");
12. Student12 e2 = new Student12(222,"Aryan");
13. e1.display();
14. e2.display();
15.}
16.}
Output:111 Karan
222 Aryan
If local variables(formal arguments) and instance variables are different, there is no need to use this keyword
like in the following program:
this() can be used to invoked current class constructor.
The this() constructor call can be used to invoke the current class constructor (constructor chaining). This
approach is better if you have many constructors in the class and want to reuse that constructor.
1.//Program of this() constructor call (constructor chaining)
2.
3.class Student13{
4. int id;
5. String name;
6. Student13(){System.out.println("default constructor is invoked");}
7.
8. Student13(int id,String name){
9. this ();//it is used to invoked current class constructor.
10. this.id = id;
11. this.name = name;
12. }
13. void display(){System.out.println(id+" "+name);}
14.
15. public static void main(String args[]){
16. Student13 e1 = new Student13(111,"karan");
17. Student13 e2 = new Student13(222,"Aryan");
18. e1.display();
19. e2.display();
20. }
21.}
Output:
default constructor is invoked
default constructor is invoked
111 Karan
222 Aryan
The this() constructor call should be used to reuse the constructor in the constructor. It maintains the chain
between the constructors i.e. it is used for constructor chaining. Let's see the example given below that displays
the actual use of this keyword.
Where to use this() constructor call?
1.class Student14{
2. int id;
3. String name;
4. String city;
5.
6. Student14(int id,String name){
7. this.id = id;
8. this.name = name;
9. }
10. Student14(int id,String name,String city){
11. this(id,name);//now no need to initialize id and name
12. this.city=city;
13. }
14. void display(){System.out.println(id+" "+name+" "+city);}
15.
public static void main(String args[]){
16. Student14 e1 = new Student14(111,"karan");
17. Student14 e2 = new Student14(222,"Aryan","delhi");
18. e1.display();
19. e2.display();
20. }
21.}
Output:111 Karan null
222 Aryan delhi
Call to this() must be the first statement in constructor.
1.class Student15{
2. int id;
3. String name;
4. Student15(){System.out.println("default constructor is invoked");}
5.
6. Student15(int id,String name){
7. id = id;
8. name = name;
9. this ();//must be the first statement
10. }
11. void display(){System.out.println(id+" "+name);}
12.
13. public static void main(String args[])
14.{
15. Student15 e1 = new Student15(111,"karan");
16. Student15 e2 = new Student15(222,"Aryan");
17. e1.display();
18. e2.display();
19. }
20.}
Output:Compile Time Error