Java Programming Basics Explained
Java Programming Basics Explained
In 1991 james gosling (project leader) wants to develop a software which is used in T.V remotes, micro
wovens, refrigerators. James gosling first selected 'C++' language to develop that software. After some
development, he finds some problems to develop software in 'C++'. The problems are pointers and
operator overloading. The main problem by using C++ is that is system dependent. Then he wants first
to develop a new language which is similar to C++, which eliminates pointers and operator overloading
and difficult topics in 'C++' language and which is system independent. Then he develops new language
called "OAK" (tree name). But the name is already registered in software industry. So it was renamed as
java (coffee seed) in 1995. After some modifications finally java was developed by Sun Micro Systems of
U.S.A.
Versions of Java
C, C++ are called platform dependent languages. Because these languages produces executable files.
These executable files executes only on particular platform (operating system). After compiling java
produces class file which contains byte codes. These byte codes are intermediate code, which is not
related to any operating system. But executes on any operating system with the help of JVM (Java
Virtual Machine). JVM is the interpreter for byte codes. JVM converts the byte codes into appropriate
operating system instructions. The slogan of java is "write once, run anywhere (os)".
Editions of Java
J2SE :- It deals with developing standalone applications, fundamental applications for a network.
Embedded Systems :- Storing programs in hardware or chip. Using embedded systems we can write
programs directly in chips.
Features of Java
Simple :- Java is a simple programming language. Learning java is easy. Because almost java syntax is
similar to 'C' and 'C++'. Difficult topics are eliminated in java like pointers and operator overloading. The
following topics are also eliminated from java. (goto, global variables, typedef, sizeof, unsigned integer,
structures, unions, header files, multiple inheritance).
Object Oriented :- Java is purely object oriented language. Whereas C++ is not purely object oriented
language. Another example for purely object oriented language is small talk.
Object :- Real things that we can see and touch are called objects. An object is anything that exists
physically in the world. An object can perform activities. In programming languages, objects are
instances (variables) of classes. An object contains properties (variables) and actions (methods).
Method :- It is nothing but a function. But comparing with function the difference is, it must be written
inside a class. We don't have functions in java, only methods are there.
Class :- A class is a model or blue print for creating objects. A class is a group name given to objects. It
specifies the properties and actions of objects. In programming languages, a class is an user-defined
data type. By using class concept we can create new data types. In C++, without using class we can write
a program. So it is not a purely object oriented. In java, we must write at least one class to perform
anything.
Distributed :- Using java we can develop network applications. Network application is used by all
systems in that network.
Robust (Strong / Unbreakable) :- Java programs will not crash easily. Because of its memory
management and exception handling features, we can write break free programs. Generally programs
are break due to memory insufficiency. In java, memory is allotted by JVM's class loader sub system and
deallocation is done by JVM's garbage collector.
Garbage Collector :- It removes unused variables & objects from the memory. This memory can be used
by another variables or objects.
Secure :- Java is a secure language because java contains firewalls. Firewalls strictly checks everything
before downloading into our system. Java enables the construction of virus free applications.
Architecture Neutral :- Java's byte code is not machine dependent. It can run on any machine with any
processor and any operating system.
Interpreted :- Java programs are compiled to generate the byte code. This byte code can be downloaded
and is executed by the interpreter. Both compiler and interpreter present in java.
[Link] ====> compiler ====> [Link] ====> JVM (interpreter + JIT compiler)
High Performance :- Along with interpreter, there will be a JIT (Just in time) compiler, which enhances
the speed of execution. So that both compiler and interpreter run the program simultaneously.
Multi Threaded :- Thread means process or execution. Executing different parts of a program
simultaneously is called multithreading. This is an essential feature to design server side programs.
Dynamic :- We can develop programs in java which dynamically interact with the user on internet.
javac (compiler):- It is used to convert java program into class file which contains byte codes.
javap (profiler compiler) :- It is used to convert class file into java program. It gives only structure of the
java program. If we use "JAD" utility we get entire java program from class file.
javah (header file compiler) :- It is used to include native methods, header files into java program.
javadoc (documentation compiler) :- It is used to convert java program into html document. The
generated html document is called API (application programming interface) document.
1) Standalone applications
2) Applets
Standalone applications :- These are general programs which are not related to internet. These
applications are executed by java interpreter (java tool). These applications contains main( ) method. So
program execution starts from main( ) method.
Applets :- These are small web programs. Applets are executed by web browser (internet explorer,
mozilla firefox) or appletviewer tool. Because these applications don't have main( ) method.
A Sample Program
class First
{
public static void main(String args[ ])
{
[Link]("Welcome to Java Programming");
}
}
Note :- The above program must be saved as "[Link]". Because class name and file name must be
same. In java all class names must start with upper case alphabet.
edit [Link]
write program
[Link] :- System is a class and out it a data member(variable). It refers to monitor. print( ) is a
method (function) of System class. It is used to display information on the screen.
public :- main( ) method is called outside the class. So it is declared as public. public members can access
from anywhere.
static :- Generally any method is called by using an object. A static method is a method which is called
without creating an object through class.
String args[] :- args is an array of String data type. args stores command line arguments.
class Second
{
public static void main(String args[ ])
{
[Link]("One");
[Link]("Two");
[Link]("Three");
}
}
Importing packages :- Before using any class we must import the appropriate package in the following
manner.
import package_name.class_name;
Ex :- import [Link];
import [Link];
If we write
import [Link].*;
All classes are imported from [Link] package into our program.
[Link] :- It contains primary classes for java programming like System, String etc. This package is
imported by default into every java program.
2) class / interface name in java name should start with capital letter. If a class or interface has multiple
words then each word of class or interface start with a capital letter.
3) method name should start with small letter. If a method has multiple words then each word of
method start with a capital letter.
5) constant (literals) variables should be written using all capital letters. Use underscore if a constant
has multiple words.
[Link] (language):- The basic classes that are used in java program are present in this package. This
package contains primary classes and interfaces. It is essential for java program.
[Link] (utilities):- This package contains useful classes and interfaces like Stack, LinkedList, Date,
Arrays etc.
[Link] :- This package contains classes which handles input and output operations.
[Link] (Abstract Window Toolkit) :- This package helps to develop GU (Graphical User Interface)
applications.
[Link] :- It is extension to [Link] package. This package helps to develop GUI applications like
[Link]. It contains more graphics.
x :- Stands for extended package. It means in first java version we don't have these packages.
Server :- Server is a machine which serves information to the client. A server can serve information to
any number of clients at a time.
[Link] :- Applets are small intelligent programs which travel from one place to another place in
internet. Applet is a program comes from server into client machine and displays the result in client
machine. This package contains applet related classes.
[Link] (Structured Query Language):- This package helps to connect the databases (Ms-Access, Oracle,
Sybase, Mysql) and utilize them in java program.
[Link] :- Beans are software reliable components (push button, check box, drop down list etc). They
can be developed using this package. Once we create a component this can be used again and again by
different people in different programs without redeveloping them.
[Link] (Remote Method Invocation):- It is technology to call methods of remote objects and use
them. The objects which exist on one computer in network can be called from another computer and
can be used.
[Link] :- Servlets are server side programs which handle clients. This package is useful to develop
servlets.
Data Types
The default precision is set to int in integer family. long integer constants must be postfixed with "l" /
"L".
ex :- long x = 100L;
The default precision is set to double in real family. Float constants must be postfixed with "f" / "F".
Ex :- float x = 12.34F;
Character (2 bytes) :- When we type the character on keyboard a relevant integer code is generated.
This code is called ASCII code. In java character occupies 2 bytes. Because it supports unicode character
set. Unicode is a specification to include all international languages into the character set of java.
String :- A string represents a group of characters. Any string is an object of String class in java. Any
object in java is created with new operator.
Creating Strings
class Third
{
public static void main(String args[])
{
byte b;
short s;
int i;
long l;
float f;
double d;
char c;
boolean b1;
String s1;
b = 10;
s = 30000;
i = 999999;
l = 123456L;
f = 1.23F;
d = 123.456789;
c = 'K';
b1 = true;
s1 = "Rama";
[Link](b);
[Link]("B Value : " + b); // + ====> Concatenation / Joining Operator
[Link](b + " is B Value");
[Link]("Ravana has " + b + " Heads");
[Link]("S Value : " + s);
[Link]("I Value : " + i);
[Link]("L Value : " + l);
[Link]("F Value : " + f);
[Link]("D Value : " + d);
[Link]("C Value : " + c);
[Link]("B1 Value : " + b1);
[Link]("S1 Value : " + s1);
}
}
Square of a number
class Four
{
public static void main(String args[ ] )
{
int n,s;
n = 6;
s = n * n;
[Link]("Square : " + s);
}
}
class Five
{
public static void main(String args[ ] )
{
int a,b,c;
a = 10;
b = 20;
c = a + b;
[Link]("Sum : " + c);
}
}
class Six
{
public static void main(String args[ ] )
{
int a;
byte b;
a = 10;
b = 20;
[Link]("A Value : %d\n",a);
[Link]("B Value : %d",b);
}
}
class Six
{
public static void main(String args[ ] )
{
float f = 123.456F;
double d = 123.456789;
[Link]("F Value : %f\n",f);
[Link]("F Value : %.2f\n",f);
[Link]("D Value : %f\n",d);
[Link]("D Value : %.2f\n",d);
[Link]("F Value : %e\n",f);
[Link]("F Value : %.2e\n",f);
[Link]("D Value : %e\n",d);
[Link]("D Value : %.2e",d);
}
}
class Six
{
public static void main(String args[ ] )
{
int n,s;
n = 6;
s = n * n;
[Link]("Square : " + s);
}
}
We run the above any number of times, the programs gives the same output. Because 'n' value is fixed.
If we pass the 'n' value after running / before running we can provide different values at each runtime.
So the above program is useless.
Command line arguments :- These arguments are passed before running the program from command
line. These arguments are stored in the array named args of type String.
class Six
{
public static void main(String args[ ] )
{
[Link](args[0]);
}
}
In java arrays has a special property called "length". It is used to find size of the array.
class Six
{
public static void main(String [ ]val)
{
int i,n;
n = [Link];
[Link]("Passed Arguments are : ");
for(i = 0; i < n; i++)
{
[Link](val[i] + "\t");
}
}
}
Passing numeric type arguments
Wrapper Classes :- These classes are used to convert primitive data types / simple data types (int, char,
float, double, boolean) into object data types and object data types into primitive data types. Advantage
of converting from primitive data types into object data types is, objects has methods to operate the
data.
parseInt( ) :- This method is used to convert number from string object format into simple integer
format. parseInt( ) is a static method in Integer class.
class Six
{
public static void main(String [ ]args)
{
int x;
x = [Link](args[0]);
[Link]("X Value : " + x);
}
}
class Six
{
public static void main(String [ ]args)
{
int n,s;
n = [Link](args[0]);
s = n * n;
[Link]("Square : " + s);
}
}
class Six
{
public static void main(String [ ]args)
{
int x,y,z;
x = [Link](args[0]);
y = [Link](args[1]);
z = x + y;
[Link]("Sum : " + z);
}
}
long k; String p;
k = [Link](args[0]); p = args[0];
byte x; short x;
x = [Link](args[0]); x = [Link](args[0]);
float x; double d;
x = [Link](args[0]); d = [Link](args[0]);
class Six
{
public static void main(String args[ ])
{
int eno,msal,asal;
float dsal;
String ename;
eno = [Link](args[0]);
ename = args[1];
msal = [Link](args[2]);
asal = msal * 12;
dsal = msal / 30.0F;
[Link]("Employee Number : " + eno);
[Link]("Employee Name : " + ename);
[Link]("Monthly Salary : " + msal);
[Link]("Annual Salary : " + asal);
[Link]("Day Salary : " + dsal);
}
}
Java does not supports garbage values. Before using a variable we must store some value in it.
class Six
{
public static void main(String args[ ])
{
int a;
a = 10;
[Link]("A Value : " + a);
}
}
Initialization
class Six
{
public static void main(String args[ ])
{
int a = 10; // Static initialization
[Link]("A Value : " + a);
}
}
class Six
{
public static void main(String args[ ])
{
int a = [Link](args[0]); // Dynamic initialization
[Link]("A Value : " + a);
}
}
Literals / Constants :- These variables stores only one value. We can't change these values. Generally
known values are declared as literals. Generally we must initialize literals. Literals are declared by using
"final" keyword.
class Six
{
public static void main(String args[ ])
{
final int a = 10;
a = 20; (error)
[Link]("A Value : " + a);
}
}
Flexible declarations :- In java we can declare variables any where in the program, just before use.
class Six
{
public static void main(String args[ ])
{
int a,b;
a = 10;
b = 20;
int c;
c = a + b;
[Link]("Sum : " + c);
}
}
A variable may initialize with a constant / variable / expression / function return value.
A variable may declare in for loop also. But it's scope is within for loop.
class Six
{
public static void main(String args[ ])
{
for(int i = 1; i <= 5; i++)
{
[Link](i + "\t");
}
[Link](i); (error)
}
}
Type Casting
To perform automatic conversion, target variable memory size must be greater than source variable
memory size.
class Six
{
public static void main(String args[ ])
{
int x;
x = 'A';
[Link]("X Value : " + x);
char y;
y = 65;
[Link]("Y Value : " + y);
int i;
i = 10;
float f;
f = i;
[Link]("I Value : " + i);
[Link]("F Value : " + f);
f = 12.34F;
i = (int) f;
[Link]("I Value : " + i);
[Link]("F Value : " + f);
byte b;
b = 10;
i = b;
[Link]("B Value : " + b);
[Link]("I Value : " + i);
i = 20;
b = (byte) i;
[Link]("B Value : " + b);
[Link]("I Value : " + i);
}
}
If an integer expression contains byte variables or short variables or int variables then the entire
expression is converted into int.
class Six
{
public static void main(String args[ ])
{
byte a,b;
int c;
a = 10;
b = 20;
c = a + b;
[Link]("Sum : " + c);
byte d;
d = (byte) (a + b);
[Link]("Sum : " + d);
}
}
Operators :- An operator is a special symbol which performs some operation. An operator acts on some
variables or constants which are called operands. Operators are classified into four categories.
1) Unary operators
2) Binary operators
[ ++, --, - ]
class Six
{
public static void main(String args[ ])
{
int a;
a = 10;
[Link]("A Value : " + (a++));
[Link]("A Value : " + a);
int b;
b = 10;
[Link]("B Value : " + (++b));
[Link]("B Value : " + b);
}
}
Binary operators :- Which works on two operands. These operators are classified into the following
categories.
1) Arithmetical operators
2) Assignment operator
(Shorthand operators)
3) Relational operators
4) Logical operators
5) Boolean operators
6) Bitwise operators
Arithmetical operators :- These operators are used to perform arithmetical operations like addition,
subtraction etc.
[ +, -, *, /, % ]
Assignment operator (=) :- It is used to store values / data / constants into a variable. It contains a sub
category called shorthand operators.
[ += ,-=, *=, /=, %= ]
Relational operators :- These operators are used to check relation between two operands. These
operators always return boolean value.
[ >, >=, <, <=, ==, != ]
Logical operators :- These operators are used to join multiple conditions. The purpose of these
operators is to check more than one condition.
[ &&, ||, ! ]
Boolean operators :- These operators only work with boolean data type variables.
[ &, |, ^, ! ]
& boolean and
| boolean or
^ (carat) boolean xor (exclusive) (both operands contains different values)
! boolean not
class Six
{
public static void main(String args[ ])
{
boolean x,y,res;
x = true;
y = false;
res = x & y;
[Link](res);
res = x | y;
[Link](res);
res = x ^ y;
[Link](res);
y = true;
res = x ^ y;
[Link](res);
[Link](!x);
}
}
Bitwise operators :- These operators are used to perform operations on bits. Advantage of using these
operators is speed.
[ ~, &, |, ^, <<, >>, >>> ]
~ :- bitwise compliment
& :- bitwise and
| :- bitwise or
^ :- bitwise xor (exclusive)
<< :- left shift
>> :- right shift
>>> :- zero fill / unsigned right shift
class Six
{
public static void main(String args[ ])
{
int a,b;
a = 25;
[Link](a);
[Link](~a);
a = 15;
b = 25;
[Link](a & b);
[Link](a | b);
[Link](a ^ b);
a = 20;
[Link](a << 2);
[Link](a >> 2);
a = 24;
[Link](a >> 2);
[Link](a >>> 2);
a = -24;
[Link](a >> 2);
[Link](a >>> 2);
}
}
In case of positive values, there is no difference between right shift and zero fill right shift operators.
Ternary operator :- it is the alternative construct to simple if else statement. This operator takes three
expressions. That's why it is called ternary operator. It is also called conditional operator.
class Six
{
public static void main(String args[ ])
{
int a,b,c;
a = [Link](args[0]);
b = [Link](args[1]);
c = (a > b) ? a : b;
[Link]("Big Number : " + c);
}
}
class Six
{
public static void main(String args[ ])
{
String str = "Rama";
boolean b;
b = str instanceof String;
[Link](b);
}
}
new operator :- It is the most commonly used operator in java. It is used to create objects. JVM will allot
memory for objects in heap area.
PrintStream :- This class is used to print information on the screen. It is an alternative class to system
class.
import [Link];
class Six
{
public static void main(String args[ ])
{
PrintStream ps = new PrintStream([Link]);
int a = 10;
[Link]("Program Started");
[Link]("Welcome to Print Stream Class");
[Link]("A Value : " + a);
[Link]("Program Ended");
}
}
read( ) :- This method inputs single character. This method reads data in integer format. So need type
casting. This method throws IOException. So we have to type “throws IOException" along with main
method.
import [Link];
import [Link];
class Six
{
public static void main(String args[ ]) throws IOException
{
PrintStream ps = new PrintStream([Link]);
char x;
[Link]("Enter Character");
x = (char) [Link]( );
[Link]("Character : " + x);
}
}
import [Link].*;
class Six
{
public static void main(String args[ ]) throws IOException
{
PrintStream ps = new PrintStream([Link]);
BufferedReader br = new BufferedReader(new InputStreamReader([Link]));
String name;
[Link]("Enter Your Name");
name = [Link]( );
[Link]("Your Name : " + name);
}
}
import [Link].*;
class Six
{
public static void main(String args[ ]) throws IOException
{
PrintStream ps = new PrintStream([Link]);
BufferedReader br = new BufferedReader(new InputStreamReader([Link]));
String temp;
int n;
[Link]("Enter Integer");
temp = [Link]( );
n = [Link](temp);
[Link]("Integer : " + n);
}
}
import [Link].*;
class Six
{
public static void main(String args[ ]) throws IOException
{
PrintStream ps = new PrintStream([Link]);
BufferedReader br = new BufferedReader(new InputStreamReader([Link]));
String temp;
float n;
[Link]("Enter Float");
temp = [Link]( );
n = [Link](temp);
[Link]("Float : " + n);
}
}
[Link]( ), [Link]( ), [Link]( ), [Link]( )
Square of a number
import [Link].*;
class Six
{
public static void main(String args[ ]) throws IOException
{
PrintStream ps = new PrintStream([Link]);
BufferedReader br = new BufferedReader(new InputStreamReader([Link]));
int n,s;
[Link]("Enter Number");
n = [Link]([Link]( ));
s = n * n;
[Link]("Square : " + s);
}
}
import [Link].*;
class Six
{
public static void main(String args[ ]) throws IOException
{
PrintStream ps = new PrintStream([Link]);
BufferedReader br = new BufferedReader(new InputStreamReader([Link]));
int a,b,c;
[Link]("Enter Two Numbers");
a = [Link]([Link]( ));
b = [Link]([Link]( ));
c = a + b;
[Link]("Sum : " + c);
}
}
Using DataInputStream to input data
import [Link].*;
class Six
{
public static void main(String args[ ]) throws IOException
{
PrintStream ps = new PrintStream([Link]);
DataInputStream dis = new DataInputStream([Link]);
int a,b,c;
[Link]("Enter Two Numbers");
a = [Link]([Link]( ));
b = [Link]([Link]( ));
c = a + b;
[Link]("Sum : " + c);
}
}
By using this class we can directly connect with keyboard. The main advantage of using this class is to
read numeric types of data without converting it. This class can't throws IOException. It is available in
[Link] package. This class contains the following methods.
import [Link];
import [Link];
class Six
{
public static void main(String args[ ])
{
PrintStream ps = new PrintStream([Link]);
Scanner sc = new Scanner([Link]);
String st;
[Link]("Enter String");
st = [Link]( ); // st = [Link]( );
[Link]("String : " + st);
}
}
import [Link];
import [Link];
class Six
{
public static void main(String args[ ])
{
PrintStream ps = new PrintStream([Link]);
Scanner sc = new Scanner([Link]);
int a,b,c;
[Link]("Enter Two Numbers");
a = [Link]( );
b = [Link]( );
c = a + b;
[Link]("Sum : " + c);
}
}
Infinite loops
import [Link];
import [Link];
class Six
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
Scanner sc = new Scanner([Link]);
int n,r;
[Link]("Enter Numbers, 0 to Stop");
while(true) // for(; ;)
{
n = [Link]( );
if(n == 0)
{
break;
}
if(n % 2 == 0)
{
[Link]("Even Number");
}
else
{
[Link]("Odd Number");
}
}
}
}
Labelled loops
import [Link];
class Six
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
int i,j;
xxx :
for(i = 1; i <= 5; i++)
{
[Link]("J = ");
for(j = 1; j <= 5; j++)
{
[Link](j + "\t");
if(j == 3)
{
break xxx; / continue xxx;
}
}
[Link]( );
}
}
}
Arrays
An array is a group of items of similar data type. Each item is called an element. Each element has an
unique index. Array index always starts from zero. So an array is always created with n-1. In java arrays
are called as objects. The main advantage of objects is, objects contains methods which operates the
data. An object is always creates with the help of new operator. An object is destroyed by assigning null
keyword.
In java, arrays has a special property called length, which returns size of the array.
import [Link];
class Six
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
int a[ ];
a = new int[5];
a[0] = 10;
a[1] = 20;
a[2] = 30;
a[3] = 40;
a[4] = 50;
[Link]("Array Elements");
for(int i = 0; i < [Link]; i++)
{
[Link](a[i] + "\t");
}
}
}
Initializing Arrays
int a[] = {10,20,30,40,50,60}; At the time of initialization we can't use new keyword.
It executes once for a each element in a collection / group. The counter variable must be declared in for
loop.
import [Link];
class Six
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
int a[] = {10,20,30,40,50,60};
[Link]("Array Elements");
for(int i : a)
{
[Link](i + "\t"); (i ====> a[i])
}
}
}
Note :- for each loop can access only value from the array. It is unable to perform any other operation
on the array.
String Arrays
import [Link];
import [Link];
class Six
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
Scanner sc = new Scanner([Link]);
String names[ ] = new String[5];
[Link]("Enter Five Names");
for(int i = 0; i < [Link]; i++)
{
names[i] = [Link]( );
}
[Link]("Names : ");
for(String i : names)
{
[Link](i + "\t"); (i ====> names[i])
}
}
}
2-D Arrays
import [Link];
class Six
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
int a[][]; / int [ ][ ]a; / int [ ]a[ ];
a = new int[3][5];
a[0][0] = 10;
a[0][1] = 20;
a[0][2] = 30;
a[0][3] = 40;
a[0][4] = 50;
a[1][0] = 60;
a[1][1] = 70;
a[1][2] = 80;
a[1][3] = 90;
a[1][4] = 100;
a[2][0] = 110;
a[2][1] = 120;
a[2][2] = 130;
a[2][3] = 140;
a[2][4] = 150;
[Link]("Array Elements");
for(int i = 0; i < [Link]; i++)
{
for(int j = 0; j < a[i].length; j++)
{
[Link](a[i][j] + "\t");
}
[Link]( );
}
}
}
import [Link];
class Six
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
int a[][] = new int[3][];
a[0] = new int[5];
a[1] = new int[3];
a[2] = new int[6];
a[0][0] = 10;
a[0][1] = 20;
a[0][2] = 30;
a[0][3] = 40;
a[0][4] = 50;
a[1][0] = 60;
a[1][1] = 70;
a[1][2] = 80;
a[2][0] = 90;
a[2][1] = 100;
a[2][2] = 110;
a[2][3] = 120;
a[2][4] = 130;
a[2][5] = 140;
[Link]("Array Elements");
for(int i = 0; i < [Link]; i++)
{
for(int j = 0; j < a[i].length; j++)
{
[Link](a[i][j] + "\t");
}
[Link]( );
}
}
}
class Sample
{
public static void main(String args[])
{
int arr[][] = { {10,20,30}, {40,50,60,70}, {80,90} };
[Link]("Array Length : " + [Link]);
[Link]("First Row Length : " + arr[0].length);
[Link]("Second Row Length : " + arr[1].length);
[Link]("Third Row Length : " + arr[2].length);
}
}
Assigning Arrays
hashCode( ) :- This method returns memory location which is pointed by an object. Unique id number
given to every object by JVM. It is also called reference number.
import [Link];
class Six
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
int a[] = {10,20,30,40,50};
int b[] = a;
[Link]("Array A Elements");
for(int i : a)
{
[Link](i + "\t");
}
[Link]( );
[Link]("Array B Elements");
for(int i : b)
{
[Link](i + "\t");
}
[Link]( );
[Link]("A Points to : " + [Link]( ) );
[Link]("B Points to : " + [Link]( ) );
}
}
Note :- In the above program arrays a & b are points to same location.
Copying Arrays
import [Link];
class Six
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
int a[] = {10,20,30,40,50};
int b[] = new int[5];
for(int i = 0; i < [Link]; i++)
{
b[i] = a[i];
}
[Link]("Array A Elements");
for(int i : a)
{
[Link](i + "\t");
}
[Link]( );
[Link]("Array B Elements");
for(int i : b)
{
[Link](i + "\t");
}
[Link]( );
[Link]("A Points to : " + [Link]( ) );
[Link]("B Points to : " + [Link]( ) );
}
}
Note :- In the above program arrays a & b are points to different locations.
arraycopy( ) :- This method is used to copy an array. This method is a static method in system class.
import [Link];
class Six
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
int a[] = {10,20,30,40,50};
int b[] = new int[5];
[Link](a,0,b,0,5);
// arrarycopy(Source Array, Source Array Starting Index,
// Target Array, Target Array Starting Index, Number of // Elements To Be copied)
[Link]("Array A Elements");
for(int i : a)
{
[Link](i + "\t");
}
[Link]( );
[Link]("Array B Elements");
for(int i : b)
{
[Link](i + "\t");
}
}
}
Comparing Arrays
import [Link];
class Six
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
int a[] = {10,20,30,40,50};
int b[] = {10,20,30,40,50};
if(a == b)
{
[Link]("Both are equal Arrays");
}
else
{
[Link]("Both are not equal Arrays");
}
}
}
equals( ) :- This method is used to compare two arrays. If both are equal then it returns true otherwise
returns false.
import [Link];
import [Link];
class Six
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
int a[] = {10,20,30,40,50};
int b[] = {10,20,30,40,50};
if([Link](a,b))
{
[Link]("Both are equal Arrays");
}
else
{
[Link]("Both are not equal Arrays");
}
}
}
Filling Arrays
fill( ) :- This method is used to fill an entire array / a range (partial array) with a specific value.
import [Link];
import [Link];
class Six
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
int a[] = new int[10];
[Link](a,6);
[Link]("Array A Elements");
for(int i : a)
{
[Link](i + "\t");
}
[Link]( );
int b[] = new int[10];
[Link](b,0,3,6); // N = EI - SI
[Link](b,3,7,3);
[Link](b,7,10,63);
[Link]("Array B Elements");
for(int i : b)
{
[Link](i + "\t");
}
}
}
Sorting Arrays
sort( ) :- This method is used to sort (arrange data in ascending order) an entire array / a range (partial
array).
import [Link];
import [Link];
class Six
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
int a[] = {30,60,50,10,40,20};
[Link]("Before Sorting, Array A Elements");
for(int i : a)
{
[Link](i + "\t");
}
[Link]( );
[Link](a);
[Link]("After Sorting, Array A Elements");
for(int i : a)
{
[Link](i + "\t");
}
[Link]( );
int b[] = {30,60,50,10,40,20};
[Link]("Before Sorting, Array B Elements");
for(int i : b)
{
[Link](i + "\t");
}
[Link]( );
[Link](b,0,4);
[Link]("After Sorting, Array B Elements");
for(int i : b)
{
[Link](i + "\t");
}
}
}
Searching
binarySearch( ) :- This method is used to search for an element in the array. If search element founds
returns index of the search element otherwise returns negative value.
import [Link];
import [Link];
import [Link];
class Six
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
Scanner sc = new Scanner([Link]);
int a[] = {40,50,60,20,30,10};
int se,pos;
[Link]("Enter Search Element");
se = [Link]( );
[Link](a);
pos = [Link](a,se);
if(pos < 0)
{
[Link]("Element Not Found");
}
else
{
[Link]("Element Found at Position : " + (pos+1));
}
}
}
Methods
A method is nothing but a function, which performs some task. Mainly methods are classified into two
categories.
Void Methods
class Six
{
static void show( )
{
[Link]("show method called");
}
public static void main(String args[])
{
show( );
}
}
Returnable Methods
class Six
{
static int square(int x)
{
return x * x;
}
public static void main(String args[])
{
int k;
k = square(6);
[Link]("Square : " + k);
[Link]("Square : " + square(3));
}
}
Strings
A string represents a group of characters. Unlike C, string is not an character array in java and it is not
terminated with null character (\0). In java any string is an object of String class. We can directly assign a
string constant to a string object. String class is available in [Link] package.
import [Link];
class Six
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
String str = "Rama";
[Link]("String : " + str);
}
}
import [Link];
class Six
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
String str = new String("Rama");
[Link]("String : " + str);
}
}
Third way :- We can create a string by converting character array into string object.
import [Link];
class Six
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
char ar[] = {'T','E','N','A','L','I'};
String str = new String(ar);
[Link]("String : " + str);
}
}
Note :- We can also create a string with some characters from a character array.
import [Link];
class Six
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
char ar[] = {'T','E','N','A','L','I'};
String str = new String(ar,2,3);
[Link]("String : " + str);
}
}
+ :- This operator is called concatenation / joining operator. This operators concats two or more strings.
import [Link];
class Six
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
String str1 = "Rama";
String str2 = "Krishna";
String str3;
str3 = str1 + str2;
[Link]("String : " + str3);
}
}
import [Link];
class Six
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
String str1 = "Rama";
String str2 = "Krishna";
String str3,str4;
str3 = [Link](str2);
str4 = [Link](str1);
[Link]("String : " + str3);
[Link]("String : " + str4);
}
}
Note :- Concatenation operator concats any type of data. But concat( ) method concats only string type
of data.
import [Link];
class Six
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
String str1 = "Rama";
int n = 10;
String str2;
str2 = str1 + n;
[Link]("String : " + str2);
}
}
import [Link];
class Six
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
String str1 = "Rama";
int n = 10;
String str2;
str2 = [Link](n); (error)
[Link]("String : " + str2);
}
}
Note :- Concatenation operators concats any number of strings. But concat( ) method concats only two
strings.
import [Link];
class Six
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
String str1 = "Raja ";
String str2 = "Ram ";
String str3 = "Mohan ";
String str4 = "Roy";
String str5;
str5 = str1 + str2 + str3 + str4;
[Link]("String : " + str5);
}
}
length( ) :- This method is used to find length of string. length means how many characters in a string.
import [Link];
class Six
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
String str = "Rama Rao";
int n;
n = [Link]( );
[Link]("String Length : " + n);
}
}
Character extraction
charAt( ):- This method is used to extract (access / get) a character from a string.
import [Link];
class Six
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
String str = "Rama Krishna";
char x;
x = [Link](5);
[Link]("Extracted Character : " + x);
}
}
import [Link];
class Six
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
String str = "Rama Krishna";
[Link]("String : " + str);
[Link]("String : ");
for(int i = 0; i < [Link]( ); i++)
{
[Link]([Link](i) + " ");
}
}
}
getChars( ) :- This method is used to extract multiple character from a string into a character array.
import [Link];
class Six
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
String str = "Raja Ram Mohan Roy";
char x[] = new char[3];
[Link](5,8,x,0);
// getChars(Source String Starting Index, Source String Ending, Index, Target Array, Target Array Starting
// index)
[Link]("String : " + str);
[Link]("Extracted String : ");
for(int i = 0; i < [Link]; i++)
{
[Link](x[i]);
}
}
}
Comparing Strings
import [Link];
class Six
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
String str1 = new String("Rama");
String str2 = new String("Rama");
if(str1 == str2)
{
[Link]("Both are equal Strings");
}
else
{
[Link]("Both are not equal Strings");
}
}
}
equals( ) :- This method is used to compare two strings. If both are equal then it returns true otherwise
returns false.
equalsIgnoreCase( ) :- This method is used to compare two strings without case sensitive.
import [Link];
class Six
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
String str1 = new String("Rama");
String str2 = new String("Rama");
String str3 = new String("RAMA");
if([Link](str2))
{
[Link]("String1 and String2 are equal Strings");
}
else
{
[Link]("String1 and String2 are not equal Strings");
}
if([Link](str3))
{
[Link]("String1 and String3 are equal Strings");
}
else
{
[Link]("String1 and String3 are not equal Strings");
}
if([Link](str3))
{
[Link]("String1 and String3 are equal Strings");
}
else
{
[Link]("String1 and String3 are not equal Strings");
}
}
}
compareTo( ) :- This method is used to compare two strings. It returns the following values.
compareToIgnoreCase( ) :- This method is used to compare two strings without case sensitive.
import [Link];
import [Link];
class Six
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
Scanner sc = new Scanner([Link]);
String str1;
String str2;
int res;
[Link]("Enter Two Strings");
str1 = [Link]( );
str2 = [Link]( );
res = [Link](str2);
[Link]("Result : " + res);
if(res == 0)
{
[Link]("Both are equal Strings");
}
else
if(res > 0)
{
[Link]("First String is Big");
}
else
{
[Link]("Second String is Big");
}
}
}
import [Link];
class Six
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
String str1 = "Raja Ram Mohan Roy";
String str2 = "Seeta Rama Raju";
String str3 = "Seeta RAMA Raju";
if([Link](5,str2,6,3))
// regionMatches(first string starting index, second string, second // string starting index, number of
// characters to be compared);
{
[Link]("Both are equal Strings");
}
else
{
[Link]("Both are not equal Strings");
}
if([Link](5,str3,6,3))
{
[Link]("Both are equal Strings");
}
else
{
[Link]("Both are not equal Strings");
}
if([Link](true,5,str3,6,3))
// regionMatches(true,first string starting index, second string, second string starting index, number
// of characters to be compared); true :- Without case sensitive.
{
[Link]("Both are equal Strings");
}
else
{
[Link]("Both are not equal Strings");
}
}
}
startsWith( ) :- This method is used to check a string starts with particular string or not.
import [Link];
class Six
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
String str = "Ramesh";
if([Link]("Ram"))
{
[Link]("Yes");
}
else
{
[Link]("No");
}
}
}
endsWith( ) :- This method is used to check a string ends with particular string or not.
import [Link];
class Six
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
String str = "Ramesh";
if([Link]("sh"))
{
[Link]("Yes");
}
else
{
[Link]("No");
}
}
}
Searching Strings
indexOf( ) :- This method is used to find first occurrence of a sub string in a string. If the sub string is not
found then it returns -1. By default it starts searching from zero position. We can specify the starting
position if we need.
import [Link];
class Six
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
String str = "This is a book";
int p;
p = [Link]("is");
if(p == -1)
{
[Link]("Sub String Not Found");
}
else
{
[Link]("Position : " + (p + 1));
}
p = [Link]("was");
if(p == -1)
{
[Link]("Sub String Not Found");
}
else
{
[Link]("Position : " + (p + 1));
}
p = [Link]("is",3);
if(p == -1)
{
[Link]("Sub String Not Found");
}
else
{
[Link]("Position : " + (p + 1));
}
}
}
lastIndexOf( ) :- This method is used to find last occurrence of a sub string in a string. If the sub string is
not found then it returns -1. By default it continues searching upto end of the string. . We can specify
the last position to be search, if we need.
import [Link];
class Six
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
String str = "This is a book";
int p;
p = [Link]("is");
if(p == -1)
{
[Link]("Sub String Not Found");
}
else
{
[Link]("Position : " + (p + 1));
}
p = [Link]("was");
if(p == -1)
{
[Link]("Sub String Not Found");
}
else
{
[Link]("Position : " + (p + 1));
}
p = [Link]("is",3);
if(p == -1)
{
[Link]("Sub String Not Found");
}
else
{
[Link]("Position : " + (p + 1));
}
}
}
Converting Strings
import [Link];
class Six
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
String str = "RAMA";
[Link]("String : " + str);
[Link]("Converted String : " + [Link]( ));
}
}
import [Link];
class Six
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
String str = "rama";
[Link]("String : " + str);
[Link]("Converted String : " + [Link]( ));
}
}
Modifying Strings
substring( ) :- This method is used to get sub string from main string.
import [Link];
class Six
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
String str = "Raja Ram Mohan Roy";
[Link]("String : " + str);
[Link]("Sub String : " + [Link](5,8));
[Link]("Sub String : " + [Link](5));
}
}
replace( ) :- This method is used to replace a character / sub string with another character / sub string.
import [Link];
class Six
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
String str1 = "Raja Ram Mohan Roy Siva Ram Krishna";
String str2,str3;
str2 = [Link]('a','*');
str3 = [Link]("Ram","Tata");
[Link]("String : " + str1);
[Link]("Replaced String : " + str2);
[Link]("Replaced String : " + str3);
}
}
trim( ) :- This method is used to remove all leading (before) and trailing (after) spaces .
import [Link];
class Six
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
String str1 = " Raja Ram ";
String str2;
str2 = [Link]( );
[Link]("String : " + str1);
[Link]("Trimmed String : " + str2);
}
}
split( ) :- This method is used to divide main string into some sub strings.
import [Link];
class Six
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
String str1 = "Raja Ram Mohan Roy Siva Rama Krishna";
String str2[ ] = [Link](" ");
[Link]("String : " + str1);
[Link]("Splitted Strings");
for(String i : str2)
{
[Link](i);
}
String str3[] = [Link](" ",5);
[Link]("Splitted Strings");
for(String i : str3)
{
[Link](i);
}
}
}
Nesting of methods
import [Link];
class Six
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
String str1 = " Raja Ram ";
int n;
n = [Link]( );
[Link]("String Length : " + n);
n = [Link]( ).length( );
[Link]("String Length : " + n);
}
}
import [Link];
class Six
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
String str1 = "Raja ";
String str2 = "Ram ";
String str3 = "Mohan ";
String str4 = "Roy";
String str5;
str5 = [Link](str2).concat(str3).concat(str4);
[Link]("String : " + str5);
}
}
import [Link];
class Six
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
String str1 = "RAJA RAM MOHAN ROY";
[Link]("Sub String : " + [Link](5,8).toLowerCase( ));
}
}
Types of objects
1) Immutable objects
2) Mutable objects
Fixed strings :- String class objects are immutable objects / fixed strings. These objects size can't be
increased / decreased and we can't make any modifications in string objects.
import [Link];
class Six
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
String str1 = "Rama";
String str2;
[Link]("String 1 : " + str1);
str2 = [Link]( );
[Link]("String 2 : " + str2);
[Link]("String 1 : " + str1);
[Link]("String 1 : " + [Link]( ));
[Link]("String 1 : " + str1);
}
}
Dynamic strings :- StringBuffer class objects are mutable objects / dynamic strings. These objects size
can be increased / decreased and we can make any modifications in StringBuffer objects. By default
StringBuffer object has 16 bytes extra space to perform modifications. StringBuffer class is available in
[Link] package.
capacity( ) :- this method is used to find maximum number of characters to be stored by a StringBuffer
object.
import [Link];
class Six
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
StringBuffer str1 = new StringBuffer( );
StringBuffer str2 = new StringBuffer(10);
StringBuffer str3 = new StringBuffer("Rama");
[Link]("String 1 : " + str1);
[Link]("String 1 Capacity : " + [Link]( ));
[Link]("String 2 : " + str2);
[Link]("String 2 Capacity : " + [Link]( ));
[Link]("String 3 : " + str3);
[Link]("String 3 Capacity : " + [Link]( ));
}
}
length( ) :- This method is used to find length of StringBuffer object. Length means how many characters
in a StringBuffer object.
import [Link];
class Six
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
StringBuffer str = new StringBuffer("Rama");
int n;
n = [Link]( );
[Link]("String Length : " + n);
}
}
We can't assign contents to StringBuffer class. But we can append contents to StringBuffer class.
append( ) :- This method is used to add contents at end to the existing object.
import [Link];
class Six
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
StringBuffer str1 = new StringBuffer( );
str1 = "Rama"; (error)
[Link]("Rama");
[Link]("String 1 : " + str1);
[Link]("String 1 Capacity : " + [Link]( ));
}
}
insert( ) :- This method is used to add contents at specified position to the existing object.
import [Link];
class Six
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
StringBuffer str1 = new StringBuffer("Rama is Boy");
[Link]("String 1 : " + str1);
[Link](8,"Good ");
[Link]("String 1 : " + str1);
}
}
import [Link];
class Six
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
StringBuffer str = new StringBuffer("Ramesh");
[Link]("String : " + str);
[Link](2,'j');
[Link]("String : " + str);
}
}
replace( ) :- This method is used to replace a character / sub string with another character / sub string.
import [Link];
class Six
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
StringBuffer str = new StringBuffer("Siva Rama Krishna");
[Link]("String : " + str);
[Link](5,9,"Radha");
[Link]("String : " + str);
}
}
delete( ) :- This method is used to delete a sub string from main string.
import [Link];
class Six
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
StringBuffer str = new StringBuffer("Siva Rama Krishna");
[Link]("String : " + str);
[Link](5,10);
[Link]("String : " + str);
}
}
import [Link];
class Six
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
StringBuffer str = new StringBuffer("Rama");
[Link]("String : " + str);
[Link]( );
[Link]("String : " + str);
}
}
Note :- all methods in the character class are static methods. Character class is available in [Link]
package.
IsLetterOrDigit( ) :- this method is used to check whether a character is alphabet / digit or not.
import [Link];
import [Link];
class Six
{
public static void main(String args[]) throws IOException
{
PrintStream ps = new PrintStream([Link]);
char ch;
[Link]("Enter Character");
ch = (char) [Link]( );
if([Link](ch))
{
[Link]("It is Alphabet / Digit");
}
else
{
[Link]("It is Not Alphabet / Digit");
}
}
}
import [Link];
import [Link];
class Six
{
public static void main(String args[]) throws IOException
{
PrintStream ps = new PrintStream([Link]);
char ch;
[Link]("Enter Character");
ch = (char) [Link]( );
if([Link](ch))
{
[Link]("It is Alphabet");
}
else
{
[Link]("It is Not Alphabet");
}
}
}
import [Link];
import [Link];
class Six
{
public static void main(String args[]) throws IOException
{
PrintStream ps = new PrintStream([Link]);
char ch;
[Link]("Enter Character");
ch = (char) [Link]( );
if([Link](ch))
{
[Link]("It is Digit");
}
else
{
[Link]("It is Not Digit");
}
}
}
import [Link];
import [Link];
class Six
{
public static void main(String args[]) throws IOException
{
PrintStream ps = new PrintStream([Link]);
char ch;
[Link]("Enter Character");
ch = (char) [Link]( );
if([Link](ch))
{
[Link]("It is Space");
}
else
{
[Link]("It is Not Space");
}
}
}
isWhitespace( ) :- This method is used to check whether a character is tab / space / enter or not.
import [Link];
import [Link];
class Six
{
public static void main(String args[]) throws IOException
{
PrintStream ps = new PrintStream([Link]);
char ch;
[Link]("Enter Character");
ch = (char) [Link]( );
if([Link](ch))
{
[Link]("It is Tab / Space / Enter");
}
else
{
[Link]("It is Not Tab / Space / Enter");
}
}
}
isLowerCase( ) :- This method is used to check whether an alphabet is in lower case or not.
import [Link];
import [Link];
class Six
{
public static void main(String args[]) throws IOException
{
PrintStream ps = new PrintStream([Link]);
char ch;
[Link]("Enter Alphabet");
ch = (char) [Link]( );
if([Link](ch))
{
[Link]("It is Lower Case Alphabet");
}
else
{
[Link]("It is Not Lower Case Alphabet");
}
}
}
isUpperCase( ) :- This method is used to check whether an alphabet is in upper case or not.
import [Link];
import [Link];
class Six
{
public static void main(String args[]) throws IOException
{
PrintStream ps = new PrintStream([Link]);
char ch;
[Link]("Enter Alphabet");
ch = (char) [Link]( );
if([Link](ch))
{
[Link]("It is Upper Case Alphabet");
}
else
{
[Link]("It is Not Upper Case Alphabet");
}
}
}
toLowerCase( ) :- This method is used to convert a character into lower case.
import [Link];
import [Link];
class Six
{
public static void main(String args[]) throws IOException
{
PrintStream ps = new PrintStream([Link]);
char ch;
[Link]("Enter Upper Case Alphabet");
ch = (char) [Link]( );
[Link]("Entered Alphabet : " + ch);
[Link]("Converted Alphabet : " + [Link](ch));
}
}
import [Link];
import [Link];
class Six
{
public static void main(String args[]) throws IOException
{
PrintStream ps = new PrintStream([Link]);
char ch;
[Link]("Enter Lower Case Alphabet");
ch = (char) [Link]( );
[Link]("Entered Alphabet : " + ch);
[Link]("Converted Alphabet : " + [Link](ch));
}
}
Note :- All methods in the math class are static methods. Almost all methods in math class take double
type parameters. Math class is available in [Link] package.
import [Link];
import [Link];
class Six
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
Scanner sc = new Scanner([Link]);
double n,s;
[Link]("Enter Number");
n = [Link]( );
s = [Link](n);
[Link]("Square Root : " + s);
}
}
import [Link];
import [Link];
class Six
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
Scanner sc = new Scanner([Link]);
double b,p,res;
[Link]("Enter Base, Power");
b = [Link]( );
p = [Link]( );
res = [Link](b,p);
[Link]("Result : " + res);
}
}
All trigonometry methods takes arguments as radians. So, we have to convert radians into degrees.
import [Link];
import [Link];
class Six
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
Scanner sc = new Scanner([Link]);
double d,r,res;
[Link]("Enter Degrees");
r = [Link]( );
d = r * [Link] / 180;
res = [Link](d);
// res = 1 / [Link](d);
// res = [Link](d);
// res = 1 / [Link](d);
// res = [Link](d);
// res = 1 / [Link](d);
[Link]("Result : " + res);
}
}
import [Link];
class Six
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
double n,res;
n = 12.3;
res = [Link](n);
[Link]("Result : " + res);
n = 12.9;
res = [Link](n);
[Link]("Result : " + res);
n = 12.7;
res = [Link](n);
[Link]("Result : " + res);
n = 12.3;
res = [Link](n);
[Link]("Result : " + res);
n = 12.5;
res = [Link](n);
[Link]("Result : " + res);
}
}
round( ) :- This method is used to store a float value into a integer variable with data loss.
import [Link];
class Six
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
float a = 12.25F;
int b;
b = [Link](a);
[Link]("B Value : " + b);
}
}
abs( ) :- This method is used to find absolute value (always positive value / a value without sign) of a
number.
import [Link];
class Six
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
double n,res;
n = 12;
res = [Link](n);
[Link]("Result : " + res);
n = -12;
res = [Link](n);
[Link]("Result : " + res);
}
}
import [Link];
import [Link];
class Six
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
Scanner sc = new Scanner([Link]);
double n,s;
[Link]("Enter Number");
n = [Link]( );
s = [Link]([Link](n));
[Link]("Square Root : " + s);
}
}
import [Link];
import [Link];
class Six
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
Scanner sc = new Scanner([Link]);
double a,b,res;
[Link]("Enter Two Numbers");
a = [Link]( );
b = [Link]( );
res = [Link](a,b);
[Link]("Maximum Number : " + res);
res = [Link](a,b);
[Link]("Minimum Number : " + res);
}
}
random( ) :- This method is used to generate random numbers between 0 and specified number.
sleep( ) :- This method is used to stay processing at specified time. this is the static method in thread
class, which is available in [Link] package.
import [Link];
class Six
{
public static void main(String args[]) throws InterruptedException
{
PrintStream ps = new PrintStream([Link]);
double n;
int r;
while(true)
{
n = [Link]( ) * 10 ;
r = (int) n;
[Link](r + "\t");
if(r == 0)
{
break;
}
[Link](3000); // 3000 : 3 thousand milli seconds, it means three seconds
}
}
}
Formatting Numbers
Factory Methods
Some times objects to the classes may not be created by JVM. So we unable to use new operator. For
some classes in java, we can't create an object to that classes by using new operator. For example we
can't create object to system class. Because system class depends on operating system internally. In this
situations we can create objects with factory methods.
Factory method :- A factory method is a method that returns an object of class to which it belongs. All
factory methods are static methods.
NumberFormat class is used to format numbers. NumberFormat class is available in [Link] package.
NumberFormat class is an abstract class. It means we can't create object from it. Only we can create
reference. getInstance( ) is the factory method of NumberFormat class.
import [Link];
import [Link];
import [Link];
class Six
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
Scanner sc = new Scanner([Link]);
NumberFormat nf = [Link]( );
String str;
int rds;
double area;
[Link]("Enter Radius");
rds = [Link]( );
area = [Link] * rds * rds;
[Link](6);
[Link](2);
str = [Link](area);
[Link]("Area of Circle : " + area);
[Link]("Area of Circle : " + str);
}
}
import [Link];
import [Link];
class Six
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
Scanner sc = new Scanner([Link]);
int rds;
double area;
[Link]("Enter Radius");
rds = [Link]( );
area = [Link] * rds * rds;
[Link]("Area of Circle : %.2f",area);
}
}
Java provides several classes to handle dates. The most commonly used class is date of [Link] package.
This class is used to get current system date and time.
import [Link];
import [Link];
class Six
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
Date d = new Date( );
[Link]("Current Date : " + d);
}
}
Output
Formatting Dates
DateFormat class is used to format date and time. DateFormat class is available in [Link] package.
DateFormat class is an abstract class. It means we can't create object from it. Only we can create
reference. DateFormat class contains the following factory methods.
DateFormat class contains the following date and time format constants.
import [Link];
import [Link].*;
import [Link];
class Six
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
String str;
Date d = new Date( );
[Link]("Default Format : " + d);
DateFormat df = [Link]([Link],[Link]);
// (SHORT : Recommended)
str = [Link](d);
[Link]("Short Format : " + str);
df = [Link]([Link],[Link]);
str = [Link](d);
[Link]("Medium Format : " + str);
df = [Link]([Link],[Link]);
str = [Link](d);
[Link]("Long Format : " + str);
df = [Link]([Link],[Link]);
str = [Link](d);
[Link]("Full Format : " + str);
}
}
Output
Default Format : Tue Apr 20 [Link] IST 2010
Short Format : 20/04/10
Medium Format : 20-Apr-2010
Long Format : 20 April 2010
Full Format : 20 April 2010
import [Link];
import [Link].*;
import [Link];
class Six
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
String str;
Date d = new Date( );
[Link]("Default Format : " + d);
DateFormat df = [Link]([Link],[Link]);
str = [Link](d);
[Link]("Short Format : " + str);
df = [Link]([Link],[Link]);
(MEDIUM : recommended)
str = [Link](d);
[Link]("Medium Format : " + str);
df = [Link]([Link],[Link]);
str = [Link](d);
[Link]("Long Format : " + str);
df = [Link]([Link],[Link]);
str = [Link](d);
[Link]("Full Format : " + str);
}
}
Output
Default Format : Tue Apr 20 [Link] IST 2010
Short Format : 09:39
Medium Format : [Link]
Long Format : [Link] IST
Full Format : [Link] o'clock IST
import [Link];
import [Link].*;
import [Link];
class Six
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
String str;
Date d = new Date( );
[Link]("Default Format : " + d);
DateFormat df = [Link]([Link],[Link],[Link]);
// FIRST ONE DATE FORMAT CONSTANT, SECOND TIME FORMAT CONSTANT
str = [Link](d);
[Link]("Short Format : " + str);
df = [Link]([Link],[Link],[Link]);
str = [Link](d);
[Link]("Medium Format : " + str);
df = [Link]([Link],[Link],[Link]);
str = [Link](d);
[Link]("Long Format : " + str);
df = [Link]([Link],[Link],[Link]);
str = [Link](d);
[Link]("Full Format : " + str);
}
}
Output
Default Format : Tue Apr 20 [Link] IST 2010
Short Format : 20/04/10 09:50
Medium Format : 20-Apr-2010 [Link]
Long Format : 20 April 2010 [Link] IST
Full Format : 20 April 2010 [Link] o'clock IST
import [Link];
import [Link].*;
import [Link];
class Six
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
String str;
Date d = new Date( );
[Link]("Default Format : " + d);
DateFormat df = [Link]([Link],[Link]);
str = [Link](d);
[Link]("UK Date Format : " + str);
df = [Link]([Link],[Link]);
str = [Link](d);
[Link]("US Date Format : " + str);
df = [Link]([Link],[Link]);
str = [Link](d);
[Link]("Japan Date Format : " + str);
}
}
Output
Default Format : Tue Apr 20 [Link] IST 2010
UK Date Format : 20/04/10
US Date Format : 4/20/10
Japan Date Format : 10/04/20
This class is used to format dates. It is the most commonly used date format class. This class is available
in [Link] package.
import [Link];
import [Link];
import [Link];
class Six
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
Date d = new Date( );
String str;
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
// MM = MONTH, mm = MINUTE
str = [Link](d);
[Link]("Date in Indian Format : " + str);
sdf = new SimpleDateFormat("MM-dd-yyyy");
str = [Link](d);
[Link]("Date in American Format : " + str);
sdf = new SimpleDateFormat("[Link]");
str = [Link](d);
[Link]("Date in Japan Format : " + str);
sdf = new SimpleDateFormat("hh:mm:ss");
// hh : 12 HOURS FORMAT, HH : 24 HOURS FORMAT
str = [Link](d);
[Link]("Current Time in 12 Hours Format : " + str);
sdf = new SimpleDateFormat("HH:mm:ss");
str = [Link](d);
[Link]("Current Time in 24 Hours Format : " + str);
}
}
dd, MM, yyyy, hh, HH, mm, ss are called date and time format codes. date and time format codes has
case sensitive.
Calendar Class
Calendar class is used to access date and time parts individually. Calendar class is available in [Link]
package. Calendar class is an abstract class. It means we can't create an object from it. Only we can
create reference. getInstance( ) is the factory method of calendar class. This class provides get( ) and
set( ) methods to access and modify date and time.
Calendar class provides the following constants to get and set individual parts of date and time. All
constants returns integer.
import [Link];
import [Link];
class Six
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
Calendar cobj = [Link]( );
int res;
[Link]("Current Date : " + cobj);
res = [Link]([Link]);
[Link]("Day : " + res);
res = [Link](Calendar.DAY_OF_WEEK);
[Link]("Day of Week : " + res);
res = [Link](Calendar.DAY_OF_WEEK_IN_MONTH);
[Link]("Day of Week in Month : " + res);
res = [Link](Calendar.DAY_OF_MONTH);
[Link]("Day of Month : " + res);
res = [Link](Calendar.DAY_OF_YEAR);
[Link]("Day of Year : " + res);
res = [Link](Calendar.WEEK_OF_MONTH);
[Link]("Week of Month : " + res);
res = [Link](Calendar.WEEK_OF_YEAR);
[Link]("Week of Year : " + res);
res = [Link]([Link]);
// MONTH constant starts from zero.
[Link]("Month : " + (res+1) );
res = [Link]([Link]);
[Link]("Year : " + res );
res = [Link]([Link]);
[Link]("Hours (12 Hours Format) : " + res );
res = [Link](Calendar.HOUR_OF_DAY);
[Link]("Hours (24 Hours Format) : " + res );
res = [Link]([Link]);
[Link]("Minutes : " + res );
res = [Link]([Link]);
[Link]("Seconds : " + res );
res = [Link]([Link]);
[Link]("Milli Seconds : " + res );
res = [Link](Calendar.AM_PM); // returns zero for AM and one for PM
[Link]("AM / PM : " + res );
}
}
import [Link];
import [Link];
class Six
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
Calendar cobj = [Link]( );
int d,m,y;
d = [Link]([Link]);
m = [Link]([Link]);
y= [Link]([Link]);
[Link]("Date in Indian Format : " + d + "/" + (m + 1) + "/" + y);
[Link]("Date in American Format : " + (m + 1) + "-" + d + "-" + y);
[Link]("Date in Japan Format : " + y + "." + (m + 1) + "." + d);
}
}
import [Link];
import [Link];
class Six
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
Calendar cobj = [Link]( );
int d,mm,y,h,mi,s,r;
d = [Link]([Link]);
mm = [Link]([Link]);
y = [Link]([Link]);
h = [Link]([Link]);
mi = [Link]([Link]);
s = [Link]([Link]);
r = [Link](Calendar.AM_PM);
[Link]("Current Date & Time : " + d + "/" + (mm + 1) + "/" + y + "," + h + ":" + mi + ":" + s + " ");
if(r == 0)
{
[Link]("AM");
}
else
{
[Link]("PM");
}
[Link]([Link],6);
[Link]([Link],(8-1)); // for August
[Link]([Link],2002);
[Link](Calendar.HOUR_OF_DAY,20);
[Link]([Link],21);
[Link]([Link],22);
d = [Link]([Link]);
mm = [Link]([Link]);
y = [Link]([Link]);
h = [Link]([Link]);
mi = [Link]([Link]);
s = [Link]([Link]);
r = [Link](Calendar.AM_PM);
[Link]("Updated Date & Time : " + d + "/" + (mm + 1) + "/" + y + "," + h + ":" + mi + ":" + s + " ");
if(r == 0)
{
[Link]("AM");
}
else
{
[Link]("PM");
}
}
}
The method exec( ) of runtime class is used to execute operating system commands. Process class
reference variable stores the reference of the exec( ) method. getRuntime( ) is the factory method of
Runtime class. Runtime class is an abstract class. It means we can't create object from it. Only we can
create reference.
Command Program
notepad notepad
write wordpad
mspaint paint
calc calculator
import [Link];
import [Link];
import [Link];
class Six
{
public static void main(String args[]) throws IOException
{
PrintStream ps = new PrintStream([Link]);
Scanner sc = new Scanner([Link]);
Runtime r = [Link]( );
Process p;
String cmd;
[Link]("Enter Operating System Command");
cmd = [Link]( );
p = [Link](cmd);
}
}
Wrapper Classes
These classes are used to convert primitive data types into objects and objects into primitive data types.
Every primitive data type has related wrapper class.
Primitive Data type Wrapper Class
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean
import [Link];
class Six
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
int n = 10;
Integer ob = new Integer(n);
[Link]("N Value : " + n);
[Link]("Object Value : " + ob);
}
}
byte n = 10;
Byte ob = new Byte(n);
short n = 10;
Short ob = new Short(n);
long n = 10L;
Long ob = new Long(n);
float n = 10.25F;
Float ob = new Float(n);
double n = 10.25;
Double ob = new Double(n);
char n = 'k';
Character ob = new Character(n);
boolean n = true;
Boolean ob = new Boolean(n);
xxxValue( ) :- This method is used to access value from an object and stores into a primitive data type.
Here xxx means data type.
import [Link];
class Six
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
Integer ob = new Integer(10);
int n = [Link]( );
[Link]("Object Value : " + ob);
[Link]("N Value : " + n);
}
}
import [Link];
class Six
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
Integer iob = new Integer(10);
String sob = [Link]( );
[Link]("Integer Object Value : " + iob);
[Link]("String Object Value : " + sob);
}
}
valueOf( ) :- Every numeric class has a static method called valueOf( ). This method is used to convert
string type object into numeric object.
import [Link];
class Six
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
String sob = "10";
Integer iob = [Link](sob);
[Link]("String Object Value : " + sob);
[Link]("Integer Object Value : " + iob);
}
}
import [Link];
class Six
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
int n = 10;
String ob = [Link](n);
[Link]("N Value : " + n);
[Link]("String Object Value : " + ob);
}
}
byte n = 10;
String ob = [Link](n);
short n = 10;
String ob = [Link](n);
long n = 10L;
String ob = [Link](n);
float n = 10.25F;
String ob = [Link](n);
double n = 10.25;
String ob = [Link](n);
char n = 'K';
String ob = [Link](n);
boolean n = true;
String ob = [Link](n);
parseXxx( ) :- Every numeric class has a static method called parseXxx( ). this method is used to access
value from an string object and stores into a primitive numeric data type. here xxx means data type.
import [Link];
class Six
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
String ob = "10";
int n = [Link](ob);
[Link]("String Object Value : " + ob);
[Link]("N Value : " + n);
}
}
String ob = "10";
byte n = [Link](ob);
String ob = "10";
short n = [Link](ob);
String ob = "10";
long n = [Link](ob);
String ob = "10.25";
float n = [Link](ob);
String ob = "10.25";
double n = [Link](ob);
String ob = "true";
boolean n = [Link](ob);
Once we create the software, it is difficult to write again & again the solutions for the problem give by
client. This is main problem in procedural languages like C, C++. For example if software is employee pay
role only, client will come again and again that your software is not calculating p.f, bank reports etc. So
programmer has to write the solutions again and again for particular problem.
In procedural approach, concentration is what is the problem and how to solve the problem. It does not
study the behaviour of the entire system.
Procedural approach is not suitable for developing complex programs which has thousands of lines.
Because programmer may loose their control on the program.
In procedural language, programmer loose control on the program at a particular state when the
program size exceeds between ten thousand and lakhs lines of code. So procedural approach is not
suitable for creative bigger and complex softwares.
OOPS :- OOPS helpful to create very complex programs. OOPS reflect human life. C++ and java come
under OOPS. small talk, simula-67 are inspiration behind java development. But they are object based
languages, where as C++ and java are object oriented languages. C++ is not pure OOPS. It is called partial
OOPS. Because it does not support 100% features of OOPS. But java is pure OOPS. It supports 100%
features of OOPS. Another example for pure OOPS is small talk.
Inheritance :- It is the very powerful feature. By using inheritance we can implement number of
concepts in OOPS.
Features of OOPS
object / class :- OOPS developed from the root concept is called object. An object is something that is
existing in the real world. An object have properties and actions. For example if man is an object then
name, color, height, weight are called properties and walk, eat, sleep are called actions. In programming
languages, properties are called variables and actions are called methods.
A class is an abstract idea, not real. But an object is real. class does not exist physically, but object exist
physically. An object does not exist without a class, but a class can exist without an object. class is also a
data type. A class is a group name that specifies properties and actions of object. A class is a model /
blue print for creating objects. In java memory is allotted to objects not for classes. A class / an object
contains variables and methods.
Encapsulation :- Binding up of data and methods in the same memory. Class is an example for
encapsulation. Variables and methods are called members of class. The members of each class are
separated from the members of other classes. The main advantage of encapsulation is, data required to
methods is available in the same memory, so speeder execution is possible.
Abstraction :- Hiding unnecessary data from the user is called abstraction. Some data is not displayed to
the user. User has no light to see it. For example engine in the car is hidden. To provide abstraction, a
programmer uses keywords like private, protected, default, public etc.
Inheritance :- Producing new classes from an existing class is called inheritance. We can create new
classes from old existing class without rewriting the code. It means we are reusing the existing code. The
main advantage of inheritance is reusability.
Polymorphism :- If something exist in many forms. The ability to exist in different forms. Same method
performing different tasks based on situation is called polymorphism.
A class is a model to create the object. An object is an instance (variable) of class. Whatever we write in
the object will be there in the class.
Java is a complete OOPS. In OOPS we can't do anything without object. The whole OOPS concept is
implemented through object. Object is the vehicle to implement all the features of the OOPS.
class :- It is a collection of data members and methods. Once class is created we can create any number
of object from that class.
Creation of class
Syntax
class class_name
{
access_specifier data_type data_member_1;
access_specifier data_type data_member_2;
access_specifier data_type data_member_n;
access_specifier return_type method_name_1( )
{
body of the method 1;
}
access_specifier return_type method_name_2( )
{
body of the method 2;
}
access_specifier return_type method_name_n( )
{
body of the method n;
}
};
To create a class we need a keyword "class". Semicolon is required at the end of the class. If a java
program contains more than one class, then the name of the program as that class name, which
contains the main( ).
A sample class
class Student
{
int sno;
String sname;
double age;
};
After creation of class, the structure and format of an object is ready to use. But we can't do anything in
class. Everything is done in object.
(DRAW FIGURE)
Creation of object
Syntax
After creating an object, JVM will allot a unique identification number to that object and that number is
going to store in ob (as per above example). ob is a variable of student class. ob will point to object. The
identification number given to object is called hashcode. hashcode is not a memory address. JVM
internally used an hashcode generation algorithm to create hashcode. This algorithm takes the memory
address of object as input and shuffles that and finally it gives hashcode. It means memory address and
hashcode both are not equal.
Student( ) :- It is a special method called constructor, which is implicitly pass by java compiler and it's
name is equivalent to the class name. Constructor is used to initialize an object with specified values /
default values. Only class variables have default values.
byte 0
short 0
int 0
long 0
float 0.0
double 0.0
char ' ' (space)
boolean false
String / object null
(draw figure)
Syntax
object_name.data_member_name;
object_name.method_name( );
Ex :-
[Link] = 101;
[Link] = "Rama";
[Link] = 21.6;
class Student
{
int sno;
String sname;
double age;
};
class DemoOops1
{
public static void main(String args[])
{
Student ob = new Student( );
[Link]("Student Details");
[Link]("Student Number : " + [Link]);
[Link]("Student Name : " + [Link]);
[Link]("Student Age : " + [Link]);
}
}
As per OOPS rules, the above program not correct. Because non method of Student class (main( )
method, which is the method of DemoOops1 class) accessing members of Student class. This is quite
opposite to OOPS rules. The main problem of the above program is the variables of a class is accessing
outside the class. The data may be misuse / erase / modify. So data is misused. There is no security for
data. We can use data through the methods of the class only. So data is not misused.
class Student
{
int sno;
String sname;
double age;
void set( )
{
sno = 101;
sname = "Rama";
age = 12.6;
}
void show( )
{
[Link]("Student Number : " + sno);
[Link]("Student Name : " + sname);
[Link]("Student Age : " + age);
}
};
class DemoOops2
{
public static void main(String args[])
{
Student ob = new Student( );
[Link]( );
[Link]("Student Details");
[Link]( );
}
}
class Student
{
int sno;
String sname;
double age;
void set( )
{
sno = 101;
sname = "Rama";
age = 12.6;
}
void show( )
{
[Link]("Student Number : " + sno);
[Link]("Student Name : " + sname);
[Link]("Student Age : " + age);
}
};
class DemoOops3
{
public static void main(String args[])
{
Student ob = new Student( );
[Link]( );
[Link] = "King";
[Link]("Student Details");
[Link]( );
}
}
The above program is logically correct, but as per OOPS rules not correct. In the above program sname is
accessed by non method of Student class (main() method). We have no controlling on data. By default
data is available to all methods even non methods also. We can control data through access specifiers.
Access specifier :- It is a keyword that represents how to access the members of a class. Java provides
four types of access specifiers.
private :- If a member is declared as private, then the member is not available anywhere outside the
class. It can access only inside the class.
public :- If a member is declared as public, then the member is available anywhere outside the class.
protected :- This is similar to public. But some difference is there. This access specifier is discussed in
inheritance concept.
default :- It is the default access specifier. For example if we write int sno; then compiler places default
keyword before to int sno; and changes the statement into default int sno; this is similar to public. But
some difference is there. This keyword is discussed in packages concept.
Generally the variables of a class are declared as private and the methods of a class are declared as
public.
class Student
{
private int sno;
private String sname;
private double age;
void set( )
{
sno = 101;
sname = "Rama";
age = 12.6;
}
void show( )
{
[Link]("Student Number : " + sno);
[Link]("Student Name : " + sname);
[Link]("Student Age : " + age);
}
};
class DemoOops4
{
public static void main(String args[])
{
Student ob = new Student( );
[Link]( );
[Link] = "King"; (error)
/* Because private members are not accessed outside the class. So there is high security for data in
OOPS concept through private access specifier
*/
[Link]("Student Details");
[Link]( );
}
}
Finally a class is a collection of variables (data members) and functions (methods). Only those methods
which are written inside the class, can access the data members of the class.
Once a class is defined we can create any number of objects from that class.
class Student
{
private int sno;
private String sname;
private double age;
void set( )
{
sno = 101;
sname = "Rama";
age = 12.6;
}
void show( )
{
[Link]("Student Number : " + sno);
[Link]("Student Name : " + sname);
[Link]("Student Age : " + age);
}
};
class DemoOops5
{
public static void main(String args[])
{
Student ob1 = new Student( );
[Link]( );
[Link]("First Student Details");
[Link]( );
Student ob2 = new Student( );
[Link]( );
[Link]("Second Student Details");
[Link]( );
Student ob3 = new Student( );
[Link]( );
[Link]("Third Student Details");
[Link]( );
}
}
The above program is logically not correct, because all objects have same data. The solution for above
problem is parameterized methods. A parameterized method is a method which have some parameters.
Parameterized Methods
class Student
{
private int sno;
private String sname;
private double age;
void set(int vsno,String vsname,double vage)
{
sno = vsno;
sname = vsname;
age = vage;
}
void show( )
{
[Link]("Student Number : " + sno);
[Link]("Student Name : " + sname);
[Link]("Student Age : " + age);
}
};
class DemoOops6
{
public static void main(String args[])
{
Student ob1 = new Student( );
[Link](101,"Rama",12.6);
[Link]("First Student Details");
[Link]( );
Student ob2 = new Student( );
[Link](102,"King",15.3);
[Link]("Second Student Details");
[Link]( );
Student ob3 = new Student( );
[Link](103,"Tata",21.6);
[Link]("Third Student Details");
[Link]( );
}
}
Square of a number
class Square
{
int n;
int s;
void set(int x)
{
n = x;
}
void process( )
{
s = n * n;
}
void show( )
{
[Link]("Square : " + s);
}
};
class SquareDemo
{
public static void main(String args[])
{
Square ob = new Square( );
[Link](6);
[Link]( );
[Link]( );
}
}
class Sum
{
int a;
int b;
int c;
void set(int x, int y)
{
a = x;
b = y;
}
void process( )
{
c = a + b;
}
void show( )
{
[Link]("Sum : " + c);
}
};
class SumDemo
{
public static void main(String args[])
{
Sum ob = new Sum( );
[Link](6,3);
[Link]( );
[Link]( );
}
}
class Square
{
int n;
int s;
void set(int x)
{
n = x;
}
void process( )
{
s = n * n;
}
void show( )
{
[Link]("Square : " + s);
}
};
class SquareDemo1
{
public static void main(String args[])
{
Square ob = new Square( );
int k;
k = [Link](args[0]);
[Link](k);
[Link]( );
[Link]( );
}
}
// java SquareDemo1 6
class Sum
{
int a;
int b;
int c;
void set(int x, int y)
{
a = x;
b = y;
}
void process( )
{
c = a + b;
}
void show( )
{
[Link]("Sum : " + c);
}
};
class SumDemo1
{
public static void main(String args[])
{
Sum ob = new Sum( );
int n1,n2;
n1 = [Link](args[0]);
n2 = [Link](args[1]);
[Link](n1,n2);
[Link]( );
[Link]( );
}
}
// java SumDemo1 6 3
import [Link];
class Student
{
PrintStream ps = new PrintStream([Link]);
int sno;
String sname;
int em;
int tm;
int hm;
int mm;
int scm;
int som;
int tot;
double avg;
void set(int vsno,String vsname,int vem, int vtm, int vhm, int vmm, int vscm, int vsom)
{
sno = vsno;
sname = vsname;
em = vem;
tm = vtm;
hm = vhm;
mm = vmm;
scm = vscm;
som = vsom;
}
void process( )
{
tot = em + tm + hm + mm + scm + som;
avg = tot / 6.0;
}
void show( )
{
[Link]("Student Number : " + sno);
[Link]("Student Name : " + sname);
[Link]("Total Marks : " + tot);
[Link]("Average Marks : %.2f\n",avg);
}
};
class StdResDemo
{
public static void main(String args[])
{
Student ob = new Student( );
int xsno;
String xsname;
int xem;
int xtm;
int xhm;
int xmm;
int xscm;
int xsom;
xsno = [Link](args[0]);
xsname = args[1];
xem = [Link](args[2]);
xtm = [Link](args[3]);
xhm = [Link](args[4]);
xmm = [Link](args[5]);
xscm = [Link](args[6]);
xsom = [Link](args[7]);
[Link](xsno,xsname,xem,xtm,xhm,xmm,xscm,xsom);
[Link]( );
[Link]( );
}
}
Runtime Input
import [Link];
import [Link];
class Square
{
PrintStream ps = new PrintStream([Link]);
Scanner sc = new Scanner([Link]);
int n;
int s;
void input( )
{
[Link]("Enter Number");
n = [Link]( );
}
void process( )
{
s = n * n;
}
void show( )
{
[Link]("Square : " + s);
}
};
class SquareDemo2
{
public static void main(String args[])
{
Square ob = new Square( );
[Link]( );
[Link]( );
[Link]( );
}
}
import [Link];
import [Link];
class Sum
{
PrintStream ps = new PrintStream([Link]);
Scanner sc = new Scanner([Link]);
int a;
int b;
int c;
void input( )
{
[Link]("Enter Two Numbers");
a = [Link]( );
b = [Link]( );
}
void process( )
{
c = a + b;
}
void show( )
{
[Link]("Sum : " + c);
}
};
class SumDemo2
{
public static void main(String args[])
{
Sum ob = new Sum( );
[Link]( );
[Link]( );
[Link]( );
}
}
Sales Amount
import [Link];
import [Link];
class Item
{
PrintStream ps = new PrintStream([Link]);
Scanner sc = new Scanner([Link]);
int icode;
String iname;
int qty;
double rate;
int discPer;
double amt;
double discAmt;
double bill;
void input( )
{
[Link]("Enter Item Code, Name");
icode = [Link]( );
iname = [Link]( );
[Link]("Enter Quantity, Rate, Discount (%)");
qty = [Link]( );
rate = [Link]( );
discPer = [Link]( );
}
void process( )
{
amt = qty * rate;
discAmt = amt * discPer / 100;
bill = amt - discAmt;
}
void show( )
{
[Link]("Item Code : " + icode);
[Link]("Item Name : " + iname);
[Link]("Quantity : " + qty);
[Link]("Rate : %.2f\n",rate);
[Link]("Discount (%) : " + discPer);
[Link]("Amount : %.2f\n",amt);
[Link]("Discount : %.2f\n",discAmt);
[Link]("Bill : %.2f\n",bill);
}
};
class ItemDemo
{
public static void main(String args[])
{
Item ob = new Item( );
[Link]( );
[Link]( );
[Link]( );
}
}
Current Bill
import [Link];
import [Link];
class Current
{
PrintStream ps = new PrintStream([Link]);
Scanner sc = new Scanner([Link]);
int srvcNo;
String cname;
int lmr;
int pmr;
double ur;
int nuc;
double bill;
void input( )
{
[Link]("Enter Service Number, Consumer Name");
srvcNo = [Link]( );
cname = [Link]( );
[Link]("Enter Last Month Reading, Present Month Reading");
lmr = [Link]( );
pmr = [Link]( );
[Link]("Enter Unit Rate");
ur = [Link]( );
}
void process( )
{
nuc = pmr - lmr;
bill = nuc * ur;
}
void show( )
{
[Link]("Service Number : " + srvcNo);
[Link]("Consumer Name : " + cname);
[Link]("Last Month Reading : " + lmr);
[Link]("Present Month Reading : " + pmr);
[Link]("Unit Rate : %.2f\n",ur);
[Link]("Number of Units Consumed : " + nuc);
[Link]("Bill : %.2f\n",bill);
}
};
class CurrentDemo
{
public static void main(String args[])
{
Current ob = new Current( );
[Link]( );
[Link]( );
[Link]( );
}
}
import [Link];
import [Link];
class EmpPayRoll
{
PrintStream ps = new PrintStream([Link]);
Scanner sc = new Scanner([Link]);
int empNo;
String empName;
int bsal;
double hra;
double da;
double ta;
double it;
double pf;
double alw;
double gsal;
double ded;
double nsal;
void input( )
{
[Link]("Enter Employee Number, Name, Basic Salary");
empNo = [Link]( );
empName = [Link]( );
bsal = [Link]( );
}
void process( )
{
hra = bsal * 0.25;
da = bsal * 0.3;
ta = bsal * 0.15;
it = bsal * 0.04;
pf = bsal * 0.08;
alw = hra + da + ta;
gsal = bsal + alw;
ded = it + pf;
nsal = gsal - ded;
}
void show( )
{
[Link]("Employee Number : " + empNo);
[Link]("Employee Name : " + empName);
[Link]("Basic Salary : " + bsal);
[Link]("Allowances : %.2f\n",alw);
[Link]("Gross Salary : %.2f\n",gsal);
[Link]("Deductions : %.2f\n",ded);
[Link]("Net Salary : %.2f\n",nsal);
}
};
class EmpPayRollDemo
{
public static void main(String args[])
{
EmpPayRoll ob = new EmpPayRoll( );
[Link]( );
[Link]( );
[Link]( );
}
}
import [Link];
import [Link];
class Big
{
PrintStream ps = new PrintStream([Link]);
Scanner sc = new Scanner([Link]);
int a;
int b;
int c;
void input( )
{
[Link]("Enter Two Numbers");
a = [Link]( );
b = [Link]( );
}
void process( )
{
if(a > b)
{
c = a;
}
else
{
c = b;
}
}
void show( )
{
[Link]("Big Number : " + c);
}
};
class BigDemo
{
public static void main(String args[])
{
Big ob = new Big( );
[Link]( );
[Link]( );
[Link]( );
}
}
Student Grade
import [Link];
import [Link];
class Student
{
PrintStream ps = new PrintStream([Link]);
Scanner sc = new Scanner([Link]);
int sno;
String sname;
int em;
int tm;
int hm;
int mm;
int scm;
int som;
int tot;
double avg;
String res;
void input( )
{
[Link]("Enter Student Number, Name");
sno = [Link]( );
sname = [Link]( );
[Link]("Enter English, Telugu, Hindi Marks");
em = [Link]( );
tm = [Link]( );
hm = [Link]( );
[Link]("Enter Maths, Science, Social Marks");
mm = [Link]( );
scm = [Link]( );
som = [Link]( );
}
void process( )
{
tot = em + tm + hm + mm + scm + som;
avg = tot / 6.0;
if(em >= 35 && tm >= 35 && hm >= 35 && mm >= 35 && scm >= 35 && som >= 35)
{
if(avg >= 80)
{
res = "Distinction";
}
else
if(avg >= 60)
{
res = "First Class";
}
else
if(avg >= 50)
{
res = "Second Class";
}
else
if(avg >= 40)
{
res = "Third Class";
}
else
{
res = "Ordinary Pass";
}
}
else
{
res = "Fail";
}
}
void show( )
{
[Link]("Student Number : " + sno);
[Link]("Student Name : " + sname);
[Link]("Total Marks : " + tot);
[Link]("Average Marks : %.2f\n",avg);
[Link]("Result : " + res);
}
};
class StdGrdDemo
{
public static void main(String args[])
{
Student ob = new Student( );
[Link]( );
[Link]( );
[Link]( );
}
}
Returnable Methods
import [Link];
import [Link];
class Square
{
PrintStream ps = new PrintStream([Link]);
Scanner sc = new Scanner([Link]);
int n;
int s;
void input( )
{
[Link]("Enter Number");
n = [Link]( );
}
int process( )
{
s = n * n;
return s;
}
};
class SquareDemo3
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
Square ob = new Square( );
int k;
[Link]( );
k = [Link]( );
[Link]("Square : " + k);
[Link]("Square : " + [Link]( ) );
}
}
import [Link];
import [Link];
class Sum
{
PrintStream ps = new PrintStream([Link]);
Scanner sc = new Scanner([Link]);
int a;
int b;
int c;
void input( )
{
[Link]("Enter Two Numbers");
a = [Link]( );
b = [Link]( );
}
int process( )
{
c = a + b;
return c;
}
};
class SumDemo3
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
Sum ob = new Sum( );
int k;
[Link]( );
k = [Link]( );
[Link]("Sum : " + k);
}
}
import [Link];
import [Link];
class Big
{
PrintStream ps = new PrintStream([Link]);
Scanner sc = new Scanner([Link]);
int a;
int b;
void input( )
{
[Link]("Enter Two Numbers");
a = [Link]( );
b = [Link]( );
}
int process( )
{
if(a > b)
{
return a;
}
else
{
return b;
}
}
};
class BigDemo1
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
Big ob = new Big( );
int k;
[Link]( );
k = [Link]( );
[Link]("Big Number : " + k);
}
}
import [Link];
import [Link];
class Circle
{
PrintStream ps = new PrintStream([Link]);
Scanner sc = new Scanner([Link]);
int rds;
double area;
void input( )
{
[Link]("Enter Radius");
rds = [Link]( );
}
double process( )
{
area = [Link] * rds * rds;
return area;
}
};
class AreaOfCircleDemo
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
Circle ob = new Circle( );
double k;
[Link]( );
k = [Link]( );
[Link]("Area of Circle : %.2f\n",k);
}
}
import [Link];
import [Link];
class Student
{
PrintStream ps = new PrintStream([Link]);
Scanner sc = new Scanner([Link]);
int sno;
String sname;
int em;
int tm;
int hm;
int mm;
int scm;
int som;
void input( )
{
[Link]("Enter Student Number, Name");
sno = [Link]( );
sname = [Link]( );
[Link]("Enter English, Telugu, Hindi Marks");
em = [Link]( );
tm = [Link]( );
hm = [Link]( );
[Link]("Enter Maths, Science, Social Marks");
mm = [Link]( );
scm = [Link]( );
som = [Link]( );
}
int calcTot( )
{
return (em + tm + hm + mm + scm + som);
}
double calcAvg( )
{
return ( (em + tm + hm + mm + scm + som) / 6.0);
}
boolean findRes( )
{
if(em >= 35 && tm >= 35 && hm >= 35 && mm >= 35 && scm >= 35 && som >= 35)
{
return true;
}
else
{
return false;
}
}
String findGrd(double vavg)
{
if(vavg >= 80)
{
return "Distinction";
}
else
if(vavg >= 60)
{
return "First Class";
}
else
if(vavg >= 50)
{
return "Second Class";
}
else
if(vavg >= 40)
{
return "Third Class";
}
else
{
return "Ordinary Pass";
}
}
void show( )
{
[Link]("Student Number : " + sno);
[Link]("Student Name : " + sname);
}
};
class StdGrdDemo1
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
Student ob = new Student( );
int tot;
double avg;
boolean res;
String grd;
[Link]( );
tot = [Link]( );
avg = [Link]( );
res = [Link]( );
[Link]( );
[Link]("Total Marks : " + tot);
[Link]("Average Marks : %.2f\n",avg);
if(res)
{
grd = [Link](avg);
[Link]("Grade : " + grd);
}
else
{
[Link]("Result : Fail");
}
}
}
A reference is a variable which stores object hashcode. A hashcode is nothing but memory location
which is pointed by an object. Unique id number given to every object by JVM. It is also called reference
number. Memory is actually allotted to object not to reference.
import [Link];
import [Link];
class Square
{
PrintStream ps = new PrintStream([Link]);
Scanner sc = new Scanner([Link]);
int n;
int s;
void input( )
{
[Link]("Enter Number");
n = [Link]( );
}
void process( )
{
s = n * n;
}
void show( )
{
[Link]("Square : " + s);
}
};
class SquareDemo4
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
Square ob = new Square( );
Square ref;
[Link]( );
[Link]( );
[Link]( );
ref = ob;
[Link]( );
[Link]("Object Points to : " + [Link]( ));
[Link]("Reference Points to : " + [Link]( ));
/*ref = null; (deleting link)
[Link]( );
*/
}
}
Primitive data types are automatically passed by value and object types are automatically passed by
reference.
import [Link];
class Sample
{
void change(int x)
{
x = 20;
}
};
class PassByValDemo
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
Sample ob = new Sample( );
int n = 10;
[Link]("Before Calling Function, N Value : " + n);
[Link](n);
[Link]("After Calling Function, N Value : " + n);
}
}
import [Link];
class Sample
{
void change(StringBuffer x)
{
[Link]( );
}
};
class PassByRefDemo
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
Sample ob = new Sample( );
StringBuffer str = new StringBuffer("Rama");
[Link]("Before Calling Function, String : " + str);
[Link](str);
[Link]("After Calling Function, String : " + str);
}
}
import [Link];
import [Link];
class Bank
{
PrintStream ps = new PrintStream([Link]);
Scanner sc = new Scanner([Link]);
int ano;
String ahName;
double bal;
void input( )
{
[Link]("Enter Account Number, Holder Name, Balance");
ano = [Link]( );
ahName = [Link]( );
bal = [Link]( );
}
void show( )
{
[Link]("Account Number : " + ano);
[Link]("Holder Number : " + ahName);
[Link]("Balance : " + bal);
}
};
class BankAcDemo
{
public static void main(String args[])
{
Bank ob = new Bank( );
[Link]( );
[Link]( );
}
}
import [Link];
import [Link];
class Bank
{
PrintStream ps = new PrintStream([Link]);
Scanner sc = new Scanner([Link]);
int ano;
String ahName;
double bal;
void input( )
{
[Link]("Enter Account Number, Holder Name, Balance");
ano = [Link]( );
ahName = [Link]( );
bal = [Link]( );
}
void transfer(Bank vob2,double vamt)
{
bal = bal - vamt;
[Link] = [Link] + vamt;
}
void show( )
{
[Link]("Account Number : " + ano);
[Link]("Holder Number : " + ahName);
[Link]("Balance : " + bal);
}
};
class MoneyTransferDemo
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
Scanner sc = new Scanner([Link]);
Bank ob1 = new Bank( );
[Link]( );
Bank ob2 = new Bank( );
[Link]( );
[Link]("Before Transferring, First Account Details");
[Link]( );
[Link]("Before Transferring, Second Account Details");
[Link]( );
double amt;
[Link]("Enter how much amount to be transferred");
amt = [Link]( );
[Link](ob2,amt);
[Link]("After Transferring, First Account Details");
[Link]( );
[Link]("After Transferring, Second Account Details");
[Link]( );
}
}
Returning Objects
import [Link];
class Employee
{
PrintStream ps = new PrintStream([Link]);
int empNo;
String empName;
double sal;
void set(int vempNo, String vempName, double vsal)
{
empNo = vempNo;
empName = vempName;
sal = vsal;
}
Employee incrSal(Employee vob)
{
[Link] = [Link] + [Link] * 0.1;
return vob;
}
void show( )
{
[Link]("Employee Number : " + empNo);
[Link]("Employee Name : " + empName);
[Link]("Employee Salary : " + sal);
}
};
class EmpSalIncrDemo
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
Employee ob1 = new Employee( );
Employee ob2 = new Employee( );
[Link](101,"Rama",2500);
[Link]("Before Incrementing, Employee Details");
[Link]( );
ob2 = [Link](ob1);
[Link]("After Incrementing, Employee Details");
[Link]( );
}
}
Object Arrays
import [Link];
import [Link];
class Student
{
PrintStream ps = new PrintStream([Link]);
Scanner sc = new Scanner([Link]);
int sno;
String sname;
int em;
int tm;
int hm;
int mm;
int scm;
int som;
int tot;
double avg;
String res;
void input( )
{
[Link]("Enter Student Number, Name");
sno = [Link]( );
sname = [Link]( );
[Link]("Enter English, Telugu, Hindi Marks");
em = [Link]( );
tm = [Link]( );
hm = [Link]( );
[Link]("Enter Maths, Science, Social Marks");
mm = [Link]( );
scm = [Link]( );
som = [Link]( );
}
void process( )
{
tot = em + tm + hm + mm + scm + som;
avg = tot / 6.0;
if(em >= 35 && tm >= 35 && hm >= 35 && mm >= 35 && scm >= 35 && som >= 35)
{
if(avg >= 80)
{
res = "Distinction";
}
else
if(avg >= 60)
{
res = "First Class";
}
else
if(avg >= 50)
{
res = "Second Class";
}
else
if(avg >= 40)
{
res = "Third Class";
}
else
{
res = "Ordinary Pass";
}
}
else
{
res = "Fail";
}
}
void show( )
{
[Link]("Student Number : " + sno);
[Link]("Student Name : " + sname);
[Link]("Total Marks : " + tot);
[Link]("Average Marks : %.2f\n",avg);
[Link]("Result : " + res);
}
};
class ObjArysDemo
{
public static void main(String args[])
{
Student ob[ ] = new Student[5];
int i;
for(i = 0; i < [Link]; i++)
{
ob[i] = new Student( );
}
for(i = 0; i < [Link]; i++)
{
ob[i].input( );
}
for(i = 0; i < [Link]; i++)
{
ob[i].process( );
}
for(i = 0; i < [Link]; i++)
{
ob[i].show( );
}
}
}
import [Link];
import [Link];
class Student
{
PrintStream ps = new PrintStream([Link]);
Scanner sc = new Scanner([Link]);
int sno;
String sname;
int em;
int tm;
int hm;
int mm;
int scm;
int som;
int tot;
double avg;
String res;
void input( )
{
[Link]("Enter Student Number, Name");
sno = [Link]( );
sname = [Link]( );
[Link]("Enter English, Telugu, Hindi Marks");
em = [Link]( );
tm = [Link]( );
hm = [Link]( );
[Link]("Enter Maths, Science, Social Marks");
mm = [Link]( );
scm = [Link]( );
som = [Link]( );
}
void process( )
{
tot = em + tm + hm + mm + scm + som;
avg = tot / 6.0;
if(em >= 35 && tm >= 35 && hm >= 35 && mm >= 35 && scm >= 35 && som >= 35)
{
if(avg >= 80)
{
res = "Distinction";
}
else
if(avg >= 60)
{
res = "First Class";
}
else
if(avg >= 50)
{
res = "Second Class";
}
else
if(avg >= 40)
{
res = "Third Class";
}
else
{
res = "Ordinary Pass";
}
}
else
{
res = "Fail";
}
}
void show( )
{
[Link]("Student Number : " + sno);
[Link]("Student Name : " + sname);
[Link]("Total Marks : " + tot);
[Link]("Average Marks : %.2f\n",avg);
[Link]("Result : " + res);
}
};
class ObjArysDemo1
{
public static void main(String args[])
{
Student ob[ ] = new Student[5];
for(int i = 0; i < [Link]; i++)
{
ob[i] = new Student( );
}
for(Student k : ob)
{
[Link]( );
[Link]( );
[Link]( );
}
}
}
import [Link];
import [Link];
class Bank
{
PrintStream ps = new PrintStream([Link]);
int ano;
String ahName;
double bal;
void set(int vano, String vahName, double vbal)
{
ano = vano;
ahName = vahName;
bal = vbal;
}
boolean checkBal(double vamt)
{
if(vamt <= (bal - 500))
{
return true;
}
else
{
return false;
}
}
void transfer(Bank vob,double vamt)
{
bal = bal - vamt;
[Link] = [Link] + vamt;
}
void show( )
{
[Link]("Account Number : " + ano);
[Link]("Holder Number : " + ahName);
[Link]("Balance : " + bal);
}
};
class MoneyTransferDemo1
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
Scanner sc = new Scanner([Link]);
Bank ob[ ] = new Bank[10];
int frmAno,toAno,frmIndex,toIndex;
boolean frmAnoFound,toAnoFound,balAvailable;
double amt;
for(int i = 0; i < [Link]; i++)
{
ob[i] = new Bank( );
}
ob[0].set(101,"Rama",5000);
ob[1].set(102,"King",3000);
ob[2].set(103,"Siva",9000);
ob[3].set(104,"Ford",2000);
ob[4].set(105,"Ward",10000);
ob[5].set(106,"Tata",4000);
ob[6].set(107,"Blake",6000);
ob[7].set(108,"Smith",1000);
ob[8].set(109,"Scott",8000);
ob[9].set(110,"Jones",7000);
[Link]("Enter From Account Number");
frmAno = [Link]( );
frmAnoFound = false;
frmIndex = 0;
for(int i = 0; i < [Link]; i++)
{
if(ob[i].ano == frmAno)
{
frmAnoFound = true;
frmIndex = i;
break;
}
}
if(!frmAnoFound)
{
[Link]("From Account Number Not Found, Try Again");
[Link](0);
}
[Link]("Enter To Account Number");
toAno = [Link]( );
toAnoFound = false;
toIndex = 0;
for(int i = 0; i < [Link]; i++)
{
if(ob[i].ano == toAno)
{
toAnoFound = true;
toIndex = i;
break;
}
}
if(!toAnoFound)
{
[Link]("To Account Number Not Found, Try Again");
[Link](0);
}
[Link]("Before Transferring " + frmAno + " Account Details");
ob[frmIndex].show( );
[Link]("Before Transferring " + toAno + " Account Details");
ob[toIndex].show( );
[Link]("Enter how much amount to be transferred");
amt = [Link]( );
balAvailable = ob[frmIndex].checkBal(amt);
if(!balAvailable)
{
[Link]("Sorry, Insufficient Balance, Minimum Balance Five Hundred");
[Link](0);
}
ob[frmIndex].transfer(ob[toIndex],amt);
[Link]("After Transferring " + frmAno + " Account Details");
ob[frmIndex].show( );
[Link]("After Transferring " + toAno + " Account Details");
ob[toIndex].show( );
}
}
Polymorphism
It is derived from two greek words called "poly" and "morphic". Poly means many and Morphic means
forms. Polymorphism means one method different forms or if something exist in many forms. It means
same method performing different tasks based on situation. It means the ability to exist in different
forms. Java supports two types of polymorphism.
1) Static Polymorphism
2) Dynamic Polymorphism
Ex :- Method overloading
Method Overloading
In Cc' language we can use unique name for methods (functions) . It means we can't put the same name
for two methods (functions). Method overloading means we can use the same name for several
methods. It means we can use single method for several purposes.
Overloading is possible when methods signature are different. Signature means method header /
method prototype. Method signature contains method name, parameters and method return type. To
overload methods we must follow one of the following two rules.
import [Link];
class Sample
{
PrintStream ps = new PrintStream([Link]);
void show(byte x)
{
[Link]("Byte : " + x);
}
void show(short x)
{
[Link]("Short : " + x);
}
void show(int x)
{
[Link]("Integer : " + x);
}
void show(long x)
{
[Link]("Long : " + x);
}
void show(float x)
{
[Link]("Float : " + x);
}
void show(double x)
{
[Link]("Double : " + x);
}
void show(boolean x)
{
[Link]("Boolean : " + x);
}
void show(char x)
{
[Link]("Character : " + x);
}
void show(String x)
{
[Link]("String : " + x);
}
};
class MethOvrLodDemo1
{
public static void main(String args[])
{
Sample ob = new Sample( );
[Link]((byte)100);
[Link]((short)10000);
[Link](100000);
[Link](10000000L);
[Link](12.34F);
[Link](56.78);
[Link](true);
[Link]('K');
[Link]("Rama");
}
}
import [Link];
class Maths
{
byte abs(byte x)
{
if(x < 0)
{
return (byte) -x;
}
else
{
return x;
}
}
short abs(short x)
{
if(x < 0)
{
return (short) -x;
}
else
{
return x;
}
}
int abs(int x)
{
if(x < 0)
{
return -x;
}
else
{
return x;
}
}
long abs(long x)
{
if(x < 0)
{
return -x;
}
else
{
return x;
}
}
float abs(float x)
{
if(x < 0)
{
return -x;
}
else
{
return x;
}
}
double abs(double x)
{
if(x < 0)
{
return -x;
}
else
{
return x;
}
}
};
class MethOvrLodDemo2
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
Maths ob = new Maths( );
byte b;
b = [Link]((byte) -100);
[Link]("Byte Absolute Value : " + b);
short s;
s = [Link]((short) -10000);
[Link]("Short Absolute Value : " + s);
int i;
i = [Link](-1000000);
[Link]("Integer Absolute Value : " + i);
long l;
l = [Link](-100000000L);
[Link]("Long Absolute Value : " + l);
float f;
f = [Link](-12.34F);
[Link]("Float Absolute Value : " + f);
double d;
d = [Link](-56.78);
[Link]("Double Absolute Value : " + d);
}
}
import [Link];
class Sum
{
PrintStream ps = new PrintStream([Link]);
void sum(int x, int y)
{
int k;
k = x + y;
[Link]("Integer Sum : " + k);
}
void sum(long x, long y)
{
long k;
k = x + y;
[Link]("Long Sum : " + k);
}
void sum(float x, float y)
{
float k;
k = x + y;
[Link]("Float Sum : " + k);
}
void sum(double x, double y)
{
double k;
k = x + y;
[Link]("Double Sum : " + k);
}
};
class MethOvrLodDemo3
{
public static void main(String args[])
{
Sum ob = new Sum( );
[Link](6,3);
[Link](63L,36L);
[Link](12.34F,56.78F);
[Link](98.76,54.32);
}
}
import [Link];
class Swapping
{
PrintStream ps = new PrintStream([Link]);
int a;
int b;
long c;
long d;
float e;
float f;
double g;
double h;
char i;
char j;
String k;
String l;
void set(int x, int y)
{
a = x;
b = y;
}
void set(long x, long y)
{
c = x;
d = y;
}
void set(float x, float y)
{
e = x;
f = y;
}
void set(double x, double y)
{
g = x;
h = y;
}
void set(char x, char y)
{
i = x;
j = y;
}
void set(String x, String y)
{
k = x;
l = y;
}
void swap(int x)
{
int temp;
temp = a;
a = b;
b = temp;
}
void swap(long x)
{
long temp;
temp = c;
c = d;
d = temp;
}
void swap(float x)
{
float temp;
temp = e;
e = f;
f = temp;
}
void swap(double x)
{
double temp;
temp = g;
g = h;
h = temp;
}
void swap(char x)
{
char temp;
temp = i;
i = j;
j = temp;
}
void swap(String x)
{
String temp;
temp = k;
k = l;
l = temp;
}
void show(int x)
{
[Link]("A Value : " + a + "\tB Value : " + b);
}
void show(long x)
{
[Link]("C Value : " + c + "\tD Value : " + d);
}
void show(float x)
{
[Link]("E Value : " + e + "\tF Value : " + f);
}
void show(double x)
{
[Link]("G Value : " + g + "\tH Value : " + h);
}
void show(char x)
{
[Link]("I Value : " + i + "\tJ Value : " + j);
}
void show(String x)
{
[Link]("K Value : " + k + "\tL Value : " + l);
}
};
class MethOvrLodDemo4
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
Swapping ob = new Swapping( );
[Link](10,20);
[Link]("Integers Before Swapping");
[Link](6);
[Link](6);
[Link]("Integers After Swapping");
[Link](6);
[Link](1000000L,20000000L);
[Link]("Longs Before Swapping");
[Link](6L);
[Link](6L);
[Link]("Longs After Swapping");
[Link](6L);
[Link](12.34F,56.78F);
[Link]("Floats Before Swapping");
[Link](1.2F);
[Link](1.2F);
[Link]("Floats After Swapping");
[Link](1.2F);
[Link](98.76,54.32);
[Link]("Doubles Before Swapping");
[Link](1.2);
[Link](1.2);
[Link]("Doubles After Swapping");
[Link](1.2);
[Link]('K','V');
[Link]("Characters Before Swapping");
[Link]('E');
[Link]('E');
[Link]("Characters After Swapping");
[Link]('E');
[Link]("Rama","Krishna");
[Link]("Strings Before Swapping");
[Link]("A");
[Link]("A");
[Link]("Strings After Swapping");
[Link]("A");
}
}
import [Link];
class Sum
{
PrintStream ps = new PrintStream([Link]);
void sum(int x, int y)
{
int k;
k = x + y;
[Link]("Two Parameters Sum : " + k);
}
void sum(int x, int y, int z)
{
int k;
k = x + y + z;
[Link]("Three Parameters Sum : " + k);
}
void sum(int x, int y, int z, int t)
{
int k;
k = x + y + z + t;
[Link]("Four Parameters Sum : " + k);
}
};
class MethOvrLodDemo5
{
public static void main(String args[])
{
Sum ob = new Sum( );
[Link](6,3);
[Link](10,20,30);
[Link](100,200,300,400);
}
}
Ex :-
void sum(int x, int y)
{
int k;
k = x + y;
[Link]("Sum : " + k);
}
int sum(int x, int y)
{
int k;
k = x + y;
return k;
}
import [Link];
class Student
{
PrintStream ps = new PrintStream([Link]);
int sno = 101;
String sname = "Rama";
double age = 12.6;
void show( )
{
[Link]("Student Number : " + sno);
[Link]("Student Name : " + sname);
[Link]("Student Age : " + age);
}
};
class ConsDemo1
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
Student ob = new Student( );
[Link]("Student Details");
[Link]( );
}
}
The main drawback of initializing class variables is, all objects are initialized with same data. Look at the
following program.
import [Link];
class Student
{
PrintStream ps = new PrintStream([Link]);
int sno = 101;
String sname = "Rama";
double age = 12.6;
void show( )
{
[Link]("Student Number : " + sno);
[Link]("Student Name : " + sname);
[Link]("Student Age : " + age);
}
};
class ConsDemo2
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
Student ob1 = new Student( );
[Link]("First Student Details");
[Link]( );
Student ob2 = new Student( );
[Link]("Second Student Details");
[Link]( );
Student ob3 = new Student( );
[Link]("Third Student Details");
[Link]( );
}
}
The above program displays all students data as same. So we can't initialize variables of a class by using
assignment operator. This drawback is resolved through constructors.
Constructors
A constructor is also one of the method of a class. But the specialty of the constructor is which contains
same class name. Constructors are used to initialize an object. The task of constructor is to initialize the
data members. We must follow the rules in constructors.
Types of Constructors
1) Non-Parameterized constructors
2) Parameterized constructors
3) Default constructors
4) Dynamic initialization of constructors
5) Constructor overloading
Non-Parameterized Constructors
import [Link];
class Student
{
PrintStream ps = new PrintStream([Link]);
int sno;
String sname;
double age;
Student( )
{
sno = 101;
sname = "Rama";
age = 12.6;
}
void show( )
{
[Link]("Student Number : " + sno);
[Link]("Student Name : " + sname);
[Link]("Student Age : " + age);
}
};
class ConsDemo3
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
Student ob = new Student( );
[Link]("Student Details");
[Link]( );
}
}
import [Link];
class Student
{
PrintStream ps = new PrintStream([Link]);
int sno;
String sname;
double age;
Student( )
{
sno = 101;
sname = "Rama";
age = 12.6;
}
void show( )
{
[Link]("Student Number : " + sno);
[Link]("Student Name : " + sname);
[Link]("Student Age : " + age);
}
};
class ConsDemo4
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
Student ob1 = new Student( );
[Link]("First Student Details");
[Link]( );
Student ob2 = new Student( );
[Link]("Second Student Details");
[Link]( );
Student ob3 = new Student( );
[Link]("Third Student Details");
[Link]( );
}
}
The above program displays all students data as same. This drawback is resolved through parameterized
constructors.
Parameterized Constructors
A parameterized constructor is a constructor, which contains some parameters. The main advantage of
using parameterized constructor is, we can initialize each object with different data.
import [Link];
class Student
{
PrintStream ps = new PrintStream([Link]);
int sno;
String sname;
double age;
Student(int vsno, String vsname, double vage)
{
sno = vsno;
sname = vsname;
age = vage;
}
void show( )
{
[Link]("Student Number : " + sno);
[Link]("Student Name : " + sname);
[Link]("Student Age : " + age);
}
};
class ConsDemo5
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
Student ob1 = new Student(101,"Rama",12.6);
[Link]("First Student Details");
[Link]( );
Student ob2 = new Student(102,"King",15.3);
[Link]("Second Student Details");
[Link]( );
Student ob3 = new Student(103,"Siva",6.3);
[Link]("Third Student Details");
[Link]( );
}
}
import [Link];
class Sum
{
PrintStream ps = new PrintStream([Link]);
int a;
int b;
int c;
Sum(int x, int y)
{
a = x;
b = y;
}
void process( )
{
c = a + b;
}
void show( )
{
[Link]("Sum : " + c);
}
};
class ConsDemo6
{
public static void main(String args[])
{
Sum ob = new Sum(6,3);
[Link]( );
[Link]( );
}
}
Default Constructors
An object always creates with the help of constructor. If your class can't contain any constructor, then
java compiler automatically writes and places a default constructor in your class. If your program
contains any constructor, java compiler can't write and place a default constructor in your class. Then it
is programmer's responsibility to write default constructor.
class_name( )
{
}
Ex :-
Student( )
{
}
The main advantage of default constructor is to create an object successfully when our program has
other constructors.
import [Link];
import [Link];
class Student
{
PrintStream ps = new PrintStream([Link]);
Scanner sc = new Scanner([Link]);
int sno;
String sname;
double age;
Student( )
{
}
Student(int vsno, String vsname, double vage)
{
sno = vsno;
sname = vsname;
age = vage;
}
void input( )
{
[Link]("Enter Student Number, Name, Age");
sno = [Link]( );
sname = [Link]( );
age = [Link]( );
}
void show( )
{
[Link]("Student Number : " + sno);
[Link]("Student Name : " + sname);
[Link]("Student Age : " + age);
}
};
class ConsDemo7
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
Student ob1 = new Student(101,"Rama",12.6);
Student ob2 = new Student( );
[Link]( );
[Link]("First Student Details");
[Link]( );
[Link]("Second Student Details");
[Link]( );
}
}
import [Link];
import [Link];
class Sum
{
PrintStream ps = new PrintStream([Link]);
Scanner sc = new Scanner([Link]);
int a;
int b;
int c;
Sum( )
{
}
Sum(int x,int y)
{
a = x;
b = y;
}
void input( )
{
[Link]("Enter Two Numbers");
a = [Link]( );
b = [Link]( );
}
void process( )
{
c = a + b;
}
void show( )
{
[Link]("Sum : " + c);
}
};
class ConsDemo8
{
public static void main(String args[])
{
Sum ob1 = new Sum(6,3);
[Link]( );
[Link]( );
Sum ob2 = new Sum( );
[Link]( );
[Link]( );
[Link]( );
}
}
import [Link];
import [Link];
class Student
{
PrintStream ps = new PrintStream([Link]);
int sno;
String sname;
double age;
Student(int vsno, String vsname, double vage)
{
sno = vsno;
sname = vsname;
age = vage;
}
void show( )
{
[Link]("Student Number : " + sno);
[Link]("Student Name : " + sname);
[Link]("Student Age : " + age);
}
};
class ConsDemo9
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
Scanner sc = new Scanner([Link]);
int xsno;
String xsname;
double xage;
[Link]("Enter Student Number, Name, Age");
xsno = [Link]( );
xsname = [Link]( );
xage = [Link]( );
Student ob = new Student(xsno,xsname,xage);
[Link]( );
}
}
import [Link];
import [Link];
class Sum
{
PrintStream ps = new PrintStream([Link]);
int a;
int b;
int c;
Sum(int x,int y)
{
a = x;
b = y;
}
void process( )
{
c = a + b;
}
void show( )
{
[Link]("Sum : " + c);
}
};
class ConsDemo10
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
Scanner sc = new Scanner([Link]);
int xa,xb;
[Link]("Enter Two Numbers");
xa = [Link]( );
xb = [Link]( );
Sum ob = new Sum(xa,xb);
[Link]( );
[Link]( );
}
}
Constructor Overloading
Like methods, we can also overload constructors. The main advantage of overloading constructors is we
can create variety of objects. It means flexible objects. Through constructor overloading, user can create
objects as per his requirements.
import [Link];
import [Link];
class Student
{
PrintStream ps = new PrintStream([Link]);
Scanner sc = new Scanner([Link]);
int sno;
String sname;
String addr;
Student( )
{
}
Student(int vsno)
{
sno = vsno;
sname = "Smith";
addr = "Tenali";
}
Student(int vsno, String vsname)
{
sno = vsno;
sname = vsname;
addr = "Guntur";
}
Student(int vsno, String vsname, String vaddr)
{
sno = vsno;
sname = vsname;
addr = vaddr;
}
void input( )
{
[Link]("Enter Student Number, Name, Address");
sno = [Link]( );
sname = [Link]( );
addr = [Link]( );
}
void show( )
{
[Link]("Student Number : " + sno);
[Link]("Student Name : " + sname);
[Link]("Student Address : " + addr);
}
};
class ConsDemo11
{
public static void main(String args[])
{
Student ob1 = new Student( );
[Link]( );
[Link]( );
Student ob2 = new Student(101);
[Link]( );
Student ob3 = new Student(102,"Tata");
[Link]( );
Student ob4 = new Student(103,"King","Chennai");
[Link]( );
}
}
this keyword
This refers to current object. Generally it is used to remove naming conflictions and returning objects.
import [Link];
class Student
{
PrintStream ps = new PrintStream([Link]);
int sno;
String sname;
double age;
Student(int sno, String sname, double age)
{
[Link] = sno;
[Link] = sname;
[Link] = age;
}
void show( )
{
[Link]("Student Number : " + sno);
[Link]("Student Name : " + sname);
[Link]("Student Age : " + age);
}
};
class ThisDemo1
{
public static void main(String args[])
{
Student ob = new Student(101,"Rama",12.6);
[Link]( );
}
}
import [Link];
class Employee
{
PrintStream ps = new PrintStream([Link]);
int empNo;
String empName;
double sal;
void set(int vempNo, String vempName, double vsal)
{
empNo = vempNo;
empName = vempName;
sal = vsal;
}
Employee incrSal( )
{
sal = sal + sal * 0.1;
return this;
}
void show( )
{
[Link]("Employee Number : " + empNo);
[Link]("Employee Name : " + empName);
[Link]("Employee Salary : " + sal);
}
};
class ThisDemo2
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
Employee ob = new Employee( );
[Link](101,"Rama",2500);
[Link]("Before Incrementing, Employee Details");
[Link]( );
ob = [Link]( );
[Link]("After Incrementing, Employee Details");
[Link]( );
}
}
Types of variables
Static variable :- A static variable is a variable, whose single copy is shared by all objects of the class.
Static variables are created on method area.
import [Link];
import [Link];
class Student
{
PrintStream ps = new PrintStream([Link]);
Scanner sc = new Scanner([Link]);
int sno;
String sname;
double age;
String cname;
void input( )
{
[Link]("Enter Student Number, Name");
sno = [Link]( );
sname = [Link]( );
[Link]("Enter Age, College Name");
age = [Link]( );
cname = [Link]( );
}
void show( )
{
[Link]("Student Number : " + sno);
[Link]("Student Name : " + sname);
[Link]("Student Age : " + age);
[Link]("College Name : " + cname);
}
};
class StatDemo1
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
Student ob1 = new Student( );
Student ob2 = new Student( );
Student ob3 = new Student( );
[Link]( );
[Link]( );
[Link]( );
[Link]( );
[Link]( );
[Link]( );
}
}
In the above program cname creates separately in 3 objects namely ob1, ob2 & ob3. Generally all
students has same college name. So memory is wasted. Another risk of the above program is user may
enter another college name which is invalid.
Generally instance data members are created in objects and static data members are created in class.
Java provides a special keyword static. Using this keyword, we can define static data members and static
methods.
The specialty of static data members is, it can't created in the object, it created in class. So, it can be
used by each and every object created from that class. It means all objects created from that class can
share these data members. Through static data members, we can save memory and provide common
data (ex :- college name, batch code) to all objects. We can also reduce invalid entry risk.
A static variable is a variable whose single copy is shared by all the objects of the class. Only one copy of
that variable in memory and it is shared by all objects of class is called static variable.
import [Link];
import [Link];
class Student
{
PrintStream ps = new PrintStream([Link]);
Scanner sc = new Scanner([Link]);
int sno;
String sname;
double age;
static String cname = "VSR";
void input( )
{
[Link]("Enter Student Number, Name, Age");
sno = [Link]( );
sname = [Link]( );
age = [Link]( );
}
void show( )
{
[Link]("Student Number : " + sno);
[Link]("Student Name : " + sname);
[Link]("Student Age : " + age);
[Link]("College Name : " + cname);
}
};
class StatDemo2
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
Student ob1 = new Student( );
Student ob2 = new Student( );
Student ob3 = new Student( );
[Link]( );
[Link]( );
[Link]( );
[Link]( );
[Link]( );
[Link]( );
}
}
import [Link];
import [Link];
class Student
{
PrintStream ps = new PrintStream([Link]);
Scanner sc = new Scanner([Link]);
static int sno;
String sname;
double age;
Student( )
{
sno++;
}
void input( )
{
[Link]("Enter Student Name, Age");
sname = [Link]( );
age = [Link]( );
}
void show( )
{
[Link]("Student Number : " + sno);
[Link]("Student Name : " + sname);
[Link]("Student Age : " + age);
}
};
class StatDemo3
{
public static void main(String args[])
{
Student ob1 = new Student( );
[Link]( );
[Link]( );
Student ob2 = new Student( );
[Link]( );
[Link]( );
Student ob3 = new Student( );
[Link]( );
[Link]( );
}
}
import [Link];
class Sample
{
PrintStream ps = new PrintStream([Link]);
int a;
static int b;
Sample( )
{
b++;
}
void set(int x)
{
a = x;
}
void show( )
{
[Link]("A Value : " + a);
[Link]("B Value : " + b);
}
};
class StatDemo4
{
public static void main(String args[])
{
Sample ob1 = new Sample( );
[Link](6);
[Link]( );
Sample ob2 = new Sample( );
[Link](3);
[Link]( );
Sample ob3 = new Sample( );
[Link](9);
[Link]( );
}
}
Types of methods
1) Instance methods
A) Accessor methods
B) Mutator methods
2) Static methods
3) Factory methods
Instance methods :- These methods act upon instance variables of a class. The variables which will
present in objects.
Accessor methods :- These are the methods which access the instance variables.
Mutator methods :- These are the methods which not only access the instance variables and also
modify them.
Generally if we want to call a method, first we must create an object from that class. Without creating
an object, we can't call the method of a class. It the method is static method, then we are able to call
that method, without creating an object.
Static method :- These methods act upon static variables of a class. These methods handles only static
data members. Non-static methods are object level methods and static methods are class level
methods.
import [Link];
class Sample
{
static void show( )
{
[Link]("Welcome to Static Methods");
}
};
class StatDemo5
{
public static void main(String args[])
{
[Link]( );
}
}
import [Link];
class Sample
{
static void show1( )
{
[Link]("Static Method");
}
void show2( )
{
[Link]("Non Static Method");
}
};
class StatDemo6
{
public static void main(String args[])
{
Sample.show1( );
Sample ob = new Sample( );
ob.show2( );
ob.show1( );
}
}
import [Link];
class Square
{
static int n;
static int s;
static void set(int x)
{
n = x;
}
static void process( )
{
s = n * n;
}
static void show( )
{
[Link]("Square : " + s);
}
};
class StatDemo7
{
public static void main(String args[])
{
[Link](6);
[Link]( );
[Link]( );
}
}
import [Link];
class Sum
{
static int a;
static int b;
static int c;
static void set(int x, int y)
{
a = x;
b= y;
}
static int process( )
{
c = a + b;
return c;
}
};
class StatDemo8
{
public static void main(String args[])
{
[Link](6,3);
int k;
k = [Link]( );
[Link]("Sum : " + k);
[Link]("Sum : " + [Link]( ));
}
}
Factory method :- A factory method is a method that returns an object of class to which it belongs. All
factory methods are static methods.
Static Blocks
A static block is a block which is prefixed with the keyword "static". The specialty of static block it
executes before the main( ) method.
class StatDemo9
{
static
{
[Link]("Static Block");
}
public static void main(String args[])
{
[Link]("Static Method");
}
}
We are using static keyword in the following three forms.
2) Static method
3) Static block
2) Static block
3) Static method
class StatDemo10
{
static int a = 10;
static
{
[Link]("A Value : " + a);
a = 20;
}
public static void main(String args[])
{
[Link]("A Value : " + a);
}
}
Inner Classes
A class within another class is called inner class. Generally if we write a class, other programmer can
create object to our class. He can use our class. So there is no security.
Security :- Restricting the access. That is only some people may access.
Generally security for instance variables is provided through private keyword. But private keyword can't
be used before a class. But we can use private keyword only for inner class. That is other programmer
can't create an object to the inner class. But we can create an object to the class and use it.
Inner class is a safety mechanism, we can't create an object for inner class in any other class, but only in
outer class. The objects of outer and inner classes will be created separately in memory. Inner class can
access the members of outer class. The object of inner class contains another invisible field called
"this$0" which contains the hashcode of outer class object. An object of inner class contains invisible
field "this$0" that refers the outer class object.
The inner class data members can be referenced as
[Link];
[Link];
class Sample
{
void show( )
{
[Link]("Outer Class");
Simple v = new Simple( );
[Link]( );
}
private class Simple
{
void display( )
{
[Link]("Inner Class");
}
};
};
class InnerDemo1
{
public static void main(String args[])
{
Sample k = new Sample( );
[Link]( );
}
}
import [Link];
import [Link];
class Student
{
PrintStream ps = new PrintStream([Link]);
Scanner sc = new Scanner([Link]);
int sno;
String sname;
int em;
int tm;
int hm;
int mm;
int scm;
int som;
int tot;
double avg;
String res;
void input( )
{
[Link]("Enter Student Number, Name");
sno = [Link]( );
sname = [Link]( );
[Link]("Enter English, Telugu, Hindi Marks");
em = [Link]( );
tm = [Link]( );
hm = [Link]( );
[Link]("Enter Maths, Science, Social Marks");
mm = [Link]( );
scm = [Link]( );
som = [Link]( );
}
void process( )
{
tot = em + tm + hm + mm + scm + som;
avg = tot / 6;
}
void show( )
{
Result resob = new Result( );
res = [Link]( );
[Link]("Student Number : " + sno);
[Link]("Student Name : " + sname);
[Link]("Total Marks : " + tot);
[Link]("Average Marks : %.2f\n",avg);
[Link]("Result : " + res);
}
class Result
{
String rs;
String findRes( )
{
if(em >= 35 && tm >= 35 && hm >= 35 && mm >= 35 && scm >= 35 && som >= 35)
{
rs = "Pass";
}
else
{
rs = "Fail";
}
return rs;
}
};
};
class InnerDemo2
{
public static void main(String args[])
{
Student ob = new Student( );
[Link]( );
[Link]( );
[Link]( );
}
}
class BankAct
{
private double bal;
BankAct(double vbal)
{
bal = vbal;
}
void start(double vrate)
{
Interest in = new Interest(vrate);
[Link]( );
}
private class Interest
{
private double rate;
Interest(double vrate)
{
rate = vrate;
}
void calculateInterest( )
{
double interest = bal * rate / 100;
[Link]("Actual Balance : " + bal);
[Link]("Interest : " + interest);
bal = bal + interest;
[Link]("Final Balance : " + bal);
}
};
};
class InnerDemo3
{
public static void main(String args[])
{
BankAct ob = new BankAct(10000);
[Link](10);
}
}
Inheritance
import [Link];
import [Link];
class Student1
{
PrintStream ps = new PrintStream([Link]);
Scanner sc = new Scanner([Link]);
int sno;
String sname;
void input1( )
{
[Link]("Enter Student Number, Name");
sno = [Link]( );
sname = [Link]( );
}
void show1( )
{
[Link]("Student Number : " + sno);
[Link]("Student Name : " + sname);
}
};
class Student2
{
PrintStream ps = new PrintStream([Link]);
Scanner sc = new Scanner([Link]);
int sno;
String sname;
int em;
int tm;
int hm;
int mm;
int scm;
int som;
int tot;
double avg;
String res;
void input2( )
{
[Link]("Enter Student Number, Name");
sno = [Link]( );
sname = [Link]( );
[Link]("Enter English, Telugu, Hindi Marks");
em = [Link]( );
tm = [Link]( );
hm = [Link]( );
[Link]("Enter Maths, Science, Social Marks");
mm = [Link]( );
scm = [Link]( );
som = [Link]( );
}
void process( )
{
tot = em + tm + hm + mm + scm + som;
avg = tot / 6;
if(em >= 35 && tm >= 35 && hm >= 35 && mm >= 35 && scm >= 35 && som >= 35)
{
if(avg >= 80)
{
res = "Distinction";
}
else
if(avg >= 60)
{
res = "First Class";
}
else
if(avg >= 50)
{
res = "Second Class";
}
else
if(avg >= 40)
{
res = "Third Class";
}
else
{
res = "Ordinary Pass";
}
}
else
{
res = "Fail";
}
}
void show2( )
{
[Link]("Student Number : " + sno);
[Link]("Student Name : " + sname);
[Link]("Total Marks : " + tot);
[Link]("Average Marks : %.2f\n",avg);
[Link]("Result : " + res);
}
};
class InhDemo1
{
public static void main(String args[])
{
Student1 ob1 = new Student1( );
ob1.input1( );
ob1.show1( );
Student2 ob2 = new Student2( );
ob2.input2( );
[Link]( );
ob2.show2( );
}
}
import [Link];
import [Link];
class Student1
{
PrintStream ps = new PrintStream([Link]);
Scanner sc = new Scanner([Link]);
int sno;
String sname;
void input1( )
{
[Link]("Enter Student Number, Name");
sno = [Link]( );
sname = [Link]( );
}
void show1( )
{
[Link]("Student Number : " + sno);
[Link]("Student Name : " + sname);
}
};
class Student2 extends Student1
{
int em;
int tm;
int hm;
int mm;
int scm;
int som;
int tot;
double avg;
String res;
void input2( )
{
[Link]("Enter English, Telugu, Hindi Marks");
em = [Link]( );
tm = [Link]( );
hm = [Link]( );
[Link]("Enter Maths, Science, Social Marks");
mm = [Link]( );
scm = [Link]( );
som = [Link]( );
}
void process( )
{
tot = em + tm + hm + mm + scm + som;
avg = tot / 6;
if(em >= 35 && tm >= 35 && hm >= 35 && mm >= 35 && scm >= 35 && som >= 35)
{
if(avg >= 80)
{
res = "Distinction";
}
else
if(avg >= 60)
{
res = "First Class";
}
else
if(avg >= 50)
{
res = "Second Class";
}
else
if(avg >= 40)
{
res = "Third Class";
}
else
{
res = "Ordinary Pass";
}
}
else
{
res = "Fail";
}
}
void show2( )
{
[Link]("Total Marks : " + tot);
[Link]("Average Marks : %.2f\n",avg);
[Link]("Result : " + res);
}
};
class InhDemo2
{
public static void main(String args[])
{
Student1 ob1 = new Student1( );
ob1.input1( );
ob1.show1( );
Student2 ob2 = new Student2( );
ob2.input1( );
ob2.input2( );
[Link]( );
ob2.show1( );
ob2.show2( );
}
}
Inheritance is the technique of extension of already existing class. It means we can produce new class
from existing class without disturbing existing class. In this process, existing class is called as super class /
base class / old class and the extended class is called as sub class / derived class / new class. Sub class is
powerful than super class, because sub class have all the features of super class and additional features
of itself. The main advantage of inheritance is reusability of code. If we create an object to sub class it
contains a copy of super class object. That is the reason why super class members are available to sub
class. Generally we don't create an object to super class in inheritance. So better way is create object to
sub class not to super class.
Types of Inheritance
1) Single inheritance
3) Hierarchical inheritance
4) Multiple inheritance
6) Hybrid inheritance
[draw figure]
Java's rule is that a class can have only one super class. So java does not support multiple, multi path
and hybrid inheritances directly. But supports indirectly in the form of interfaces. An interface is similar
to class but minor differences.
Single Inheritance
Deriving new class from single class.
import [Link];
class One
{
PrintStream ps = new PrintStream([Link]);
void show1( )
{
[Link]("show1 method called from class One");
}
};
class Two extends One
{
void show2( )
{
[Link]("show2 method called from class Two");
}
};
class InhDemo3
{
public static void main(String args[])
{
Two ob = new Two( );
ob.show1( );
ob.show2( );
}
}
In the above program two classes have different method names called show1( ) and show2( ). There is
possibility to assign same name for two methods in two classes. This concept is called method
overriding.
Method overriding :- Writing two or more methods with same name and same signature is called
method overriding. The sub class method overrides the super class method.
super :- This keyword is used to access super class methods & data members.
import [Link];
class One
{
PrintStream ps = new PrintStream([Link]);
void show( )
{
[Link]("show method called from class One");
}
};
class Two extends One
{
void show( )
{
[Link]( );
[Link]("show method called from class Two");
}
};
class InhDemo4
{
public static void main(String args[])
{
Two ob = new Two( );
[Link]( );
}
}
protected :- If a member is declared as protected, then the member is available to that class methods
and it's sub class methods. It means it can used by that class and it's sub class.
import [Link];
import [Link];
class NonExecutive
{
PrintStream ps = new PrintStream([Link]);
Scanner sc = new Scanner([Link]);
private int empNo;
private String empName;
private String job;
protected double bsal;
void input( )
{
[Link]("Enter Employee Number, Name");
empNo = [Link]( );
empName = [Link]( );
[Link]("Enter Job, Basic Salary");
job = [Link]( );
bsal = [Link]( );
}
void show( )
{
[Link]("Employee Number : " + empNo);
[Link]("Employee Name : " + empName);
[Link]("Employee Job : " + job);
[Link]("Basic Salary : " + bsal);
}
};
class Executive extends NonExecutive
{
double hra;
double da;
double ta;
double it;
double pf;
double alw;
double gsal;
double ded;
double nsal;
void process( )
{
hra = bsal * 0.1;
da = bsal * 0.15;
ta = bsal * 0.3;
it = bsal * 0.03;
pf = bsal * 0.08;
alw = hra + da + ta;
gsal = bsal + alw;
ded = it + pf;
nsal = gsal - ded;
}
void show( )
{
[Link]( );
[Link]("House Rent Allowance : " + hra);
[Link]("Dearness Allowance : " + da);
[Link]("Travelling Allowance : " + ta);
[Link]("Income Tax : " + it);
[Link]("Provident Fund : " + pf);
[Link]("Allowances : " + alw);
[Link]("Gross Salary : " + gsal);
[Link]("Deductions : " + ded);
[Link]("Net Salary : " + nsal);
}
};
class InhDemo5
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
NonExecutive neob = new NonExecutive( );
[Link]("Enter Non Executive Employee Details");
[Link]( );
[Link]( );
Executive eob = new Executive( );
[Link]("Enter Executive Employee Details");
[Link]( );
[Link]( );
[Link]( );
}
}
Multilevel Inheritance
import [Link];
class One
{
PrintStream ps = new PrintStream([Link]);
void show( )
{
[Link]("show method called from class One");
}
};
class Two extends One
{
void show( )
{
[Link]( );
[Link]("show method called from class Two");
}
};
class Three extends Two
{
void show( )
{
[Link]( );
[Link]("show method called from class Three");
}
};
class Four extends Three
{
void show( )
{
[Link]( );
[Link]("show method called from class Four");
}
};
class InhDemo6
{
public static void main(String args[])
{
Four ob = new Four( );
[Link]( );
}
}
In the above program class three is the direct super class to class four and class two, one are the indirect
super classes to class four.
In the above program class four is the direct sub class to class three and indirect sub class to class two
and class one.
import [Link];
class One
{
PrintStream ps = new PrintStream([Link]);
void show1( )
{
[Link]("show1 method called from class One");
}
};
class Two extends One
{
void show2( )
{
[Link]("show2 method called from class Two");
}
};
class Three extends Two
{
void show3( )
{
[Link]("show3 method called from class Three");
}
};
class Four extends Three
{
void show4( )
{
[Link]("show4 method called from class Four");
}
};
class InhDemo7
{
public static void main(String args[])
{
Four ob = new Four( );
ob.show1( );
ob.show2( );
ob.show3( );
ob.show4( );
}
}
import [Link];
import [Link];
import [Link];
class DateDemo1
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
Scanner sc = new Scanner([Link]);
int d,m,y;
[Link]("Enter Day, Month, Year");
d = [Link]( );
m = [Link]( );
y = [Link]( ); .// yy + 100
Date dob = new Date(y,(m-1),d);
[Link]("Date of Birth : " + dob);
}
}
import [Link];
import [Link];
import [Link];
class DateDemo2
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
Scanner sc = new Scanner([Link]);
int d,m,y;
[Link]("Enter Day, Month, Year");
d = [Link]( );
m = [Link]( );
y = [Link]( );
Date dob = new Date(y,(m-1),d);
[Link]("Date of Birth : " + dob);
}
}
import [Link];
import [Link];
import [Link];
class DateDemo3
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
Scanner sc = new Scanner([Link]);
String str;
[Link]("Enter Date of Birth [yyyy-mm-dd]");
str = [Link]( );
Date dob = [Link](str);
[Link]("Date of Birth : " + str);
[Link]("Date of Birth : " + dob);
}
}
import [Link];
import [Link];
import [Link];
class Student
{
PrintStream ps = new PrintStream([Link]);
Scanner sc = new Scanner([Link]);
int sno;
String sname;
String cls;
void input( )
{
[Link]("Enter Student Number, Name");
sno = [Link]( );
sname = [Link]( );
[Link]("Enter Studying Class");
cls = [Link]( );
}
void show( )
{
[Link]("Student Number : " + sno);
[Link]("Student Name : " + sname);
[Link]("Studying Class : " + cls);
}
};
class Personal extends Student
{
String fname;
String saddr;
String str;
Date dob;
void input( )
{
[Link]( );
[Link]("Enter Father Name, Address");
fname = [Link]( );
saddr = [Link]( );
[Link]("Enter Date of Birth [yyyy-mm-dd]");
str = [Link]( );
dob = [Link](str);
}
void show( )
{
[Link]( );
[Link]("Father Name : " + fname);
[Link]("Student Address : " + saddr);
[Link]("Date of Birth : " + dob);
}
};
class Exam extends Personal
{
int em;
int tm;
int hm;
int mm;
int scm;
int som;
int tot;
double avg;
String res;
void input( )
{
[Link]( );
[Link]("Enter English, Telugu, Hindi Marks");
em = [Link]( );
tm = [Link]( );
hm = [Link]( );
[Link]("Enter Maths, Science, Social Marks");
mm = [Link]( );
scm = [Link]( );
som = [Link]( );
}
void process( )
{
tot = em + tm + hm + mm + scm + som;
avg = tot / 6;
if(em >= 35 && tm >= 35 && hm >= 35 && mm >= 35 && scm >= 35 && som >= 35)
{
if(avg >= 80)
{
res = "Distinction";
}
else
if(avg >= 60)
{
res = "First Class";
}
else
if(avg >= 50)
{
res = "Second Class";
}
else
if(avg >= 40)
{
res = "Third Class";
}
else
{
res = "Ordinary Pass";
}
}
else
{
res = "Fail";
}
}
void show( )
{
[Link]( );
[Link]("Total Marks : " + tot);
[Link]("Average Marks : %.2f\n",avg);
[Link]("Result : " + res);
}
};
class InhDemo8
{
public static void main(String args[])
{
Exam ob = new Exam( );
[Link]( );
[Link]( );
[Link]( );
}
}
import [Link];
import [Link];
import [Link];
class Employee
{
PrintStream ps = new PrintStream([Link]);
Scanner sc = new Scanner([Link]);
private int empNo;
private String empName;
private String job;
private String cname;
protected double bsal;
void input( )
{
[Link]("Enter Employee Number, Name");
empNo = [Link]( );
empName = [Link]( );
[Link]("Enter Company Name, Job, Basic Salary");
cname = [Link]( );
job = [Link]( );
bsal = [Link]( );
}
void show( )
{
[Link]("Employee Number : " + empNo);
[Link]("Employee Name : " + empName);
[Link]("Company Name : " + cname);
[Link]("Employee Job : " + job);
[Link]("Basic Salary : " + bsal);
}
};
class Personal extends Employee
{
String fname;
String eaddr;
String str;
Date dob,doj;
void input( )
{
[Link]( );
[Link]("Enter Father Name, Address");
fname = [Link]( );
eaddr = [Link]( );
[Link]("Enter Date of Birth [yyyy-mm-dd]");
str = [Link]( );
dob = [Link](str);
[Link]("Enter Date of Joining [yyyy-mm-dd]");
str = [Link]( );
doj = [Link](str);
}
void show( )
{
[Link]( );
[Link]("Father Name : " + fname);
[Link]("Employee Address : " + eaddr);
[Link]("Date of Birth : " + dob);
[Link]("Date of Joining : " + doj);
}
};
class NetSalary extends Personal
{
double hra;
double da;
double ta;
double it;
double pf;
double alw;
double gsal;
double ded;
double nsal;
void process( )
{
hra = bsal * 0.1;
da = bsal * 0.15;
ta = bsal * 0.3;
it = bsal * 0.03;
pf = bsal * 0.08;
alw = hra + da + ta;
gsal = bsal + alw;
ded = it + pf;
nsal = gsal - ded;
}
void show( )
{
[Link]( );
[Link]("House Rent Allowance : " + hra);
[Link]("Dearness Allowance : " + da);
[Link]("Travelling Allowance : " + ta);
[Link]("Income Tax : " + it);
[Link]("Provident Fund : " + pf);
[Link]("Allowances : " + alw);
[Link]("Gross Salary : " + gsal);
[Link]("Deductions : " + ded);
[Link]("Net Salary : " + nsal);
}
};
class InhDemo9
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
NetSalary ob = new NetSalary( );
[Link]( );
[Link]( );
[Link]( );
}
}
Hierarchical Inheritance
This type of inheritance is similar to a tree. In this model each super class has minimum two sub classes.
Generally in this model objects are created from leaf node (last sub) classes.
import [Link];
class One
{
PrintStream ps = new PrintStream([Link]);
void show( )
{
[Link]("show method called from class One");
}
};
class Two extends One
{
void show( )
{
[Link]( );
[Link]("show method called from class Two");
}
};
class Three extends One
{
void show( )
{
[Link]( );
[Link]("show method called from class Three");
}
};
class Four extends Two
{
void show( )
{
[Link]( );
[Link]("show method called from class Four");
}
};
class Five extends Two
{
void show( )
{
[Link]( );
[Link]("show method called from class Five");
}
};
class Six extends Three
{
void show( )
{
[Link]( );
[Link]("show method called from class Six");
}
};
class Seven extends Three
{
void show( )
{
[Link]( );
[Link]("show method called from class Seven");
}
};
class InhDemo10
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
Four ob1 = new Four( );
Five ob2 = new Five( );
Six ob3 = new Six( );
Seven ob4 = new Seven( );
[Link]("Class Four Methods");
[Link]( );
[Link]("Class Five Methods");
[Link]( );
[Link]("Class Six Methods");
[Link]( );
[Link]("Class Seven Methods");
[Link]( );
}
}
import [Link];
import [Link];
class Vehicle
{
PrintStream ps = new PrintStream([Link]);
Scanner sc = new Scanner([Link]);
String vname;
int wheels;
void input( )
{
[Link]("Enter Vehicle Name");
vname = [Link]( );
[Link]("Enter Number of Wheels");
wheels = [Link]( );
}
void show( )
{
[Link]("Vehicle Name : " + vname);
[Link]("Number of Wheels : " + wheels);
}
};
class LightMotor extends Vehicle
{
int speed;
void input( )
{
[Link]( );
[Link]("Enter Speed in Kilometers Per Hour");
speed = [Link]( );
}
void show( )
{
[Link]( );
[Link]("Speed [km/h] : " + speed);
}
};
class HeavyMotor extends Vehicle
{
String permitType;
void input( )
{
[Link]( );
[Link]("Enter Permit Type [State / National / International");
permitType = [Link]( );
}
void show( )
{
[Link]( );
[Link]("Permit Type : " + permitType);
}
};
class GearMotor extends LightMotor
{
int gears;
void input( )
{
[Link]( );
[Link]("Enter Number of Gears");
gears = [Link]( );
}
void show( )
{
[Link]( );
[Link]("Number of Gears : " + gears);
}
};
class NonGearMotor extends LightMotor
{
};
class PassengerMotor extends HeavyMotor
{
int seats;
void input( )
{
[Link]( );
[Link]("Enter Number of Seats");
seats = [Link]( );
}
void show( )
{
[Link]( );
[Link]("Number of Seats : " + seats);
}
};
class GoodsMotor extends HeavyMotor
{
int capacity;
void input( )
{
[Link]( );
[Link]("Enter Capacity in Tons");
capacity = [Link]( );
}
void show( )
{
[Link]( );
[Link]("Capacity [Tons] : " + capacity);
}
};
class InhDemo11
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
GearMotor ob1 = new GearMotor( );
NonGearMotor ob2 = new NonGearMotor( );
PassengerMotor ob3 = new PassengerMotor( );
GoodsMotor ob4 = new GoodsMotor( );
[Link]("Enter Gear Motor Information");
[Link]( );
[Link]("\t\tGear Motor Information");
[Link]("\t\t===================");
[Link]( );
[Link]("Enter Non Gear Motor Information");
[Link]( );
[Link]("\t\tNon Gear Motor Information");
[Link]("\t\t=======================");
[Link]( );
[Link]("Enter Passenger Motor Information");
[Link]( );
[Link]("\t\tPassenger Motor Information");
[Link]("\t\t=======================");
[Link]( );
[Link]("Enter Goods Motor Information");
[Link]( );
[Link]("\t\tGoods Motor Information");
[Link]("\t\t====================");
[Link]( );
}
}
super keyword
import [Link];
class One
{
PrintStream ps = new PrintStream([Link]);
void show( )
{
[Link]("show method called from class One");
}
};
class Two extends One
{
void show( )
{
[Link]( );
[Link]("show method called from class Two");
}
};
class InhDemo12
{
public static void main(String args[])
{
Two ob = new Two( );
[Link]( );
}
}
import [Link];
class One
{
PrintStream ps = new PrintStream([Link]);
protected int a;
};
class Two extends One
{
int a;
void set( )
{
a = 10;
super.a = 20;
}
void show( )
{
[Link]("Sub Class A Value : " + a);
[Link]("Super Class A Value : " + super.a);
}
};
class InhDemo13
{
public static void main(String args[])
{
Two ob = new Two( );
[Link]( );
[Link]( );
}
}
import [Link];
class One
{
PrintStream ps = new PrintStream([Link]);
One( )
{
[Link]("Class One Constructor Called");
}
};
class Two extends One
{
Two( )
{
[Link]("Class Two Constructor Called");
}
};
class Three extends Two
{
Three( )
{
[Link]("Class Three Constructor Called");
}
};
class InhDemo14
{
public static void main(String args[])
{
Three ob = new Three( );
}
}
Abstract Methods
It is a type of method which has only function declaration. Sub class must override these methods. If a
class contains at least one abstract method, that class must be declared as abstract class. We can't
create an object from abstract class, only we can create reference from that class.
import [Link];
abstract class One
{
abstract void show( );
};
class Two extends One
{
PrintStream ps = new PrintStream([Link]);
void show( )
{
[Link]("Show method called from class Two");
}
};
class AbstDemo1
{
public static void main(String args[ ])
{
Two ob = new Two( );
[Link]( );
}
}
Dynamic Polymorphism
The polymorphism exhibited at runtime is called dynamic polymorphism / late binding. At the time of
compilation, compiler don't know that which method is calling, so it will keep quite until runtime. At
runtime JVM will call the method which we are calling.
Method signature :- Method name along with method parameters and return type.
Method overloading :- Writing two or more methods with same name but with different method
signature is called method overloading.
Method overriding :- Writing two or more methods with same name and same signature is called
method overriding. The sub class method overrides the super class method. Method overriding is an
example of dynamic polymorphism in java. In method overriding, JVM binds (links) a method call with
the method code at runtime depending on the type of reference used to call the method. So this is
called late binding.
A programmer uses method overloading when he wants to extend the capabilities of an existing
method. Method overloading is a refinement.
A programmer uses method overriding when he wants to provide a different implementations for the
same method. Method overriding is a replacement.
import [Link];
abstract class One
{
PrintStream ps = new PrintStream([Link]);
abstract void show( );
};
class Two extends One
{
void show( )
{
[Link]("Show method called from class Two");
}
};
class Three extends One
{
void show( )
{
[Link]("Show method called from class Three");
}
};
class Four extends One
{
void show( )
{
[Link]("Show method called from class Four");
}
};
class Five extends One
{
void show( )
{
[Link]("Show method called from class Five");
}
};
class DynPolyDemo1
{
public static void main(String args[ ])
{
One ref;
Two ob2 = new Two( );
Three ob3 = new Three( );
Four ob4 = new Four( );
Five ob5 = new Five( );
ref = ob2;
[Link]( );
ref = ob3;
[Link]( );
ref = ob4;
[Link]( );
ref = ob5;
[Link]( );
}
}
final keyword
final keyword have three forms.
import [Link];
class FinalDemo1
{
public static void main(String args[ ])
{
PrintStream ps = new PrintStream([Link]);
final int a = 10;
[Link]("A Value : " + a);
a = 20; // error
[Link]("A Value : " + a);
}
}
import [Link];
class One
{
PrintStream ps = new PrintStream([Link]);
final void show( )
{
[Link]("Show method called from class One");
}
};
class Two extends One
{
void show( ) // error
{
[Link]("Show method called from class Two");
}
};
class FinalDemo2
{
public static void main(String args[ ])
{
Two ob = new Two( );
[Link]( );
}
}
import [Link];
final class One
{
PrintStream ps = new PrintStream([Link]);
void show( )
{
[Link]("Show method called from class One");
}
};
class Two extends One // error
{
void show( )
{
[Link]("Show method called from class Two");
}
};
class FinalDemo3
{
public static void main(String args[ ])
{
Two ob = new Two( );
[Link]( );
}
}
Interfaces
An interface is a fully set of abstract methods. We need not to use abstract keyword before methods. At
the time of overriding we must use public access specifier in sub classes.
import [Link];
interface One
{
void show( );
};
class Two implements One
{
PrintStream ps = new PrintStream([Link]);
public void show( )
{
[Link]("Show method called from class Two");
}
};
class InterDemo1
{
public static void main(String args[ ])
{
Two ob = new Two( );
[Link]( );
}
}
import [Link];
interface One
{
void show1( );
void show2( );
void show3( );
};
class Two implements One
{
PrintStream ps = new PrintStream([Link]);
public void show1( )
{
[Link]("Show1 method called from class Two");
}
public void show2( )
{
[Link]("Show2 method called from class Two");
}
public void show3( )
{
[Link]("Show3 method called from class Two");
}
};
class Three implements One
{
PrintStream ps = new PrintStream([Link]);
public void show1( )
{
[Link]("Show1 method called from class Three");
}
public void show2( )
{
[Link]("Show2 method called from class Three");
}
public void show3( )
{
[Link]("Show3 method called from class Three");
}
};
class InterDemo2
{
public static void main(String args[ ])
{
Two ob2 = new Two( );
ob2.show1( );
ob2.show2( );
ob2.show3( );
Three ob3 = new Three( );
ob3.show1( );
ob3.show2( );
ob3.show3( );
}
}
import [Link];
interface One
{
void show1( );
void show2( );
};
interface Two
{
void show3( );
void show4( );
};
class Three implements One,Two
{
PrintStream ps = new PrintStream([Link]);
public void show1( )
{
[Link]("Show1 method called from class Three");
}
public void show2( )
{
[Link]("Show2 method called from class Three");
}
public void show3( )
{
[Link]("Show3 method called from class Three");
}
public void show4( )
{
[Link]("Show4 method called from class Three");
}
};
class InterDemo3
{
public static void main(String args[ ])
{
Three ob = new Three( );
ob.show1( );
ob.show2( );
ob.show3( );
ob.show4( );
}
}
A class may have one super class and any number of interfaces
import [Link];
class One
{
PrintStream ps = new PrintStream([Link]);
void show1( )
{
[Link]("Show1 method called from class One");
}
void show2( )
{
[Link]("Show2 method called from class One");
}
};
interface Two
{
void show3( );
void show4( );
};
class Three extends One implements Two
{
PrintStream ps = new PrintStream([Link]);
public void show3( )
{
[Link]("Show3 method called from class Three");
}
public void show4( )
{
[Link]("Show4 method called from class Three");
}
};
class InterDemo4
{
public static void main(String args[ ])
{
Three ob = new Three( );
ob.show1( );
ob.show2( );
ob.show3( );
ob.show4( );
}
}
import [Link];
interface One
{
void show1( );
void show2( );
};
interface Two extends One
{
void show3( );
void show4( );
};
class Three implements Two
{
PrintStream ps = new PrintStream([Link]);
public void show1( )
{
[Link]("Show1 method called from class Three");
}
public void show2( )
{
[Link]("Show2 method called from class Three");
}
public void show3( )
{
[Link]("Show3 method called from class Three");
}
public void show4( )
{
[Link]("Show4 method called from class Three");
}
};
class InterDemo5
{
public static void main(String args[ ])
{
Three ob = new Three( );
ob.show1( );
ob.show2( );
ob.show3( );
ob.show4( );
}
}
Exception Handling
1) Syntax errors
2) Logical errors
3) Runtime errors
Runtime errors :- These errors occurs at runtime. These errors are most dangerous. We can’t guess
whether these errors occurs or not. When runtime error occurs then the program breaks. Runtime
errors are also called as exceptions. We can handle when a runtime error occurs with exception handling
mechanism.
ArithmeticException
import [Link];
class Excep1
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
int a,b,c;
[Link]("Module 1");
a = [Link](args[0]);
b = [Link](args[1]);
c = a / b;
[Link]("Quotient : " + c);
[Link]("Module 3");
}
}
Program using exception handling
import [Link];
class Excep2
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
int a,b,c;
[Link]("Module 1");
a = [Link](args[0]);
b = [Link](args[1]);
try
{
c = a / b;
[Link]("Quotient : " + c);
}
catch(ArithmeticException ob)
{
[Link]( );
[Link](ob);
[Link]([Link]( ));
[Link]("Second value not be zero");
}
[Link]("Module 3");
}
}
import [Link];
class Excep3
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
int a,b,c;
[Link]("Module 1");
a = [Link](args[0]);
b = [Link](args[1]);
try
{
c = a / b;
[Link]("Quotient : " + c);
}
catch(ArithmeticException ob)
{
}
[Link]("Module 3");
}
}
ArrayIndexOutOfBoundsException
import [Link];
class Excep4
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
int a,b,c;
[Link]("Module 1");
try
{
a = [Link](args[0]);
b = [Link](args[1]);
c = a / b;
[Link]("Quotient : " + c);
}
catch(ArrayIndexOutOfBoundsException ob)
{
[Link]("Please enter 2 numbers");
}
[Link]("Module 3");
}
}
NumberFormatException
import [Link];
class Excep5
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
int a,b,c;
[Link]("Module 1");
try
{
a = [Link](args[0]);
b = [Link](args[1]);
c = a / b;
[Link]("Quotient : " + c);
}
catch(NumberFormatException ob)
{
[Link]("Please enter 2 integers");
}
[Link]("Module 3");
}
}
import [Link];
class Excep6
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
int a,b,c;
[Link]("Module 1");
try
{
a = [Link](args[0]);
b = [Link](args[1]);
c = a / b;
[Link]("Quotient : " + c);
}
catch(ArrayIndexOutOfBoundsException ob)
{
[Link]("Please enter 2 numbers");
}
catch(NumberFormatException ob)
{
[Link]("Please enter 2 integers");
}
catch(ArithmeticException ob)
{
[Link]("Second value not be zero");
}
catch(Exception ob)
{
[Link]("Some error occured");
}
[Link]("Module 3");
}
}
finally :- This block statements executes whether the exception is raised or not. Generally file and
database closing statements are written in this block.
import [Link];
class Excep7
{
public static void main(String args[])
{
PrintStream ps = new PrintStream([Link]);
int a,b,c;
[Link]("Module 1");
a = [Link](args[0]);
b = [Link](args[1]);
try
{
c = a / b;
[Link]("Quotient : " + c);
}
catch(ArithmeticException ob)
{
[Link]("Second value not be zero");
}
finally
{
[Link]("Module 3");
}
}
}
Types of Exceptions
1) Checked Exceptions
2) Unchecked Exceptions
Checked exceptions are raised at the time of compilation. So we must throws checked exceptions in that
method.
import [Link];
import [Link];
class Excep8
{
public static void main(String args[ ]) throws IOException
{
PrintStream ps = new PrintStream([Link]);
char x;
[Link]("Enter Character");
x = (char) [Link]( );
[Link]("Character : " + x);
}
}
import [Link];
class InvalidMarks extends Exception
{
};
class Excep10
{
public static void main(String args[ ])
{
PrintStream ps = new PrintStream([Link]);
int m;
m = [Link](args[0]);
try
{
if(m > 100)
{
throw new InvalidMarks( );
}
}
catch(InvalidMarks ob)
{
[Link]("Please enter between 0-100");
}
[Link]("Marks : " + m);
}
}
Packages
A package is a set of classes & interfaces. Generally all classes are placed in public mode in classes which
are writing in the packages. Because they access outside the package.
package test;
import [Link];
import [Link];
public class Student
{
PrintStream ps = new PrintStream([Link]);
Scanner sc = new Scanner([Link]);
int sno;
String sname;
int em;
int tm;
int hm;
int mm;
int scm;
int som;
int tot;
double avg;
String res;
public void input( )
{
[Link]("Enter Student Number, Name");
sno = [Link]( );
sname = [Link]( );
[Link]("Enter English, Telugu, Hindi Marks");
em = [Link]( );
tm = [Link]( );
hm = [Link]( );
[Link]("Enter Maths, Science, Social Marks");
mm = [Link]( );
scm = [Link]( );
som = [Link]( );
}
public void process( )
{
tot = em + tm + hm + mm + scm + som;
avg = tot / 6;
if(em >= 35 && tm >= 35 && hm >= 35 && mm >= 35 && scm >= 35 && som >= 35)
{
if(avg >= 80)
{
res = "Distinction";
}
else
if(avg >= 60)
{
res = "First Class";
}
else
if(avg >= 50)
{
res = "Second Class";
}
else
if(avg >= 40)
{
res = "Third Class";
}
else
{
res = "Ordinary Pass";
}
}
else
{
res = "Fail";
}
}
public void show( )
{
[Link]("Student Number : " + sno);
[Link]("Student Name : " + sname);
[Link]("Total Marks : " + tot);
[Link]("Average Marks : %.2f\n",avg);
[Link]("Result : " + res);
}
};
javac -d . [Link]
import [Link];
class PackDemo2
{
public static void main(String args[ ])
{
Student ob = new Student( );
[Link]( );
[Link]( );
[Link]( );
}
}
package maths;
public class Addition
{
int a;
int b;
int c;
public Addition(int x, int y)
{
a = x;
b = y;
}
public int process( )
{
c = a + b;
return c;
}
};
javac -d . [Link]
package maths;
public class Subtraction
{
int a;
int b;
int c;
public Subtraction(int x, int y)
{
a = x;
b = y;
}
public int process( )
{
c = a - b;
return c;
}
};
javac -d . [Link]
package maths;
public class Multiplication
{
int a;
int b;
int c;
public Multiplication(int x, int y)
{
a = x;
b = y;
}
public int process( )
{
c = a * b;
return c;
}
};
javac -d . [Link]
package maths;
public class Division
{
int a;
int b;
int c;
public Division(int x, int y)
{
a = x;
b = y;
}
public int process( )
{
c = a / b;
return c;
}
};
javac -d . [Link]
package maths;
public class Remainder
{
int a;
int b;
int c;
public Remainder(int x, int y)
{
a = x;
b = y;
}
public int process( )
{
c = a % b;
return c;
}
};
javac -d . [Link]
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
class PackDemo3
{
public static void main(String args[ ])
{
PrintStream ps = new PrintStream([Link]);
Addition ob1 = new Addition(10,20);
int k;
k = [Link]( );
[Link]("Addition : " + k);
Subtraction ob2 = new Subtraction(10,5);
k = [Link]( );
[Link]("Subtraction : " + k);
Multiplication ob3 = new Multiplication(6,3);
k = [Link]( );
[Link]("Multiplication : " + k);
Division ob4 = new Division(23,4);
k = [Link]( );
[Link]("Division : " + k);
Remainder ob5 = new Remainder(23,4);
k = [Link]( );
[Link]("Remainder : " + k);
}
}
Before using import package_name.* we must move all source (java) files into package / other directory
from working directory.
import maths.*;
import [Link];
class PackDemo4
{
public static void main(String args[ ])
{
PrintStream ps = new PrintStream([Link]);
Addition ob1 = new Addition(10,20);
int k;
k = [Link]( );
[Link]("Addition : " + k);
Subtraction ob2 = new Subtraction(10,5);
k = [Link]( );
[Link]("Subtraction : " + k);
Multiplication ob3 = new Multiplication(6,3);
k = [Link]( );
[Link]("Multiplication : " + k);
Division ob4 = new Division(23,4);
k = [Link]( );
[Link]("Division : " + k);
Remainder ob5 = new Remainder(23,4);
k = [Link]( );
[Link]("Remainder : " + k);
}
}
Sub Packages
package [Link];
import [Link];
import [Link];
public class Stud
{
PrintStream ps = new PrintStream([Link]);
Scanner sc = new Scanner([Link]);
int sno;
String sname;
int em;
int tm;
int hm;
int mm;
int scm;
int som;
int tot;
double avg;
String res;
public void input( )
{
[Link]("Enter Student Number, Name");
sno = [Link]( );
sname = [Link]( );
[Link]("Enter English, Telugu, Hindi Marks");
em = [Link]( );
tm = [Link]( );
hm = [Link]( );
[Link]("Enter Maths, Science, Social Marks");
mm = [Link]( );
scm = [Link]( );
som = [Link]( );
}
public void process( )
{
tot = em + tm + hm + mm + scm + som;
avg = tot / 6;
if(em >= 35 && tm >= 35 && hm >= 35 && mm >= 35 && scm >= 35 && som >= 35)
{
if(avg >= 80)
{
res = "Distinction";
}
else
if(avg >= 60)
{
res = "First Class";
}
else
if(avg >= 50)
{
res = "Second Class";
}
else
if(avg >= 40)
{
res = "Third Class";
}
else
{
res = "Ordinary Pass";
}
}
else
{
res = "Fail";
}
}
public void show( )
{
[Link]("Student Number : " + sno);
[Link]("Student Name : " + sname);
[Link]("Total Marks : " + tot);
[Link]("Average Marks : %.2f\n",avg);
[Link]("Result : " + res);
}
};
javac -d . [Link]
import [Link];
class PackDemo5
{
public static void main(String args[ ])
{
Stud ob = new Stud( );
[Link]( );
[Link]( );
[Link]( );
}
}
Access Specifiers
1) private
2) default
3) protected
4) public
Access Same class Same package Same package Other package Other package
Specifier sub class non sub class sub class non sub class
private yes no no no no
default yes yes yes no no
protected yes yes yes yes no
public yes yes yes yes yes
Multithreading
A thread is nothing but a method. By using multithreading concept we can execute multiple threads
simultaneously. By using this concept we can save time. Every thread have the following three
properties.
1) Thread group
2) Thread name
3) Thread priority
a) MIN_PRIORITY (1)
b) NORM_PRIORITY (5)
c) MAX_PRIORITY (10)
run( ) method is the heart and soul of thread class. The code will be placed inside the run( ) method.
When we call start( ) method of thread object, then it calls run( ) method of thread class.
import [Link];
class ThreadDemo1
{
public static void main(String args[ ])
{
PrintStream ps = new PrintStream([Link]);
Thread ob = [Link]( );
[Link]("Main thread details");
[Link]("Thread Group : " + [Link]( ) );
[Link]("Thread Name : " + [Link]( ) );
[Link]("Thread Priority : " + [Link]( ) );
[Link]("Sample");
[Link](10);
[Link]("Thread Name : " + [Link]( ) );
[Link]("Thread Priority : " + [Link]( ) );
}
}
Files
Files are used to store data permanently. To perform file operations we need the following streams.
1) FileOutputStream
2) FileInputStream
Both above streams are available in [Link] package. Both above streams throw FileNotFoundException.
import [Link].*;
class File1
{
public static void main(String args[]) throws FileNotFoundException, IOException
{
FileOutputStream fos = new FileOutputStream("[Link]");
[Link]('K');
[Link]( );
}
}
import [Link].*;
class File2
{
public static void main(String args[]) throws FileNotFoundException, IOException
{
FileOutputStream fos = new FileOutputStream("[Link]",true);
[Link]('V');
[Link]( );
}
}
import [Link].*;
class File3
{
public static void main(String args[]) throws FileNotFoundException, IOException
{
FileInputStream fis = new FileInputStream("[Link]");
int t;
t = [Link]( );
[Link]((char)t);
t = [Link]( );
[Link]((char)t);
[Link]( );
}
}
import [Link].*;
class File4
{
public static void main(String args[]) throws FileNotFoundException, IOException
{
FileOutputStream fos = new FileOutputStream("[Link]");
char t;
[Link]("Enter text, ends with *");
while(true)
{
t = (char) [Link]( );
if(t == '*')
break;
[Link](t);
}
[Link]( );
}
}
import [Link].*;
class File5
{
public static void main(String args[]) throws FileNotFoundException, IOException
{
FileOutputStream fos = new FileOutputStream("[Link]",true);
char t;
[Link]("Enter text, ends with *");
while(true)
{
t = (char) [Link]( );
if(t == '*')
break;
[Link](t);
}
[Link]( );
}
}
Reading continuous text from a file
import [Link].*;
class File6
{
public static void main(String args[]) throws FileNotFoundException, IOException
{
FileInputStream fis = new FileInputStream("[Link]");
int t;
[Link]("Data from [Link]");
while(true)
{
t = [Link]( );
if(t == -1) // -1 : End of File
break;
[Link]((char)t);
}
[Link]( );
}
}