Java Guide
Java Guide
Features of java:
The features of any program language (or) their facilities (or) services provide by
the language.
The various features of java language are
1. Simple:
The learning and implementation of java language is simple based on the
following reasons.
* The syntax of java language is similar to other language like C, C++.
* The complex topics like pointers, templates of other languages are eliminated in java language
making it a simple program language. The pointer concept will head to confusion & they are
threat to the data.
* In java language the deallocation of the memory is done automatically by garbage collector &
as a programmer we need not worry about memory deallocation.
Object Oriented:
Java language is an object oriented program language. Any object oriented
program language will develop an application with the help classes and objects.
* An object can be anything that exist physically in the real world which requires some memory
(or) space.
* Every object will contain some properties & some actions. Using the properties we can
describe the object & the actions represents task performed by the object.
* A class can be considered as a plan (or) a model (or) a blueprint for creating the objects.
* A class doesn’t exist physically but it provides a logical explanation to the objects. For a class
we can create any number of objects.
* A class is a collection of common features of a group of objects.
class: student
object: surendra, srikanth, venkat etc.(Ex)
class: movie
object: Gamyam, Bommarillu etc.
Secured:
Security is one of the most important principle of any programming language.
When we develop applications in java, we need not specially provide any security programs for
protecting the data from unauthorized usage because the java language comes with by default
security programs. But in C++, we have to write security program to protect the data.
Robust:
The java language is said to be a robust (or) strong program language based on
the following reasons.
1. Memory Management:
The memory management in java is very efficient because there will be no
wastage of memory at the time of allocation and the unused memory will be deallocated
immediately by the garbage collector.
2. Exception Handling:
The errors that occur at the time of execution (Runtime Errors) are called
exceptions & the process of handling those errors is called as Exception Handling, which is very
efficient in java.
Distributed:
The java language is said to be a distributed language. With the help of this
distributed nature we can access the data available in multiple machines and provide it to the
user. Using the distributed nature we can improve the performance because of the more
availability and more accessibility of the data.
Platform Independent (or) Architecture Neutral:
The java language is said to be a platform independent language because it can be
executed on any machine irrespective of the operating system, their architecture, their hardware
(or) s/w etc.
When a ‘C’ program is compiled, the compiler will convert the ‘C’ language
instructions into machine level instructions. The machine level instructions generated by ‘C’
compiler can be executed only on that machine where it is compiled. If we want to execute on
another machine then we have to compile it once again. This nature of ‘C’ language makes it
“machine dependent”.
When a java program is compiled, the compiler will generate byte code
instructions which are called as Special java instructions.
Dynamic:
The location of the memory in java language will be done at the time of
execution.
In C, memory allocation will be done at the time of compilation.
Every java program will have the extension has [.java].
The [.java] file developed by the programmer will be provided to the compiler. The compiler
will take the (.java) file and verifies whether the java code is valid (or) not, if valid the compiler
will generate a (.class) file containing byte code instructions (Special java instructions)
The (.class) file generated by the compiler will be provided to the JVM for the execution.
JVM Architecture:
The .class file will be provided as input to the class loader subsystem. The class
loader subsystem will perform the following operations.
* The class loader subsystem will load the (.class) file into the JVM.
* Before loading the (.class) file it will verify whether the bytecode is valid (or) not with the help
of bytecode verifier.
* If the bytecode is valid then it will load bytecode in different locations called as Runtime Data
Areas.
The various Runtime Data Areas are:
1. Method Area:
This area can be used for storing all the class code and the method code.
2. Heap:
This area can be used for storing the objects.
3. Java Stack:
This area can be used for storing all the methods that are required for execution.
The java stack can be considered as a collection of frames where each frame will contain the
information of one method.
4. PC Register (Program Counter):
This register will contain the address of the next instruction that has to be
executed.
5. Java Native Stack:
This area can be used for storing all the non-java code (Native code).
Execution Engine:
The execution engine is responsible for executing the byte code available in
runtime data areas. The execution engine contains two parts:
1. Interpreter.
2. JIT compiler (Just In Time).
Both the pass of the execution engine are responsible for executing the code
simultaneously which reduces the execution time & there by improves the performance of the
application.
The bytecode available in the runtime data areas will be shared by the interpreter
and JIT compiler. Most of the code will be used for executing the code whenever required.
The code executed by the JIT compiler is called as HOTSPOTS.
Native Library:
This interface will help the JVM to load the native library into the runtime data
errors.
OS:
The JVM has to interact with the operating system so that it can use the resources
available in that machine.
Note:
The bytecode available in (.class) file can be executed on any machine with the
help of JVM.
Comments:
The comments are used for explaining the code or they make the code more
understandable. The comments in a program will improve the readability of the code. Comments
are not part of the logic, they are non-executable statements.
In java language we have different types of comments. They are
1. Single Level Comments:
The single level comment can be used for writing a comment in a single line. The
single line comments begins with”//” symbols & end in the same line.
Ex: //this is a single line comment.
2. Multiline Comment:
Multiline comments can be used for writing the comments in multiple lines. The
multiple comments begins with “/*” ends with “*/”.
Ex:
/* this is a line one comment
this is a line two comment
this is a line three comment */
These comments can begin in a line & end in any other line.
Single line & multiple comments are used purely for explaining the code only.
Multiple Comments:
These comments can be used for creating a document (Manual) for the software
that is developed i.e., using these comments we can create an API (Application Programming
Interface). These comments will begin with”/**” & ends with “*/”. These comments can begin
& end in any line.
Syntax: /**
Author: Srikanth
Created on:
Last modified on: */
(What are the classes & methods are used everything will
be describing about prg (or) software)
DATA TYPES
Data types will represent the type of data that can be stored into a memory location.
The data types in java can be classified into three types
1. Primitive Data Types:
These data types are predefined and they are designed to store a single value.
Ex: int char
2. Derived Data Types:
These data types are predefined and they are designed to store multiple values.
Ex: array
3. User Defined Data Types:
These data types are created by user or programmer according to the application
requirement. The user defined data type can contain any no of values and they can be of any
type.
Ex: class
1. Primitive Data Types:
These data types are predefined and they are used for sharing basic inputs
required for a program. These data types are also called as fundamental data types which can be
used for storing a single value.
The java language provides eight primitive data types classified into 4 categories.
i. Integer Category
ii. Floating point Category
iii. Character Category
iv. Boolean Category
i. Integer Category:
This category is used for storing numbers which can be either +ve or –ve without
decimal point. Under the integer category we have four primitive data types. They are
a) byte
b) short
c) int
d) long
The purpose of all the 4 types under integer category is to store same kind of data but
their size and ranges are different so that the memory can be utilized efficiently.
Data Type Size Range
byte 1byte -128 to 127
short 2bytes -32768 to 32767
int 4bytes -2147483648 to 2147483648
long 8bytes -9223372036854775808 to
9223372036854775807
Variable Declaration:
The process of specifying what type of data is to store into the memory is called as
variable declaration.
Syntax:
datatype variablename;
datatype var1,var2,var3,….;
Ex:
int age;
int rollno,accno;
double marks;
char grade;
boolean result;
When a variable is declared, the memory for the variable will be allocated and it
can contain some data. The amount of memory allocated to a variable will depend upon the data
type that is specified.
Once the memory for the variable is allocated it can hold some data. If we do not
provide any value to a variable then the memory location will automatically contain default value
of variable type.
Default Values
byte - 0
short - 0
int - 0
long - 0
float - 0.0
double - 0.0
char - space
boolean - false
string - null
student - null
Any class – null
If a variable is declared and if we do not provide any value then the variable will be
automatically initialized with their default value. If we do not want default values then we can
initialize the variable with our own values at the time of declaration.
Syntax:
datatype variablename;
datatype var1,var2,var3,….;
Initialization:
Process of providing value to a variable for the first time is called initialization. The value
of a variable can be changed any no of times during the execution of the program.
Assignment:
Process of providing value to a variable for the second time is called assignment.
Syntax:
int age = 20; Initialization
age = 21; Assignment
age = 22; Assignment
int rollno = 123;
double marks = 98.76;
char grade = ‘A’;
boolean result = false;
Keyword:
Words that are predefined meaning in java are whose meaning is already reserved
are called as keywords.
Literal:
Value that we store in the variable are called literals.
Identifier:
Any name that is used for the purpose of identification will be called as identifier.
* The package statement is an optional statement. A java program can contain atmost one
package statement. The package statement should be first executable statement in a java
program.
* The import statement is an optional statement. A java program can contain any no of import
statements. The import statement must be specified after the package statement before the class.
* Java program can contain any no of classes. Every class can contain variables & methods
which are together called as members of the class. A class can contain any no of variables & any
no of methods.
* The execution of a java program is done by main methods whose syntax must be as follows:
* The main method can contain any no of statements. A java program can have any no of
commands and they can be specified anywhere in the program. The comments are non-
executable statement of java program.
Syntax:
Set PATH = java installation folder
Set PATH = c:\program files\java\jdk1.6.0_12\bin;
* Setting the path means proving the address to java installation to OS.
Program 2:
Class secondprogram{
Public static void main(String[] arg){
System.out.println(“this is my second”);
System.out.println(“java program”);
System.out.println(“at inetsolv”);
}
}
* Based on the no of operands the operator considers they are classified into following
categories.
1. Unary Operators:
These operators will perform operations on single operand.
2. Binary Operators:
These operators will perform operations on two operands.
3. Ternary Operators:
These operators will perform operators on three operands.
* The operators of java language are classified into various categories based on task they
perform.
1. Arithematic Operators:
These operators can be used for calculating mathematical operations. The various
arithematic operators are
i. Addition (+)
ii. Subtraction (-)
iii. Multiplication (*)
iv. Division (/)
v. Modulus (%)
* If both operands are of integer type the result will be integer.
* If any one of operand is of float type the result is float.
Ex: 7 + 2 = 9
7-2=5
7 * 2 = 14
7 / 2 = 3 or 7 / 2.0 = 3.5
7%2=1
* An arithematic expression will be evaluated from left to right.
int x=10; O/P : 10
int y=x * 3 – 2; O/P : 28
* We can change order of evaluation by changing pair of parenthesis.
int x=10; O/P : 10
int y=x * (3 – 2); O/P : 10
* The arithematic expression will be evaluated from left to right. If operators have same
precedence otherwise evaluate the higher precedence operators first and then lower precedence
operators.
* The arithematic operators
* / % higher precedence
+ - lower precedence
Ex: int x=10; O/P: 10
int y=x * 5 / 2; O/P : 25
Ex: int x=10; O/P: 10
int y=x - 5 / 2; O/P : 8
2. Unary Operators:
These operators will perform operations on single operand.
The various unary operators are -, ++, --.
i.Unary Minus (-):
Converts positive to negative & negative to positive.
Ex: int temp=23;
int temp= -23;
int temp= -(-23);
ii. Increment Operator (++):
This operator will increment value by 1.Based on the position of increment operator the
increment operator is classified into two types.
a) Pre-increment operator:
If increment operator is placed before the variable is called pre-increment
operator (++x). The pre-increment value will use the value after increasing it.
b) Post-increment operator:
If increment operator is placed after the variable is called post-increment operator
(x++). The post-increment value will use the value before increasing it.
ii. Decrement Operator (++):
This operator will decrement value by 1.Based on the position of decrement operator the
decrement operator is classified into two types.
a) Pre-decrement operator:
If decrement operator is placed before the variable is called pre-decrement
operator (--x). The pre-decrement value will use the value after decreasing it.
b) Post-decrement operator:
If decrement operator is placed after the variable is called post-decrement
operator (x--). The post-decrement value will use the value before decreasing it.
Ex:
Class Operators {
Public static void main(String[] args){
int a=7; //8 9
int b=++a; //8 7 6
int c=b--; //8 7
int d=a++ + --b - --c; //8 + 6 - 7 7
System.out.println(a);
System.out.println(b);
System.out.println(c);
System.out.println(d);
}
}
* The increment & decrement operators can be applied to all numeric data types. The numeric
data types are byte, short, int, long, double, float and char.
* Increment & decrement operators can be applied to only variables.
* Increment & decrement operators cannot be nested.
Ex: (++(++a));
3. Assignment Operators:
This operator is used for assigning value to a variable. The assignment operator is =.
* This operator will copy value from right to left.
* On the right side we can specify either a value (or) variable (or) an expression but left side we
can specify only variable.
x=5
y=x
z=x + y
* If the assignment operator is combined with other operator it is called compound assignment
operators.
+= , -= , *= , /= , %= .
Ex: x=x+3 x+=3
y=y-2 y-=2
4. Relational Operators:
These operators can be used for comparing the values. These operators are also called as
comparision operators.
The various relational operators are >, >=, <, <=, ==,! =.
* Using the relational operators we can create conditions.
** The result of all relational operators is of boolean type. If the condition is satisfied the result
is true otherwise false.
Rules:
* The relational operators <, <=,>,>= can applied to any combination of only numeric types.
* The relational operators ==,!= are also called equality operator .The equality operator are
applied to any combination of integer or boolean type.
5. Logical Operators:
These operators are used for combining or complementing result of a condition. The
various logical operators are &, &&,|, ||, ^, !.
* The result of all logical operators is of boolean type. i.e. Either true (or) false.
& (Single Ampercent)
This operator is used for combine multiple conditions.
Syntax: cond1 & cond2
* The result of & operator will be true only when all the conditions are true.
* The & operator will evaluate all the conditions then decide the result.
|| (Double Pipe)
This operator is used for combining multiple conditions.
Syntax: cond1 || cond2
* The result of double pipe operator will be true if atleast one of the condition is true.
* The single pipe operator will evaluate the first condition if the result of first condition is true
then it will skip the evaluation of remaining conditions provides the result as true.
* If the result of the first condition is true then it will evaluate the remaining conditions.
* The double pipe operator will improve the operator sometimes when the result of first
condition is true.
^ (Exclusive OR)
Used for combining multiple condition.
Syntax: cond1 ^ cond2
* The result of ^ operator will be true if the result of the condition are different.
! (Not)
This operator will complement the result of condition.
Syntax: ! (cond)
6. Bitwise Operators:
These operators will perform operations on bits of an number. The various bitwise
operators are ~, &, |, ^, >>, <<, >>>.
~ (Tilde):
This operator will convert bits from one to zeros and 0’s to 1.
~x = - (x + 1)
| (Bitwise |):
This operator will perform operation on bits of a number.
^ (Bitwise ^):
This operator will perform operation on bits of a number.
Ex:
* Shifting the bits of a number towards left side by 1 position multiplying number by 2.
>> (Right Shift)
This operator will shift bits of a number towards right side by the specified no of
positions.
Ex:
* Shifting the bits of a number towards right side by 1 position dividing number by 2.
8. New Operator:
New operator is used for creating an object of a class means allocating memory
for members of class in the heap memory.
Ex: Class Sample{
}
Sample s = new sample();
* For every class in java language we can create any no of objects.
* Using new operator we can create object for any predefined or user defined class.
* S is called reference variable because they point to refer to object of the class.
* The name of the reference variable can be any valid java identifier.
9. Dot (.) Operator:
The dot operator can be used for accessing the members(variables,methods) from
a class from a package.
className.variable
reference.variable
className.method
reference.method
Package.className
Control Statements
The statements of a java program will always be executed in sequential order. If
we do not want to execute the statements in a sequential order then we need to take the help of
control statements.
The control statements will help the programmer to decide the flow of execution
in a program.
The control statements are classified into following categories.
1. Conditional Statements
1.1 if-else statement
1.2 Switch statement
2. Iterating Statements
2.1 for loop
2.2 while loop
2.3 do-while loop
2.4 for-each loop
1. Conditional Statements:
These statements can execute a group of statements based on a condition or a value.
1.1 If else statement:
The if-else stmt can be used for executing a group of statements based on
condition.
Syntax: if(condition){
Stmt1
}
else {
stmt2
}
* If the condition is satisfied then if block will be executed and if the condition is not satisfied
then execute else block.
Ex:
Class IfElseDemo
{
Public static void main (String [] args)
{
int n=2;
if (n%2=0)
{
System.out.println(“Even Number”);
}
else
{
System.out.println(“Odd Number”);
}
}
}
Rules:
* Specifying condition to the if statement is mandatory and it should be only Boolean type.
* Specifying an else block is optional.
* Specifying flower braces is optional. If we do not specify flower braces then it will consider
only one statement and that one statement is mandatory. If we want to consider multiple stmts
then specify the flower braces is mandatory and within the flower braces we can specify any no
of stmts (0 or more).
* In if-else stmt we can execute exactly one block either if block or else block. There is no
chance of slipping both the blocks and no chance of executing both the blocks.
* Switch argument & continues until it encounters a break statement (or) teachers end of the
switch statement.
* The break statements is a transfer statement which will transfer from inside switch to outside.
So that it stops (or) skips the execution of remaining cases. So that remaining statements are not
executed.
* Replacing switch with else if ladder.
Class SwitchDemo{
Public static void main(String[] args){
int ch=2;
if(ch==1){
System.out.println(“first choice”);
}
if(ch==2){
System.out.println(“second choice”);
}
if(ch==3){
System.out.println(“third choice”);
}
if(ch==4){
System.out.println(“fourth choice”);
}
else{
System.out.println(“wrong choice”);
}
}
}
O/P: Second choice
Replacing switch with else if ladder is not recommended to reduce the readability of the
program.
Iterating statements:
The iterating statements can be used if we want to execute a group of statements
repeatedly multiple times.
1. For Loop:
Purpose: A for loop has to be used if we want to execute a group of statements multiple
times & it should be used when we know the exact number of iterations.
Syntax:
2. while loop:
While loop can be used for executing a group statements responsibility multiple
times. The while loop should be used when we don’t know the exact no of iterations.
Syntax: while(condition)
{
Statements
}
do-while loop:
The loop can be used for executing a group of statement repeatedly multiple
times. This loop should be used when we donot know the exact no of iterations.
Syntax:
do
{
Statements
} while(condition);
Program: To write multiplication table using do while loop.
class DoWhileDemo
{
public static void main(String[] args)
{
int n=8, i=10;
do
{
System.out.println(n+"*"+i+"="+(n*i));
i--;
}while(i>=1);
}
}
Difference between while & do-while loop?
* In a while loop, the statements will be executed after the condition is checked. Where as in a
do-while loop, the statements will be executed before the condition is checked.
* In a while loop, if the condition is false for the first time then the statements will not be
executed where as in a do-while loop, if the condition is false for the first time then the
statements will be executed for one time.
* In a while loop, the statements will be executed for 0 (or) more times. In a do-while loop, the
statements will be executed for 1 (or) more times.
*
**
***
****
*****
Transfer Statement:
The transfer statement can be used for transferring the control from one location
to another location.
1. Break Statement:
The break statement can be used either in switch (or) in loops. The purpose of
break statement in switch is to transfer the control from inside the switch to outside the switch.
So that it skips the execution of remaining cases.
The purpose of break statement in a loop is to transfer the control from inside the
loop to outside the loop so that it skips the execution of remaining iterations.
Ex:
class BreakDemo
{
psum(String[] args)
{
int sum=0, capacity=234;
for(int i=1;i<=10;i++)
{
System.out.println(i);
sum=sum+i;
if(sum>=capacity)
break;
}
System.out.println(sum);
}
}
O/P: 1
2
3
'
'
'
13
sum=--
*
**
***
****
*****
class pyramid1
{
psum(String[] args)
{
for(int i=1; i<=5; i++)
{
for(int j=1; j<=i; j++)
{
System.out.println("*");
}
System.out.println();
}
}
}
*****
****
***
**
*
class pyramid2
{
psum(String[] args)
{
for(int i=1; i<=5; i++)
{
for(int j=1; j<=5; j++)
{
if(i<=j)
System.out.println("*");
}
else
{
System.out.println("-");
}
System.out.println("-");
}
System.out.println();
}
}
}
2. Continue Statement:
The continue statement can be used for skipping the current iteration &
continuing with the next iteration.
Ex:
class continueDemo
{
psum(String[] args)
{
for(int i=1; i<=10; i++)
{
if(i==7|i==3)
continue;
System.out.println(i);
}
}
}
O/P: 1
2
4
5
6
8
9
10
Note: It is recommended to use the break & continue statement along with a condition.
ARRAYS
Array:
If an application requires multiple values then we can store those multiple values
by declaring multiple variables in a program. If the no of variables are increased in the program
then the code size will increase & it will reduce the readability of the code.
* To reduce the code size & to improve the readability of the code, we take the help of the
concept called an “Array”.
* An array is a derived data type using which we can store multiple values.
The arrays are classified into two types.
1. Single Dimension Array
2. Multi Dimension Array
1. Single Dimension Array:
Single Dimension Array can be used for representing a group of values either a
single row (or) single column.
Syntax:
datatype arrayname[];
* To represent an array we take the help of square braces[]. Each pair of square braces represents
one-dimension.
Rules:
* The pair of square braces can be specified either before the array name (or) after the array
name.
int rollNo[];
float[] percent;
char [] grade;
boolean result[];
* We must not specify the size of the array at the time of array declaration
boolean result[5];
* Percent is an array name where we can store multiple values of float datatype.
* The name of the array can be any valid java identifier.
int x[];
* Syntax for creating an array. We can use any way of both the two types.
1. datatype arrayname[] = new datatype[size];
or
2. datatype arrayname[];
arrayname = new datatype[size];
Ex: 1. int arr[] = new int[5];
or
2. int arr[];
arr = new int[5];
* At the time of array creation, specifying the size of the array is mandatory & it should be of
either byte (or) int (or) char type.
Ex: byte x = 10;
int y = 10;
long z = 10;
int[] arr1 = new int[x]; //valid because of byte type
int[] arr2 = new int[y]; //valid because of int type
int[] arr3 = new int[z]; //invalid because of long type
int[] arr4 = new int[10]; //valid because of int type
int[] arr5 = new int[-10]; //invalid [ Negative array size exception]
int[] arr6 = new int[1.0]; //invalid because of float
int[] arr7 = new int[‘z’]; //valid because of char
int[] arr8 = new int[0]; //valid but no result
int[] arr9 = new int[]; //invalid because of boolean
int[] arr10 = new int[]; //invalid because of size is missing
* When an array is created, the memory for that array will be allocated in continuous memory
locations. The allocation of the memory will be based on type of the array & size of the array.
* An array is a collection of multiple elements & to access those elements we take the help of
index positions.
* The index of an array always starts with ‘0’.
* The range of the index will be 0 to [size-1] why starts with ‘0’ means to reduce the wastage of
memory of ‘0’ if they starts with “1”.
* Once the memory for the array is allocated, all the elements in that array will be initialized
automatically with default values of the array type.
* Every array is internally an object which provides a variable called “length” which will specify
the size of the array.
Syntax for accessing the array elements:
arrayname[index]
Syntax for assigning the array elements:
arrayname[index] = value;
Ex: arr[0] = 11;
Note:
If we specify an index position which is outside the range of the array index then
we get a runtime error called as “ArrayIndexOutOfBandsException”.
Example:
Class Student{
Psum(String[] args){
int marks[];
marks = new int[5];
marks[0] = 99;
marks[1] = 100;
marks[2] = 94;
marks[3] = 39;
marks[4] = 90;
int total = 0;
boolean result = true;
for(int i=0;i<marks.length;i++){
System.out.println("subject"+(i+1)+"marks:"+marks[i]);
Int[] arr; 2
arr = new int[6]; 3
arr[0] = 11; 4
arr[1] = 45; 5
arr[2] = 21; 6
arr[3] = 53; 7
arr[4] = 72; 8
arr[5] = 81; 9
Rules:
* At the time of array declaration we can specify the pair of square braces either before array
name (or) after the array name.
int arr1[][];
int []arr2[];
int [][]arr3; //All are valid.
int[] arr4[];
` int[][] arr5;
int[][] arr6;
* At the time of array declaration, we must not specify the size of the array.
* At the time of array creation, specifying the first dimension is mandatory & the remaining
dimensions are optional.
int [][]arr = new int[3][4];
(or)
int [][]arr;
arr = new int[3][4];
* In multi dimensional array, the top level arrays will contain address of bottom level arrays.
* In a multi dimensional array, only the last level will contain values & remaining all top levels
will contain addresses.
* The bottom level arrays can contain either same number of elements (or) different number of
elements.
for(int i=0;i<arr.length;i++){
for(int j=0;j<arr[i].length;j++){
System.out.println(arr[i][j]+"");
}
System.out.println();
}
for(int[] x:arr){
for(int y:x){
System.out.println(y+"");
}
System.out.println();
}
}
}
Ex:
Integer.parseInt()
Float.parseFloat()
Double.parseDouble()
Long.parseLong()
Boolean.parseBoolean()
Short.parseShort()
Byte.parseByte()
Why should the main method take string array as the parameter?
If we pass int array to the main method then we can pass only integers, if we pass double
array to the main method, then we can pass only double, floating point values, if we pass boolean
array then we can pass boolean values but if we pass string array then we can pass integers,
floating points, boolean, character values. We can convert all values except character.
import java.io.*;
class Addition {
public static void main(String abc[])throws IOException
{
BufferReader br = new BufferReader(new
InputStreamReader(System.in));
System.out.println("Enter First Number");
string fno = br.readline();
int a = Integer.parseInt(fno);
System.out.println("Enter Second Number");
string sno = br.readline();
int b = Integer.parseInt(sno);
System.out.println("sum:"+(a+b));
}
}
String
* The string is a predefined used for storing group of characters.
* The string class objects can be created in two ways.
i. by using new operator
String str = new String(“hello”);
ii. by enclosing group of characters directly within double codes.
String str = “hello”;
* The string objects created by both the mechanisms are immutable objects. Once the string
object is created which we cannot modify the content of the object, but the reference of the string
object can be modified.
String s1 = new String(“hai”);
s1 = new String(“bye”);
* If we create a string object by enclosing group of characters directly within “ ” then we store
only in string constant pool.
3. String Concat(string):
This method can be used to append the contents of one string to another string.
Ex:
String s1 = new String(“java”);
String s2 = new String(“program”);
System.out.println(s1.concat(s2));
System.out.println(s1);
System.out.println(s2);
O/P: java program
java
program
4. int CompareTo(String):
This method can be used for comparing the unicode values of the characters
available in the string. This method will do the comparision by considering their case.
S1 < S2 -ve
S1 > S2 +ve
S1 == S2 0
5. int CompareToIgnoreCase(String):
This method can be used for comparing the unicode values of the characters
available in the string. This method will compare by ignoring their case.
Ex:
String s1 = new String(“A”);
String s2 = new String(“a”);
System.out.println(s1.compare(s2));
System.out.println(s1.compareToIgnoreCase(s2));
O/P: -32
0
6. boolean equals(String):
This method can be used for comparing contents of the strings by considering
their case.
7. boolean equalsIgnoreCase(String):
This method can be used for comparing contents of the strings by ignoring their
case.
Ex:
String s1 = new String(“ABCD”);
String s2 = new String(“abcd”);
System.out.println(s1.eqals(s2));
System.out.println(s1.equalsIgnoreCase(s2));
O/P: false
True
8. boolean startswith(String):
This method can be used to check whether a string begins with specified string or
not.
9. boolean endswith(String):
This method can be used to check whether a string ends with specified string or
not.
Note: start with method & ends with methods are case sensitive.
Ex:
String s = new String(“java program”);
System.out.println(s.startswith("jav"));
System.out.println(s.startswith("JAV"));
System.out.println(s.endswith("ram"));
O/P: true
false
true
10. int indexOf(char):
This method will return the index of the first occurrence of the specified
character.
class Test{
public static void main(String[] args){
String str = "hello";
System.out.println(str);
System.out.println(str+1+2+3);
System.out.println(1+str+2+3);
System.out.println(1+2+str+3);
System.out.println(1+2+3+str);
System.out.println(str+(1+2+3));
System.out.println(1+str+(2+3));
System.out.println((1+2)+str+3);
System.out.println((1+2+3)+str);
}
O/P: hello
hello123
1hello23
3hello3
6hello
hello6
1hello5
3hello3
6hello
2. StringBuffer append(xxx):
This method can be used for appending the specified existing string buffer
content.
Ex:
String sb = new StringBuffer(“java”);
System.out.println(sb.append(1.6);
System.out.println(sb.append("program"));
3. StringBuffer deleteCharAt(int index):
This method will delete available at the specified index position
9. StringBuffer reverse():
This method can be used for reversing contents of string buffer.
Ex:
String sb = new StringBuffer("java1.6program”);
System.out.println(sb.reverse());
O/P: margorp6.1avaj
OOPS
Object Oriented Programming Concept:
An application developed in any language has to use one of the following concepts.
1. Procedure Oriented Programming Concepts
2. Object Oriented Programming Concepts
1. Procedure Oriented Programming Concepts:
The applications that are developed by using the concept of procedure or functions are
said to use procedure oriented programming concepts.
Examples of using POPC:
C, COBOL, FORTRAN, PASCAL follow popc.
Drawbacks (or) Limitations for Procedure Oriented Language:
* The application that are developed by using popc are difficult to maintain and debugging of the
application will take more time.
* The procedure oriented programming language gives more importance to the functions than to
the data.
* The application that are developed by using popc does not provide security to the data.
* The data available in the application developed by popc is open and they are accessible to the
entire application which is not suitable for developing distributed applications.
* The application that are developed by using popc are difficult to enhance.
* The procedure & functions used in procedure oriented language are the fundamental entities
for developing the application. The design of these fundamental entities is very week & they are
not suitable for developing complex & real time applications.
Note: The procedure oriented programming languages are also called as structured programming
languages.
Class:
A class is a specification of common properties & common actions of group of objects.
* A class can be considered as model or a plan or blueprint for creating the object.
* Without a class object creation is not possible.
* For every class we can create any no of objects. Even though C++ is an object oriented
programming language according to the programming language experts it is called partial object
oriented programming language because of following reasons.
i. In a C++ application we can write some code inside the class & outside the class.
ii. In a C++ language we can develop application without using any of the object oriented
programming concepts.
iii. In a C++ application using the concept of friend function we can violate any level of security.
iv. All the object oriented programming concepts are derived from the real world from the
human being lives so that the programmer understands the concept easily & implementation of
that concept will not be difficult.
v. The design of the oopc is very strong & they can be used for developing real time complex
application.
The various object oriented programming concepts are
1. Encapsulation
2. Abstraction
3. Inheritance
4. Polymorphism
1.Encapsulation:
The process of binding the variables & methods into a single entity is called as
encapsulation.
* We can achieve encapsulation in java program by using a class.
* Using encapsulation we can improve maintainance of application.
* Using encapsulation we can also achieve data hiding.
* Using encapsulation we can separate or isolate members from one class to another class.
2. Abstraction:
The process of hiding some information & presenting the required information is
called as abstraction.
* Using abstraction we achieve security i.e., we can protect the data from unauthorized usage.
3. Inheritance:
The process acquiring the members from one class to another class is called as
inheritance.
* Using inheritance we can achieve reusability, which will reduce the development time of the
application.
4. Polymorphism:
If a single entity shows multiple behaviors then it is called polymorphism.
* Using polymorphism we can achieve flexibility where a single entity can perform different
operations according to the required.
Class:
A class is a user defined data type using which we can store any no of values.
Syntax for declaring a class:
Class<className>{
datatype variable1;
datatype variable2;
datatype variable3;
returntype methodName1(parameters){
statements
}
returntype methodName1(parameters){
statements
}
:
}
Default Values
byte - 0
short - 0
int - 0
long - 0
float - 0.0
double - 0.0
char - space
boolean - false
string - null
student - null
Any class – null
It is the responsibility of the JVM for calling the main method & execution begins
from main method.
* If the class contains other methods then it is the responsibility of the programmer to call other
methods.[s.display()]
O/P: rollNo : 0
marks : 0.0
name : null
* Every class in java language will be represented in the form of a class diagram. A class
diagram will be represented in rectangular shape, divided into multiple partitions (3) as follows.
* Every class can contain variables & methods which are called as members of a class.
Variables:
The purpose of variable is to store (or) hold some data (or) value. A java program can
contain any number of variables.
* The declaration of the variables in a java program is dynamic i.e.,we can declare the variables
anywhere in the class.
* The java language is said to be strongly typed language. Any language can be said to be
strongly typed language if the variables are first declared & then used & the compiler for type
compatibility.
int x = 12; //valid
int x = true; //invalid incompatable
Methods:
The purpose of a method is to perform some task/operation.
* A java program can contain any no of methods. Inside the method, we can specify any no of
statements.
Syntax: returntype methodName(list of parameters){
Statements
}
* Every method available in a program will be divided into two parts.
1. Method Declaration/Header/Prototype
2. Method Definition/Body/Implementation
1. Method Declaration/Header/Prototype:
The method declaration includes three parts & they are
1 2 3
returntype methodName (list of parameters)
* The returntype & methodName is mandatory whereas the list of parameters is optimal. We can
pass any number of parameters & they can be of any type separated by a comma symbol.
* The return type of a method must be specified just before the method name.
* If we do not want the method to return any value then the return type of the method must be
specified as void. If we want the method to return a value then we should not specify the return
type as void. In that location, we can specify any datatype.
2. Method Definition/Body/Implementation:
The method definition includes a group of statements specified within the flower
braces.
{
Statements
}
* The method definition can contain any no of statements.
* If the method definition doesn’t contain any statements, then we call such kind of methods as
empty definition (or) null implementation.
* If the method declaration contains return type as void, then we must not specify return
statement in the method definition. But if the return type is not void, then we must specify return
statement in the method definition.
Syntax: return value;
Ex: return 123;
return 12.3;
return true;
return ‘d’;
return “hello”;
* The return statement will be generally specified as the last statement in the method definition
but it can be specified anywhere in the definition.
* A method can return atmost one value.
Types of methods:
1. Methods without returntype & without parameters:
class Addition {
void add {
int x = 12;
int y = 13;
int z = x+y;
System.out.println(“ sum of ” +x+ ”and” +y+ “is:” +z);
}
Public static void main(String[] args){
Addition a = new Addition();
a.add(); //method invocation (calling add method)
}
}
class Addition{
void add(int x, int y){
System.out.println("sum of"+x+ "and" +y+ "S:" +(x+y));
}
Psum(String[] arr){
Addition a = new Addition();
a.add(2,3);
(or)
Addition a = new Addition();
int m = Integer.parseInt(arr[0]);
int n = Integer.parseInt(arr[1]);
a.add(m,n);
}
}
3. Methods with returntype & without parameters:
class Addition {
int add() {
int x = 10;
int y = 20;
int z = x+y;
}
public static void main(String[] args){
Addition ad = new Addition();
int res = ad.add();
System.out.println("sum is:"+res);
}
}
class Addition{
int add(int x, inty){
return(x+y);
}
Psum(String[] arr){
Addition ad = new Addition();
int res = ad.add(3,4);
System.out.println("sum is:" +res);
res = ad.add(5,6);
}
}
Why should we write logic in separate methods?
When we write the logic in separate methods we will be able to achieve Modular
Approach. Using the modular approach we can achieve reusability & reduce the development
time.
Recursion:
Recursion means calling the same method itself multiple times then we call it as
recursion & that method is called as recursive method.
class Factorial{
int fact(int n){
if(n == 1)
return 1;
int f=1;
f = n * (fact(n-1));
return f;
}
psum(String[] ar){
factorial f = new factorial();
for(int i=1;i<=10;i++){
int res = f.fact(i);
System.out.println(i+"!=" +res);
}
}
}
Java stack if n = 6 (6!)
class Sample{
void display(int[] nos){
for(int x: nos)
System.out.println(x);
}
Psum(String[] arr){
Sample S = new Sample();
int[] arr1 = {10,20,30,40,50};
S.display(arr1);
int[] arr2 = {100,200,300,400};
S.display(arr2);
}
}
Program to pass an object as a parameter to a method:
class Student{
int rollNo = 12;
double marks = 99;
}
class Display{
psum(String[] arr){
Display d = new Display();
Student S = new Student();
d.Show(S);
}
void show(Student Stu){
System.out.println(Stu.rollNo);
System.out.println(Stu.marks);
}
}
Constructors:
If a variable is declared inside the class & outside the methods then such kind of
variables are called as instance variables.
* If any instance variable is declared & not initialized then it will be automatically initialized
with default values.
* If we do not want the default values, then we can initialize the instance variables with our own
values in the following two locations.
1. At the time of declaration.
2. By using the constructor.
Constructor:
A constructor can be considered as a special method whose purpose is to initialize
the instance variables.
Rules:
* The name of the constructor name must be same as that of class name. (i.e., classname &
constructor name must be exactly same).
* A constructor should not contain any return type, not even void.
Note: If we specify a return type before the constructor then the code is valid but it will be
considered as a method not a constructor.
* A constructor can be executed at the time of object creation.
* A constructor will be executed one time for one object. (It create 10 objects, 10 times
constructor will be executed)
* A constructor can have parameters based on the no of parameters, constructors are classified
into two types.
1. Zero parameterized Constructor/Default Constructor.
2. Parameterized Constructor.
** Every class in java will contain a constructor whether we specify (or) not.
** If the programmer does not specify any constructor then the compiler will provide a zero
parameterized constructor.
class Sample{
int x; //declared but not initialized
int y=10; //declared & initalized at the time of declaration
int z; //declared & intialized by using constructors
Sample(){
z=10;
}
void Show(){
System.out.println(x);
System.out.println(y);
System.out.println(z);
}
Psum(String[] ar){
Sample S=new Sample();
S.show();
}
}
Psum(String[] ar){
Sample S=new Sample();
S.Show();
}
}
O/P: 0 10 20
Instance Variables:
If a variable is declared inside the class & outside the methods, then it is called as
instance variable.
* For every class, we can create any number of objects and every object will contain its own
copy of the instance variable.
* If an instance variable is declared & not initialized, then it will be automatically initialized with
default values.
* If we do not want the default values, then we can initialize the instance variables with our own
values, either at the time of declaration (or) by using any constructor.
* If we want all the instances(objects) to contain instance variables with same values then
initialize the instance variable either at the time of declaration (or) by using a zero parameterized
constructor.
* If we want all the instances (objects) to contain instance variables with different values then
initialize the instance variables by using a parameterized constructor.
“this” Keyword:
“this” keyword can be used to refer to the current instance (object) of the class.
* Using “this” keyword we can access the instance members (Variables & Methods) of the class.
Local Variables:
The variable which is declared inside the class & inside the blocks (Methods and
Constructors), then it is called as local variables.
* If there is no confusion between instance variable & local variable then specifying “this”
keyword is optional. In such case, if we do not specify “this” keyword before the variable so that
it refers to the instance variable.
* If there is confusion between instance variables & local variables then specifying “this”
keyword is mandatory. In such case, if we do not specify “this” keyword, compiler will not
specify “this” keyword then it gives preference to local variables.
* If we want to refer to the instance variable then the programmer has to explicitly specify “this”
keyword before the variable so that it refers to the instance variable.
class Student{
int rollNo;
Student(int rollNo){
this.rollNo = rollNo;
}
void display(){
System.out.println(this.rollNo);
}
Psum(String[] ar){
Student S1 = new Student(123);
S1.display();
Student S2 = new Student(456);
S2.display();
Student S3 = new Student(789);
S3.display();
}
}
Static Keyword:
* If an instance variable is declared in a class, then the memory for that instance variable will be
allocated one time for each object.
* If we do not want to allocate memory for a variable one time for each object then declare that
variable as “Static” i.e., preceed the instance variable declaration by “Static” keyword.
** If a static variable is declared then the memory for that variable will be allocated at class
loading time.
** The memory for the static variable will be allocated in method area.
** The memory for the static variable will be allocated only one time for the entire class.
All the objects of the class will share the same copy of the static variable. We can declare
both the variables & methods of a class as “Static” and they are together called as “Static
members”. The static members are also called as class members.
Syntax for Static Variable:
Static datatype varname;
Syntax for Static Method:
Static returntype methodName(list of parameters)
{
Statements
}
* The instance members(instance variables & static methods) of the class can be accessed only
by using reference variable.
* The static members(static variables & static methods) of the class can be accessed either by
using the reference variable (or) by using a classname.
* It is recommended always access the static members by using class name because we cannot
guarantee the existence of an object.
class Employee{
int empNo = 1234;
static int compcode = 2222;
psum(String[] args){
Employee e = new Employee();
System.out.println(e.empNo);
System.out.println(e.compcode);
System.out.println(Employee.compcode);
}
}
Rules:
* An instance methods can access both instance variables & static variables.
* A static method can access only static variables.
Ex: class Sample{
int x = 11;
Static int y = 22;
void show(){
System.out.println(x);
System.out.println(y);
}
Static void display(){
System.out.println(x);
System.out.println(y);
}
Psum(String[] ar) {
Sample S = new Sample();
S.Show();
Sample.display(); // (or) S.display();
* If the instance variables & static variables are not initialized, then they will be initialized
automatically with default values.
* For a static variable if we do not want the default value then we can initialize the same variable
without own value only at the time of decalaration.
class Student {
int m1, m2, m3;
Student(int int int)
main()
}
class result{
int calculatetotal(Student S)
}
Rules for accessing instance & static members:
* An instance method can access members (Instance variables & Instance methods) directly
provided if they belong to same class otherwise they must be accessed only by using reference
variable(object).
* An instance method (or) access static members (static variables & static methods) directly
provided they belong to same class otherwise they must be accesed either by using reference
variable (or) classname.
* A static method can access static members (static variables & static methods) directly provided
if they belong to same class otherwise they must be accessed either by using reference varaiable
(or) class name.
* A static method can access instance members (instance variables & instance methods) only
using reference variable object whether they belong to the same class (or) different class.
class calculate{
int netSalary(Employee)
}
class Display(){
main()
C.netSal();
}
Explain System.out.println(); :
“System” is a predefined class available in java.lang package.
“out” is a reference variable of printstream class referring to an object of print stream
class declared as “static” in system class.
“println” is a predefined instance method available in printstream class.
PrintStream is a predefined class available in java.io package.
* To access the “println” method we require an object of printstream class which is already
created & placed in system class.
“out” reference variable can be accessed directly by using class name because “out” is
declared as static(System.out)
“System.out” will provide the object of printstream class using which we can access
“println” method.
Predefined code:
java.lang
class System{
Static printStream out = new printSream();
}
java.io
class printStream{
void println() {
}
}
The reference variable of any class can be declared as either instance (or) static (or) local.
Ex: class Sample{
Sample S1 = new Sample(); //instance reference variable
Static Sample S2 = new Sample(); //static reference variable
void m1(){
Sample S3 = new Sample(); //local reference variable
}
}
S1 is instance reference variable
S2 is static reference variable
S3 is local reference variable
Local Variables:
If variable is declared inside the class & inside the blocks (methods (or)
constructors) then that variable is called as local variable.
class Sample{
int x = 10;
static int y = 20;
void Show(){
int z=30;
System.out.println(x);
System.out.println(y);
System.out.println(z);
}
Static public void main(String[] args){
Sample S = new Sample();
S.show();
}
}
O/P: 10
20
30
class product{
product(int price){
}
}
class Sample{
getproduct(int price)
class product{
int price;
product(int price)
{
this.price = price;
}
int calculateTotal(int quant){
return 120;
}
}
Final Keyword:
The purpose of a variable is to hold (or) store a value. The value of a variable can be
changed any number of times during the program execution.
* If we do not want to change the value of a variable i.e., if we want to fix the value of a variable
then we take the help of “final” keyword.
* By declaring the variables as “final” we are creating constants in java language.
Syntax: final datatype variable = value;
Ex: final double PI = 3.14;
The final keyword can be applied to instance variables, static variables, local variables,
parameters & reference variables.
Instance variables:
If an instance variable is declared & not initialized then it will be initialized automatically
with default values. If we do not want the default values, then we can initialize the instance
variable without own values either at the time of declaration (or) by using a constructor.
Final Instance variables:
If an instance variable is declared as ”final” & not initialized then that variable will not be
initialized automatically with default values. It is the responsibility of the programmer to
initialize final instance variable explicitly either at the time of declaration (or) by using
constructor.
Ex: class Sample{
final int a; //Invalid : Variable 'a' might not have been initialized
final int b=22; //valid : initialized at the time of declaration
final int c; //valid : initialized using constructor
Sample (){
c=33;
}
}
Static Variable:
If a static variable is declared & not initialized then it will be initialized automatically
with default values. If we do not want the default values then we can initialize the static variable
without own values at the time of declaration only.
Final Static Variable:
If a static variable is declared as “final” & if it is not initialized then it will not be
initialized automatically with default values. It is the responsibility of the programmer to
initialize final static variable explicitly at the time of declaration only.
Local Variable:
If a local variable is declared & not initialized automatically with default values.
It is the responsibility of the programmer to initialize the local variable at the time of declaration
(or) before using it.
class Sample{
Psum(String[] args){
final int a=11; //valid
final int b; //valid
final int c; //Invalid: declared & not initialized using it
final int d; //valid: declared & not initialized & not using it
b = 22;
System.out.println(a);
System.out.println(b);
System.out.println(c);
}
}
Parameters:
* The parameters are the values that are passed to a method (or) constructor.
* The parameters of a method (or) constructor has same scope (or) life as that of the local
variable.
* The parameters of a method (or) constructor will be initialized when they are involved with the
values that are passed.
* The value of a parameter can be changed any number of times within the method (or)
constructor.
* If we do not want to change the value of a parameter then we can declare the parameter as
“final”.
class Rectangle{
void area(int len, final int bre){
System.out.println("Area :" +(len*bre));
len=5;
System.out.println("Area :" +(len*bre));
}
}
Psum(String[] args){
Rectangle r = new Rectangle();
r.area(3,4);
}
}
O/P: Area: 12
Area: 20
Reference Variable:
A variable said to be a reference variable if it is pointing to (or) referring to an object of a
class.
* If a reference variable is declared as final then it cannot refer (or) point to another object.
* If a reference variable is declared as final then the content of that object referred by the
reference variable can be changed or modified.
Ex: class Sample{
int x = 10;
int y = 20;
psum(String[] args){
final Sample S = new Sample();
//S = new Sample();
System.out.println(S.x+” ”+S.y);
S.x = 30;
S.y = 40;
System.out.println(S.x+” ”+S.y);
}
}
Reflections
* It is a process of examining (or) checking (or) introspecting a class in a java program.
* Using Reflections, we can access the class information during the execution of the program.
class Student{
public Employee(){
class Sample{
Object o = getObject();
Class c = o.getClass();
//Class c = Class.forName("Employee");
System.out.println(c.getName());
System.out.println(c.getPackage());
System.out.println(c.getSuperClass());
Field[] f = c.getFields();
for(Field x:f){
System.out.println(x);
for(Constructor x:cons){
System.out.println(x);
Method[] m = c.getMethods();
for(Method x:m){
System.out.println(x);
}
INHERITANCE
It is the process of acquiring the members from one class to another class.
* The class that provides (or) gives the members that is called parent class/Super class/Base
class.
* The class that takes the members will be called as child class/sub class/derived class.
* Using inheritance, we can achieve re-usability, using which we can reduce the code size &
reducing development time.
The object class is called as the “Supermost” class in java language. Every class in java
either user defined class (or) predefined class will be sub-class to object class either directly (or)
indirectly.
Ex:
When a class is compiled, the compiler checks whether the class is extending from any
other class (or) not.
* If the class is already extending from other class then the compiler not add any extends
keyword.
* If the class is not extending from any other class then the compiler will automatically place
extends keyword & makes that class as sub-class to object class.
* Every class in java either pre (or) user defined can access the members of object class.
When we create an object of any class it involves the constructor of that class. Before
executing that class constructor it checks whether the class is extending or inheriting from any
other class (or) not. If it is inheriting from another class then before executing child class
constructor it execute parent class constructor & this process will be continued until it reaches
the object class.
* The invocation of the constructor will be in the order of child to parent & the execution will be
parent to child.
Ex:
class Cone{
Cone(){
System.out.println("Cone Constructor");
class Ctwo extends Cone{
Ctwo(){
System.out.println("Ctwo Constructor");
}
class Cthree extends Ctwo{
Cthree(){
System.out.println("Cthree Constructor");
}
class Inheritance{
psum(String[] ar){
Cthree c = new Cthree();
}
}
Super Keyword:
The super keyword can be used or refer to access instance members of the parent class
(Instance variable, Instance method)
If there is confusion between current class instance variable & local variable then the
compiler will not place “this” keyword automatically & it is refer to local variable. In such case
we want to access instance variable then the programmer has to explicitly specify “this”
keyword.
If there is a confusion b/w parent class instance members & child class instance members
then the compiler will place “this” keyword & if refers to child class (or) current class instance
variable. In such case if we want to access parents class instance variable then the programmer
has explicitly specify “Super” keyword.
** When there is no confusion b/w instance variables & local variables then the compiler will
automatically place this keyword.
The compiler will never provide super keyword whether the parent class instance variable
& child class instance variable have confusion (or) not.
Super keyword can be used to refer to the instance members of only its parents. Super
keyword will work for only one level.
Ex:
class Cone{
int x = 10;
int z = 20;
}
class Ctwo extends Cone{
int x = 12;
int y = 45;
}
class Cthree extends Ctwo(
int x = 23;
int a = 30;
void show(){
int x = 34;
Cone c1 = new Cone;
System.out.println(c1.x);
System.out.println(Super.x);
System.out.println(this.x);
System.out.println(x);
System.out.println(y);
System.out.println(z);
System.out.println(a);
}
}
class Inheritance{
Psum(String[] ar){
Cthree c = new Cthree();
C.show();
}
}
Relationships:
1. Is-A Relationship:
A class inherits from another class.
2. Has-A Relationship:
If a class contains object of another class.
Types of Relationships:
If a class is inheriting from another class then it is said to be Is-A Relationship.
Ex: class vehicles {
}
Class car extend vehicle{
}
car Is-A vehicle
class House {
}
Class hut extend House{
}
2. Has-A Relationship:
If a class contains an object of another class then it is called as Has-A
Relationship.
Ex: class Engine{
}
class car{
Engine object
}
Car Has-A Engine.
In java language, we can achieve reusability using Is-A (or) Has-A Relationship.
Polymorphism
If a single entity shows multiple behaviors then it is called as polymorphism.
* Using polymorphism we can achieve flexibility where a single entity can perform different
operations depending upon the requirement.
There are two types of polymorphism.
1. Compile Time Polymorphism:
If the polymorphism nature of an entity is decided by compiler during the compilation
time then it is called as compile time polymorphism.
* To achieve the compile time polymorphism we take the help of concept called “Method
Overloading”.
Method Overloading:
It is a process of writing multiple methods (or) two or more methods with the same
method having different signature is called method overloading.
Method Signature:
The method signature includes four parts. They are
1. Method Name
2. No of Parameters
3. Types of Parameters
4. Order of Parameters
**Note:
The method signature doesn’t include return type of the method & the parameter
names.
In method overloading, the methods must have same name with either different no of
parameters (or) different order of parameters such kind of method called as Overloaded
Methods.
Ex: add(int x, int y)
add(int x, int y, int z)
add(int x, int y)
add(double x, double y)
add(int x, double y)
add(double x, int y)
add(double x, char y)
add(boolean x, int y,String s)
add(int x, int y)
sub(int x, int y)
add(int x, int y)
add(int a, int b)
Note:
A class can contain any no of methods. Every method can contain different signature.
API: E:\softwares\JSE API\docs\apI\index.html.
Ex: class Addition {
void add(int x, int y){
System.out.println("sum1:" +(x+y));
}
void add(int x, int y, int z){
System.out.println("sum2:" +(x+y+z));
}
void add(int x, double y){
System.out.println("sum3:" +(x+y));
}
void add(double x, int y){
System.out.println("sum4:" +(x+y));
}
psum(String[] args){
Addition ad = new Addition();
}
}
Ex: class Addition {
void add(int x, int y){
System.out.println("sum1:" +(x+y));
}
void add(int x, int y, int z){
System.out.println("sum2:" +(x+y+z));
}
void add(int x, double y){
System.out.println("sum3:" +(x+y));
}
void add(double x, int y){
System.out.println("sum4:" +(x+y));
}
psum(String[] args){
Addition ad = new Addition();
a.add(1,2);
a.add(1,2,3);
a.add(1,2.3);
a.add(1.2,3);
}
}
O/P: sum1: 3
sum2: 6
sum3: 3.3
sum4: 4.2
* When a program is compiled the compiler will perform linking (or) binding of method
invocation with method definition. Since the decision is taken by the compiler during
compilation time it is called as Compile time polymorphism.
* Once the binding is performed by the compiler it cannot be changed & therefore it is called as
static binding.
* Since the binding is performed before the execution of the program it is called as early binding.
}
O/P: string array
string variable
int variable
int array
* Method overloading can be implemented in one class (or) in two different classes that have “is-
a” relationship.
class Sample{
void show(int x){
System.out.println(x);
}
}
class test extends Sample{
void show(double x){
System.out.println(x);
}
}
Runtime Polymorphism:
The polymorphism nature of an entity that is decided by JVM at execution time (or)
runtime then it is called as runtime polymorphism.
* To achieve runtime polymorphism we take the help of a concept Method Overriding.
Method Overriding:
It is a process of writing two methods with same signature & same returntype in two
different classes that have “is-a” relationship.
Ex: class Parent{
void show(){
System.out.println("Good Morning");
}
}
class child extends Parent{
void show(){
System.out.println("Good Night");
}
}
class Sample{
psum(String[] args){
Parent P = new Parent();
P.show();
Constructor Overloading:
It is a process of writing multiple constructors with the same name having different
signature. i.e., the constructors that have either different no of parameters (or) different type of
parameters (or) different order of parameters.
class Rectangle {
int len;
int bre;
Rectangle() {
len = 3;
bre = 3;
}
Rectangle(int x){
len = bre = x;
}
Rectangle(int x, int y)
this.len = len;
this.bre = bre;
}
void area(){
System.out.println("Area = "+(len*bre));
}
public static void main(String[] args){
Rectangle r1 = new Rectangle();
r1.area();
Rectangle r2 = new Rectangle();
r2.area();
Rectangle r3 = new Rectangle();
r3.area();
}
}
O/P: Area = 9
Area = 16
Area = 30
this keyword:
this keyword will refer to the current object(instance) of a class.
* Using this keyword we can access the instance members of a class. (variables & methods)
* If there is no confusion between instance variables & local variables then specifying “this”
keyword is optimal. If the programmer doesn’t specify “this” keyword then the compiler will
place “this” keyword automatically referring to the instance variable.
* If there is confusion between instance variables & local variables & if the programmer doesn’t
specify “this” keyword then in such case the compiler will not place “this” keyword & gives
preference to local variable.
* If we want to refer to the instance variable then the programmer has to explicitly specify “this”
keyword.
class Sample {
int x = 11;
int y =33;
void show(){
int x = 22;
System.out.println(this.x); //mandatory
System.out.println(x);
System.out.println(this.y); //optional
this.msg(); //optional
}
void msg(){
System.out.println("very good morning");
}
Static public void main(String[] args){
Sample S= new Sample();
S.show();
}
}
O/P: 11
22
33
very good morning
this():
this() can be used to refer to the zero parameterized constructor of the current class.
this(…):
this(…) can be used to refer to the parameterized constructor of the current class.
this() / this(…):
this() / this(…) can be used to refer to the other constructors of the same class. this() /
this(…) should be used only inside constructors to invoke other constructors of the same class.
class Sample {
Sample() {
this(4,6);
System.out.println("Sample Zero Constructor");
Sample(int x){
this();
System.out.println("Sample int Constructor");
}
Sample(int x,int y){
this();
System.out.println("Sample int int Constructor");
}
psum(String[] args){
System.out.println("Sample main method");
Sample S = new Sample(5);
}
}
O/P: Sample main method
Sample int int Constructor
Sample int Constructor
Sample Zero Constructor
Super Keyword:
The super keyword can be used to access the parent class instance members (variables &
methods).
* Specifying the super keyword is sometimes optional & sometimes mandatory.
* If there is no confusion between parent class instance members & child class instance members
& if we do not specify super keyword then compiler will not specify super keyword
automatically. The compiler will access both parent class instance members & child class
instance members by placing “this” keyword.
* If there is confusion between parent class instance members & child class instance members &
if we do not specify super keyword then compiler will automatically place this keyword & gives
preference to child class instance members.
* If we want to access the parent class instance members then it is the responsibility of the
programmer to specify super keyword to access the parent class instance members.
class Sample {
int x = 11;
int y = 13;
void show(){
System.out.println(x);
System.out.println(y);
}
}
class Sample extends Demo {
int x = 12;
int z = 14;
void show(){
System.out.println("super.x");
System.out.println(x);
System.out.println(y);
System.out.println(z);
}
void display(){
super.show();
show();
}
Psum(String[] args){
System.out.println("Sample main method");
Sample S= new Sample();
S.display();
}
}
O/P:
Sample main method
11
12
11
12
13
14
Super():
Super() will refer to the zero parameterized constructor of the parent class.
Super(…):
Super(…) will refer to the parameterized constructor of the parent class.
Note:
When an object of a child class is created, the child class constructor will be invoked,
before executing the child class constructor the compiler will invoke the parent class constructor
by placing Super() in every child class constructor.
class Parent {
Parent() {
System.out.println("Parent Zero Constructor");
}
}
class child extends Parent{
child(){
Super();
System.out.println("Child Zero Constructor");
}
psum(String[] args){
child c = new Child();
}
}
Super:
* Super can be used to refer to the parent class instance members from the child class.
* Super should be specified only in child class instance blocks (instance methods (or)
constructors of child class).
Super() / Super(…):
Super() / Super(…) can be used to refer to the parent class constructors from the child
class.
Super() / Super(…) should be specified only in child class constructors.
Compiler can automatically specify either “this” keyword (or) “Super()”.
class Parent {
Parent() {
this(4,6);
System.out.println("Parent Zero Constructor");
Parent(int x){
this();
System.out.println("Parent para Constructor");
}
class Child extends Parent {
Child(){
this(5);
System.out.println("Child zero Constructor");
}
Child(int x){
Super(5);
System.out.println("Child para Constructor");
psum(String[] args){
Child S = new Child();
}
}
Final Keyword:
The final keyword can be applied to variables, methods & classes.
* If a variable is declared as final, then the value of that variable cannot be changed i.e., final
variable are constants.
* If a method is declared as final, then that method cannot be overridden in the child class.
* A method has to be declared as final if we do not want the subclasses to modify the
implementation, by declaring a method as final, we are providing security to the method logic.
* Final methods can be accessed & used in child but cannot be modified.
Final class:
* If a class is declared as final then that class cannot be inherited.
* If we want to protect the implementation of a method then we declare that method as “final”. If
we want to protect all the methods of a class then we can declare all the methods as final (or)
declare the class as “final”.
* Declaring the class as final is exactly equivalent to declaring all the methods as final.
* In a final class, only the methods of that class are final but the variables of that class are not
final.
final class Cone {
}
class Ctwo extends Cone{
}
Error: Cone cannot be inherited because Cone class is declared as ”final”.
By declaring the class as final, we are restricting “is-a” relationship. The final class
members can be accessed in other class by using “has-a” relationship only.
final class Cone {
int x = 10;
void show() {
System.out.println("Good Morning");
}
}
class Ctwo{
psum(String[] args)
Cone c = new Cone();
c.Show();
System.out.println(c.x);
c.x = 20;
System.out.println(c.x);
}
}
O/P: Good Morning
10
20
Double Literal:
The double literals can be created in two ways.
1. The double literal can be created directly by specifying a number either positive (or) negative
with decimal point.
Ex: 1.2 457.57 0.007 -12.99
2. The double literals can be created indirectly by suffixing lowercase “d” (or) uppercase “D” to
int literals.
Ex: 12D 68768D 0d -456d
Note: We can suffix “D” (or) “d” to double literals. (Numbers with decimal point)
Ex: 1.2d 457.57d 0.007d -12.99d
The double literals can be stored only into double type.
Float Literals:
The float literals can be created in two ways & both are indirect ways.
* The float literals can be created indirectly by suffixing lowercase “f” (or) uppercase “F” to
either double literals (or) to int literals.
Ex: 1.2f 457.57f 0.007F -12.99F
1.2F 68768F 0f -456f
The float literals can be stored into either float type (or) double type.
Floating point category:
Default Value: 0
Default type : double
Character Literals:
The character literals can be created by specifying exactly one character enclosed within
a single quote.
The character specified within the single quotes can be either alphabet (or) digit (or) any
special symbol.
Ex: ‘a’ ‘B’ ‘8’ ‘#’.
* The character literal can be stored into all numeric datatypes.
* The character literals can be created by using UNICODE format.
UNICODE format:
The UNICODE format must begin with “\” (back slash) followed by lowercase “u”
followed by exactly 4 digit hexadecimal number, enclosed in single quotes.
Format: ‘\uxxxx’ 0-9 a-f(A-F).
Ex: char a = ‘\nabcd’; //Invalid
char b = ‘\b1234’; //Invalid
char c = ‘\uface’; //valid
char d = ‘\ubad’; //Invalid
char e = ‘\uA1B2’; //valid
char f = ‘\uCAFE’; //valid
char g = ‘\Uabcd’; //Invalid
char h = ‘\u12345’; //Invalid
char i = ‘\u123’; //Invalid
char j = ‘\uaAbB’; //Invalid
char k = ‘\u0000’; //valid
Escape Sequences (or) Characters:
The escape sequences will provide a special meaning to the compiler & there are ‘8’
escape sequences is java.
\n \t \r \f \b \\ \’ \”
Note: Escape sequences should be specified only in lower case.
Ex: char a = ‘\n’; //valid
char b = ‘\b’; //Invalid
char c = ‘\u’; //Invalid
char d = ‘\N’; //Invalid
char e = ‘\r’; //valid
char f = ‘\p’; //Invalid
char g = ‘\a’; //Invalid
char h = ‘\T’; //Invalid
Default value of char: space (‘\u0000’)
Boolean Literals:
In java language, there are only two boolean literals & they are true & false.
* The boolean literals can be stored only into boolean types. (other types not possible)
Predefined literals of java:
1. true
2. false Both are stored into boolean types.
3. null can be stored into reference variable of any class.
Type Casting:
It is the process of converting a value from one datatype to another datatype
which is compatible.
* If both the types are same then we need not perform type casting.’
* To perform type casting both types must be different & they must be compatible.
Type casting can be performed in two ways.
1. Type casting with respect to primitive types.
2. Type casting with respect to Reference types.
2. int x = 101;
char c = (char)x;
Automatic Type Conversion:
Case 2:
class Test {
psum(String[] args) {
child c = new child();
c.show();
c.display();
c.print();
}
}
In the above class, ‘c’ is the references variable of child class holding an object of
child class. Using this ‘c’ reference variable, we can access both the members of parent class &
child class.
up casting:
If the reference variable of parent class holding an object of any of its child class will be
called as up casting.
Syntax: parentclass ref = (parent class) child classObject;
In up casting, specifying the type casting is optional. If the programmer doesn’t specify
type casting, then the compiler will perform type casting automatically.
Ex: Object o = new Object();
Object o1 = new String();
Object o2 = new Sample();
Object o3 = new Demo();
Case 3:
class Test {
psum(String[] args) {
parent p = (parent)new child();
p.show();
p.display();
p.print();
}
}
In the above class, ‘p’ is the references variable of parent class holding an object of parent class.
Using this ‘p’ reference variable, we can access all the methods of parent class & those methods
from the child class which are overridden.
O/P: child class show method
parent class display method.
Down casting:
If a reference variable of child class holding an object of parent class is called
down casting.
Syntax: childclass ref = (childclass) parentObject;
In down casting, specifying the typecasting is mandatory. Down casting is valid
during compilation time and invalid during execution time & it gives a exception called
“classcastException”.
Case 4:
class Test {
psum(String[] args) {
child c = (child)new parent();
c.show();
c.display();
c.print();
}
}
O/P: valid at compilation time
Invalid during execution time “classcast Exception”
Case 5:
class Test {
psum(String[] args) {
parent p = new child();
child c = (child)p;
c.show();
c.display();
c.print();
}
}
O/P: child class show method
parent class display method.
child class print method
Up Casting:
If a child class object is refered by parent class reference variable then it is called
as Up Casting.
Down Casting:
If a parent class object is refered by child class reference variable then it is called
as Down Casting.
Type Casting with respect to reference types will not change the object, it only
changes the reference type.
Ex:
4. class AbstractDemo{
psum(String[] args){
//AbstractDemo a = new AbstractDemo();
Programmer1 p1 = new programmer1();
p1.twice(5);
p1.msg();
programmer p2 = new programmer2();
p2.twice(6);
p2.msg();
}
}
O/P: good morning
result: 10
good morning
result: 12
An abstract class can contain main method & it can be executed.
abstract class Test{
abstract void m1();
Psum(String[] args){
System.out.println(“test main method”);
}
}
1. Every class in java (either abstract class (or) non-abstract class) will be directly (or) indirectly
subclass of object class.
2. Every class in java (either abstract (or) non-abstract class) will contain a constructor whether
we specify (or) not.
3. We cannot create an object of the abstract class but we can declare a reference variable of the
abstract class.
The reference variable of an abstract class can hold on object of any of its child class which is
non-abstract.
1. Shape.java:
abstract class Shape {
int dim1, dim2;
Shape(int dim1, int dim2){
this dim1 = dim1;
this dim2 = dim2;
}
abstract double area();
}
2. Rectangle.java:
class Rectangle extends Shape{
Rectangle(int len, int bre)
Super(len, bre);
}
double area() {
return dim1*dim2;
}
}
3. Triangle.java:
class Triangle extends shape{
Triangle(int h, int b){
Super(h, b);
}
double area() {
return 0.5*dim1*dim2;
}
}
4. AreaDemo.java:
class AreaDemo {
psum(String[] args){
Shape S;
S = new Rectangle(2,3);
double res = S.area();
System.out.println("Rectangle Area = "+res);
S = new Triangle(4,5);
res = S.area();
System.out.println("Triangle Area = "+res);
}
}
O/P: Rectangle Area = 6
Triangle Area = 4
1. A method cannot be declared as abstract & final because final keywords says we cannot
override that method & abstract keyword says we must override that method.
2. A method cannot be declared as static & abstract because if a method is declared as static, then
that method can be invoked directly by using class name & we don’t require an object. If we
invoke a method that doesn’t contain definition then it leads to a problem & therefore abstract
methods cannot be static.
Note: only instance methods cannot be abstract.
Illegal Combination of a Class:
1. A class cannot be declared as abstract & final because abstract keyword says we must inherit
that class & final keyword says we cannot inherit that class & therefore illegal combination.
Static: Static modifier can be applied to only methods, variables not for classes. We can apply
the static to inner classes.
Final: Final modifier can be applied to variables, methods & classes.
Abstract: abstract modifier can be applied to methods & classes.
Interface
* An interface is a collection of only abstract methods.
* An interface can be considered as a contract (or) an agreement for developing the softwares.
Syntax: interface <InterfaceName>{
Variables
Methods
}
* An interface can contain some variables & methods.
Ex: interface operation{
int x = 12;
void m1();
}
* When a java program is compiled, the compiler will generate(.class) file for every class
(concrete class (or) abstract class) & it also generates a (.class) file for every interface.
* When the above java program is compiled the compiler will generate “Operation.class” file.
javap Operation
interface Operation{
public static final x;
public abstract void m1();
}
* Every variable of an interface will be declared as public, static & final whether we specify (or)
not.
* Every method of an interface will be declared as public & abstract whether we specify (or) not.
Why public: The variables & methods are declared as public so that they can be accessed from
any class from any location.
Why static: The variables of an interface are declared as static so that they can be accessed
directly by using interface name.
Why final: The variables of an interface are declared as final so that the class which is accessing
that variable cannot change the value.
Why abstract: The methods of an interface are declared as abstract because they do not contain
the definition.
* We cannot create an object for an interface i.e., interfaces cannot be instantiated.
* To use the members of an interface, the interface must be inherited into a class.
* To inherit an interface into a class, we use “implements” keyword.
Syntax: interface <Interface Name>{
}
Class<Subclass> implements <InterfaceName>{
}
* Inheriting an interface into a class is also called as “is-a” relationship.
* The subclass which is inheriting from the interface should provide implementation to the
abstract methods available in the interface.
* If the subclass doesn’t provide implementation to atleast one of the abstract method then
declare the subclass as abstract.
* If the subclass doesn’t provide implementation to all the abstract methods of an interface then
such kind of classes are called as “Implementation Classes”.
* An interface (or) have any number of implementation classes.
Ex: interface Animal{ Animal.java
Void makeSand();
}
class cat implements Animal{ cat.java
public void makeSand() {
System.out.println(“Meow Meow “);
}
}
class dog implements Animal{ Dog.java
public void makeSand() {
System.out.println(“Bow Bow “);
}
}
class Sample { Sample.java
psum(String[] ar) {
Cat c = new cat();
c.makeSand();
Dog d = new dog();
d.makeSand();
} javac Sample.java
} java Sample
O/P: Meooew Meow
Bow Bow
Marked Interface:
* An interface is said to be a marked interface (or) tagged interface if it doesn’t contain any
members. i.e., they will be empty.
* The purpose of marked interface is to provide some information to the JVM to perform a
special task. Examples of predefined marked interfaces are clonable, Serializable, Random
Access etc.
* We can create our own (user-defined) marked interfaces but they are of no use because JVM
has no meaning for user defined marked interfaces.
Abstract Interface
* An abstract class can be a combination of * An interface is a collection of only abstract
abstract methods & non-abstract methods. methods.
* An abstract class can contain instance * An interface can contain only abstract
methods, static methods, concrete methods, methods which are instance.
abstract methods.
* In an abstract class, specifying the abstract * In an interface, specifying the abstract
keyword to the abstract method is mandatory. keyword to an abstract method is optimal.
* An abstract class can contain both instance * An interface can contain only static
variables.
variables & static variables.
* The values of the variables in an abstract * The variables of an interface cannot be
class can be modified. changed because it is declared as final by
default.
* To inherit a class, we use extends keyword. * To inherit as interface, we use implements
keyword.
* Every class will be either directly (or) * There is no Super most interface.
indirectly subclass of object class. The object
class is called as the "Super most class".
i. Core packages:
The packages that are provided by the sun micro systems & which are part of the java
software & which begin with the term “java” are called as “Core Packages”.
ii. Extended packages:
The packages that are provided by the sun micro systems & which are part of the java
software & which begin with the term “java” are called as “Extended Packages”.
ii. Third party packages:
The packages that are provided by the sun micro systems & which are part of the java
software & which begin with the term “java” are called as “Third party packages”.(VENDOR
Packages)
Examples of predefined packages:
1. java.lang:
The packages contain set of classes & interfaces required for basic programming.
Note: “java.lang” package will be called as default package & it will be available to every java
program.
2. java.io: (input output)
The packages contain set of classes & interfaces required for performing input ouput
operartions.
3. java.net: (Network)
The packages contain set of classes & interfaces required for developing networking
applications.
4. java.util: (utility)
The packages contain has set of classes & interfaces which are specially related to
collection framework
5. java.text:
The packages contain classes & interfaces which can be used for achieving
“internationalization(I18N)” (date & time).
6. java.awt:
This packages contains classes & interfaces required for developing a GUI(Graphical
user Interface) (radio button, textbox, checkbox etc).
7. javax.swing:
This package contains a set of classes & interfaces required for developing a GUI better
than awt.
Static Import:
A static imports is introduced in java 1.5 version & it can be used for accessing
static members from a class/interface.
Syntax: import static package.className.*; //implicit static import
import static package.className.Staticmember; //Explicit static import
Ex: import static java.lang.Math.*;
import static java.lang.Byte.MIN_VALUE;
import static java.lang.Byte.MAX_VALUE;
class Test{
psum(String[] args){
System.out.println(min(2,3)); //2.0
System.out.println(max(2,3)); //3.0
System.out.println(floor(4.9)); //4.0
System.out.println(ceil(4.9)); //5.0
System.out.println(round(4.9)); //5.0
System.out.println(random()); //0.00123 [range from 0.0 to 1.0]
System.out.println(sqrt(9)); //3
System.out.println(pow(2,3)); //
System.out.println(MIN_VALUE); //-128
System.out.println(MAX_VALUE); //127
}
}
Difference between general & static import statements?
General import statement is used for accessing a class/interface from a package. Whereas
static imports are used for accessing static members from a class/interface.
Access Specifiers:
The access specifiers will define the level of accessibility (or) visibility of a
class/interface in a package (or) they define the level of accessibility of the members of
class/interface.
* The access specifiers will define the scope(life) of the members in a class using which we can
provide security to the data.
In java language we have 4 levels of access specifiers, Specified with 3 keywords.
1. Public
2. Private
3. Protected
4. default (no access specifier)
1. Public:
If a member is declared as public then it can be accessed from any class in any package.
The public access specifier can be applied to classes, interaces, variables & constructors.
2. Private:
The private access specifier if applied to a member then it can be accessed only in that
class in which it is declared. The private access specifier can be applied to methods, variables &
constructors.
3. Protected:
If a member is declared as protected then it can be accessed from all the classes available
in that package & subclass available in other packages.
The protected access specifiers can be applied to a methods, variables & constructors.
4. Default: access:
A members is said to be default if it is not declared as private, public (or) protected
i.e., if you do not specify any access specifier then it will be called as default access. If a member
is declared as default then it is can be accessed from any class within the package & therefore the
default access is called as package level access.
* The default access can be applied to classes, interfaces, methods, variables & constructors.
Class Diagram:
Java Program:
The most restricted access is private & most accessible access specifier is public.
Mathematical Expression:
Private <default <protected <public
Overriding Rules:
However we are overriding a method, the child class method should have an access
specifier same as that of the parent class method access specifier on any bigger access specifier.
Illegal Combination of a method:
A method can’t be declared as private & abstract because a private method can be
accessed only in that class in which it is declared where as the abstract must be inherited into
other class & provide the implementation.
* A class can be declared as either public or default.
* If a class is declared as default then the name of the program can be any name.
* If a class is declared as public then class name & program must be same.
* A java program can contain any no of classes but it contains atmost one public class.
* The naming of java will be based on class declaration.
Note: The java program naming will not be based on main method (or) any other method.
Ex: public class A {
psum(String[] args){
System.out.println(“ class A main method”);
}
}
public class B {
psum(String[] args){
System.out.println(“class B main method”);
}
}
class C {
psum(“class C main method”);
}
}
class D {
//psum(“class D main method”);
}
}
* A java prg can contain any no of classes but recommended to write only one classes in a
program.
* The above java program contain 4 classes since all 4 classes are declared as default, the name
of java program can be any name.
A.java, B.java, C.java, D.java, Abcd.java, Sample.java.
Let us name the above program with Sample.java.
Syntax: javac programme with extension
javac Sample.java
When a java program is compiled, the compiler will generate a (.class) file. The
no of class files generated by the compiler will be exactly equal to no of classes available in the
program. The name of the (.class) file generated will be equal to the name of the class specified
in the program.
Every class in java will contain a constructor whether we specify or not. If the
programmer doesnot specify any constructor then the compiler will provide a zero parameterized
constructor.
* The declaration of the zero parameterized constructor provided by the compiler will be based
on class declaration i.e., if the class is declared as public then it provides public zero
parameterized constructor & if class is default then the compiler will provide default constructor.
Note: The compiler never provide parameterized constructor & they can’t be declare the
constructor as private or protected.
As a programmer we can provide or declared as zero parameterized constructor,
parameterized constructor or both & they can be declared as either private, public (or) protected
(or) default.
Singleton class:
If we are able to create only one object for a class then that would be called as singleton
class.
* To create a singleton class we need to declare the constructor as private & it should contain a
factory method.
Factory Method:
If a method returns an object of its own class then it is called as factory method.
Note: The factory method must be declared as “Static”.
Object:
Object is the super most class of all classes in java.
Throwable:
Throwable is the super most class of all runtime errors in java.
Exception:
An exception is a runtime error which occurs because of the wrong logic (or) invalid
input provided by the programmer. The exception is the super most of all the exceptions.
The exceptions are further classified into two types based on when they are identified.
1. Compile Time Exception
2. Runtime Errors
1. Compile Time Exception:
The exceptions that occur at runtime & which can be identified before runtime i.e.,
during compilation time will be called as compile time exception.
2. Runtime Exception:
The exception that occur at runtime & which can be identified only at runtime are called
as runtime exception.
Error:
An error is a runtime error which occurs because of the JVM failure.
* The runtime errors are further classified into two types based on whether they are handled (or)
not.
1. Checked Exception:
If the handling of the runtime error is mandatory then it will be called as checked
exception.
2. Unchecked Exception:
If the handling of the runtime error is optimal then it will be called as unchecked
exception.
The runtime exceptions & its subclasses, error & its subclasses are called as unchecked
exceptions & the remaining exceptions are called as checked exceptions.
class Sample {
psum(String[] args){
System.out.println(“first line”);
System.out.println(10/0);
System.out.println(“third line”);
}
}
When an exception occurs in a program, an object of the exception type will be created
along with the exception information. The object that is created will be thrown to the JVM(Java
Runtime System). The java runtime system will catch the object that is thrown & reads the
information available in that object & then looks for exception handling code in that method
which has thrown the exception object. If the java runtime system is unable to find exception
handling code in that method then the JVM will invoke “Default Exception Handler”.
The default exception handler will display the exception information available in that
object & then terminates the application abnormally leading to incomplete execution.
O/P: first line
Exception in thread main:
Arithematic Exception : / by zero at Sample.main(Sample.java:4)
Exception Handling:
It is the process of finding an alternate solution so that the remaining code is executed &
leads to normal termination.
The code that is used for exception handling will be called as Exception Handler.
Try block:
The try block can be used for specifying the statements that may generate the exception.
Syntax: try{
error generation statements
problem in code
}
* The try block can contain any no of statements but recommended to write only those
statements that may generate the exception.
Catch block:
This block can be used for displaying the information of the exception that has occurred.
Syntax: catch(Exception ref)
{
exception displaying code
}
Every catch block must contain a reference variable of any one of the exception.
Finally block:
This block can be used for performing code cleanup activities. (Releasing resources,
memory etc)
Syntax: finally{
code cleanup activities
}
Rules:
* A try block must be followed by either catch block (or) a finally block.
* A catch block must be preceded by either try block (or) catch block.
* A catch block must be followed by either a catch block (or) try block.
* A finally block must be preceded by either try block (or) catch block.
Note: A catch block & finally block cannot exist without a try block.
* A try block can contain any no of catch block (0 or more).
* If the try block contains multiple catch blocks & if the exceptions specified in the catch blocks
have “is-a” relationship then the exceptions must be specified in the order of child to parent, but
if the exceptions specified in the catch block don’t have “is-a” relationship then the exceptions
can be specified in any order.
* A try block can contain atmost one finally block.
* We can specify some statements either before the blocks (or) after the blocks (or) inside the
blocks but not in-between the blocks.
* A try, catch & finally blocks can be nested in any of the blocks.
* We cannot guarantee the execution of a try block (or) catch block, but the execution of finally
block can be guaranteed.
* In a try block, if there is no exception (or) an exception has occurred which is not matching
then in such case, catch block will not be executed.
* A catch block will be executed only when an exception has occurred & it is matching.
* If a try block contains multiple catch blocks then only one of the catch block will be executed
which is matching.
* A finally block will be executed if there is a exception (or) the exception is handled (or) not.
Throws:
The “throws” keyword is used to transfer (or) delegate the responsibility of
exception handling to its caller.
Syntax:
returntype methodName(parameters)throws Exception1, Exception2,.......{
statements
}
We can transfer the responsibility of exception handling to any of its caller
including JVM but it is recommended that we do not pass the responsibility of exception
handling to JVM.
Ex: class Sample{
psum(String[] args){
System.out.println ("main first line");
try{
methodOne();
}
catch(Arithematic Exception ae){
ae.printStackTrace();
}
System.out.println ("main last line");
}
public static void methodOn() throws Arithematic Exception{
System.out.println ("methodOne first line");
System.out.println ("10/0");
System.out.println ("methodOne last line");
}
}
O/P: main first line
methodOne first line
Arithematic Exception
methodOne first line
methodOne last line
The throw keyword can be used to throw an object explicitly and test whether the
code is able to handle the exception (or) not.
Ex: try{
System.out.println(10/0);
}
catch(Arithematic Exception ae){
System.out.println(ae);
(or)
System.out.println(ae.toString());
}
O/P: / by zero
4. Customized message:
If we do not want to display the information of an exception by using the
predefined methods then we can display our own message.
Ex: try{
System.out.println(10/0);
}
catch(Arithematic Exception ae){
System.out.println("ArithmeticException has occured");
System.out.println("It is my own message");
}
java.lang Package:
This package is the default package available to every java program. Any class
available in java.lang package can be accessed directly.
Object class:
The object class belongs to java.lang package & it is called as super most class of
all classes in java.
* Every class in java either predefined (or) user defined will be a subclass of object class either
directly (or) indirectly.
* The members available in object class can be used (or) accessed in every class of java
language.
When the reference variable of any class is displayed & if it shows the output as
“classname followed by hashcode” then the user will not be able to understand the information &
therefore it is recommended to override toString() in every user defined class. So that we can
display a meaningful (or) understandable information.
Overriding of toString() in user defined class:
class Sample{
psum(String[] args){
Sample S = new Sample();
System.out.println(S);
Student Stu = new Student(12);
System.out.println(Stu.toString());
Student Stu1 = new Student(12);
System.out.println(Stu1);
}
public string toString(){
return "Sample class object";
}
}
class Student {
int rollNo;
Student(int rollNo){
this.rollNo = rollNo;
}
public String toString(){
return ""+rollNo";
}
}
O/P: Sample class object
12
34
2. int hashcode:
This method will provide (or) generate a number which will be used for
identifying an object.
* The hashcode value must be a unique number so that every object can be identified.
Note: Hashcode is not the address of the object.
class Sample{
psum(String[] args){
Sample S1 = new Sample();
System.out.println(S1.hashcode());
Sample S2 = new Sample();
System.out.println(S2.hashcode());
}
}
O/P: 4072869
1671711
If we don’t want the hashcode to be generated automatically by the predefined
logic available in hashcode() of the object class. Then we can override hashcode() in our clas to
generate our own hashcode.
* When we override the hashcode(), we are recommended to override the method in such a way
that it generates a unique number for every object.
Ex: class Sample{
static int count = 10;
psum(String[] args){
Sample S1 = new Sample();
System.out.println(S1.hashcode());
Sample S2 = new Sample();
System.out.println(S2.hashcode());
}
public int hashcode(){
return count++;
}
}
O/P: 10
11
class Student {
int rollNo;
Student(int rollNo){
this.rollNo = rollNo;
}
}
class Sample{
psum(String[] args){
String S1 = new String("hello");
String S2 = new String("hello");
System.out.println(S1.equals(S2));
String S3 = new String("hello");
String S4 = new String("hello");
System.out.println(S3.equals(S4));
}
}
O/P: true
true
If we do not want to compare the hashcodes of the objects then we can override equals()
& define the meaning of equality.
The overridden equals() is available to only student class that we have overridden from
object class. The overridden equals() will not be available for other class(ex: employee etc.) then
again override that equals() in emp class.
4. Object clone():
* This method can be used to take a backup of an object.
* This method can be used to create a duplicate copy for an existing object.
Procedure to create a duplicate copy:
* The clone method will throw CloneNotSupportedException, which must be handled because it
is an checked exception.
* The object whose duplicate copy has to be created, its corresponding class must implement
clonable interface.
* The return type of clone method is object & it has to be type casted to our required type.
Ex: class Sample implement Clonable{
int x = 11;
int y = 22;
psum(String[] args)throws cloneNotSupportException{
Sample S1 = new Sample();
System.out.println(S1.x+""+s1.y);
Object obj = S1.clone();
S1.x = 33;
S2.x = 44;
System.out.println(S1.x+""+s1.y);
Sample S2 = new Sample();
System.out.println(S2.x+""+s2.y);
}
}
O/P: 11 22
33 44
11 22
Wrapper Classes
* These classes can be used for converting a value from primitive type to class type.
* For every primitive type available in java we have one corresponding wrapper classes.
* All the wrapper classes (8) are available in java.lang package.
byteValue()
shortValue() These 6 methods are available in each class of all
intValue() ‘6’ classes below Byte, Short, Integer, Long, Float, Double.
longValue()
floatValue()
doubleValue()
4.
Static String toBinaryString(int/long)
Static String toOctalString(int/long)
Static String toHexaString(int/long)
* The above three methods can be used to convert a value from decimal number system to binary
system, octal system & Hexadecimal system respectively.
* The above three methods are available in Integer & long wrapper classes.
Ex: int i = 12;
System.out.println(i);
System.out.println(Integer.toBinaryString(i));
System.out.println(Integer.toOctalString(i));
System.out.println(Integer.toHexaString(i));
Hierarchy of Wrapper Classes:
Boxing:
It is the process of converting a value from primitive type to wrapper type. This
process is performed automatically by the compiler from 1.5 version & therefore called it as
AutoBoxing.
UnBoxing:
It is a process of converting a value from wrapper type to primitive type. This
process is performed automatically by the compiler from 1.5 version onwards & there called it as
Auto Unboxing.
Integer m = new Integer(45);
int n = m;
enum:
The enum keyword is introduced in java 1.5 version & the purpose of an enum
keyword is to create a group of named constants.
Syntax:
enum<EnumName>{
Constants
}
javac Day.java
javap Day
O/P: enum main method
* Every enum will contain a constructor.
* An enum cannot be instantiated by the programmer i.e., the programmer cannot create the
object directly but an object of enum can be created by declaring a constant in an enum.
* The constructors of an enum will be executed one time for every constant that is declared.
enum Day{
SUN, MON, TUE, WED, THU, FRI, SAT;
Day(){
System.out.println(“enum main method”);
}
Psum(String[] args){
System.out.println(“enum main method”);
}
}
To the switch statement we can pass byte, short, int, char as an argument & it is
valid upto 1.4 version from 1.5 version onwards, we can pass byte, short, int, char primitive
types & its corresponding four wrapper classes(Byte, Short, Integer & Character) & enum.
enum Day{
SUN, MON, TUE, WED, THU, FRI, SAT;
}
class Work{
Psum(String[] args){
Day d = Day.SUN;
Switch(d){
Case MON:System.out.println(“Boring, back to office”);
break;
Case FRI:System.out.println(“preparing to enjoy”);
break;
Case SAT:System.out.println(“sleeping”);
break;
Case SUN:System.out.println(“eating”);
}
}
}
Note: The case labels must be exactly same as that of the constants available in enum.
Important Questions
* When do you allocate the memory for instance variables?
The memory for the instance variables will be allocated at the time of object
creation.
* Where?
The memory for the instance variables will be allocated in heap memory.
* How many times?
The memory for the instance variables will be allocated one time for each object.