Java Unit 1-2
Java Unit 1-2
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
James Gosling
Bill joy
Patric Noughten
} are the father (developers) of java programing.
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.
2
Java programming
Java Virtual Machine [JVM]
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.
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
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.
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.
4. Unary -- operator:
It refers to Decrement by one.
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
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
Syntax:
result = exp_1 ? exp_2 : exp_3;
Example: a = 10;
b = 5;
large = a > b ? a : b ;
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
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
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
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.
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; */
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;
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”);
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.
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;
}
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;
}
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
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 );
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 );
}
}
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;
}
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.
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( );
}
}
}
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;
CONTINUE STATEMENT
It is used to continue the statements, looping and conditions in a java
program.
General syntax:
continue;
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;
}
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);
}
}
General Syntax:
[modifier][return_type] method_name (datatype arg1, datatype arg2…)
{
declarations and statements;
:
:
return expression;
}
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.
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;
}
//Program
class overloading
{
int add(int x,int Y)
{
return x+y;
}
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));
}
}
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].
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};
40
Java programming
Memory representation of one dimensional array
Suppose the following example;
int[] a = new int[5];
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.
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
43
Java programming
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.
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:
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
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;
2. In general, we can give a method whatever name we like. However, remember that
main() is reserved for entry point program execution.
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:
Example:
class student
{
int a,b;
void show()
{
-----------
-----------
}
}
student s=new student();
s.show();
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;
}
}
void function2()
{
System.out.println(i);
System.out.println(j);
System.out.println(“Inside function2() “);
}
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;
}
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;
}
}
ths()
{
this(100);
}
ths(int a)
{
this(a,200);
}
ths(int a, int b)
{
this(a,b,300);
}
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);
}
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);
}
}
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