Professional Documents
Culture Documents
An entity that has state and behaviour is known as an object e.g. chair, bike, marker, pen, table, car
etc. It can be physical or logical (tangible and intangible). The example of intangible object is
banking system.
An object has three characteristics:
state: represents data (value) of an object.
Behaviour: represents the behaviour (functionality) of an object such as deposit, withdraw etc.
identity: Object identity is typically implemented via a unique ID. The value of the ID is not
visible to the external user. But, it is used internally by the JVM to identify each object
uniquely.
For Example: Pen is an object. Its name is Reynolds, colour is white etc. known as its state. It is
used to write, so writing is its behaviour.
Object is an instance of a class. Class is a template or blueprint from which objects are created. So
object is the instance(result) of a class.
Class Definition
A class is a group of objects that has common properties. It is a template or
blueprint from which objects are created.
A class in java can contain:
data members
methods
constructors
and block
class and interface
Syntax to declare a class:
class <class_name>{
data member; method;
}
Instance variable:A variable that is created inside the class but outside the
method, is known as instance variable. Instance variable doesn't get memory at
compile time. It gets memory at runtime when object(instance) is created. That is
why, it is known as instance variable.
Method
In java, a method is like function i.e. used to expose behaviour of an object.
Advantage of Method
1.Code Reusability
2.Code Optimization
new keyword:
The new keyword is used to allocate memory to an object at runtime.
Java Naming conventions:Java naming convention is a rule to follow as you decide
what to name your identifiers such as class, package, variable, constant, method
etc.But, it is not forced to follow. So, it is known as convention not rule.All the classes,
interfaces, packages, methods and fields of java programming language are given
according to java naming convention.
Advantage of naming conventions in java:
By using standard Java naming conventions, you make your code easier to read for
yourself and for other programmers. Readability of Java program is very important. It
indicates that less time is spent to figure out what the code does.
Name Convention
class name should start with uppercase letter and be a noun e.g. String, Color, Button,
System, Thread etc.
interface name should start with uppercase letter and be an adjective e.g. Runnable, Remote,
ActionListener etc.
method name should start with lowercase letter and be a verb e.g.
actionPerformed(), main(), print(), println() etc.
variable name should start with lowercase letter e.g. firstName, orderNumber etc.
package name should be in lowercase letter e.g. java, lang, sql, util etc.
System.out.println(s1.name);
}
}
output:
0
null
Example of Object and class that maintains the records of students
class Student2{
int rollno;
String name;
void insertRecord(int r, String n){ //method
rollno=r;
name=n;
}
void displayInformation(){//method
System.out.println(rollno+" "+name);
}
public static void main(String args[]){
Student2 s1=new Student2();
Student2 s2=new Student2();
s1.insertRecord(111,"Karan");
s2.insertRecord(222,"Aryan");
s1.displayInformation();
s2.displayInformation();
}
output:
}
111 Karan
222 Aryan
Another Example of Object and Class
class Rectangle{
int length,width;
void insert(int l, int w){
length=l;
width=w;
}
void calculateArea(){
System.out.println(length*width);
}
public static void main(String args[]){
Rectangle r1=new Rectangle();
Rectangle r2=new Rectangle();
r1.insert(11,5);
r2.insert(3,15);
r1.calculateArea(); output:
r2.calculateArea(); 55
} 45
}
Anonymous object:
Anonymous simply means nameless. An object that have no reference is known as
anonymous object.If you have to use an object only once, anonymous object is a
good approach.
class Calculation{
void fact(int n){
int fact=1;
for(int i=1;i<=n;i++){
fact=fact*i;
}
System.out.println("factorial is "+fact);
}
public static void main(String args[]){
new Calculation().fact(5);//calling method with anonymous object
}
}
output:
120
Creating multiple objects by one type only.We can create multiple objects by one
type only as we do in case of primitives.
Example:
class Rectangle{
int length,width;
void insert(int l,int w){
length=l;
width=w;
}
void calculateArea(){
System.out.println(length*width);
}
public static void main(String args[]){
Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two objects
r1.insert(11,5);
r2.insert(3,15); output:
r1.calculateArea(); 55
r2.calculateArea();
45
}
}
Advantage of OOPs over Procedure-oriented programming language
Example:
//Program to get cube of a given number by static method class
Calculate{
static int cube(int x){
return x*x*x;
}
public static void main(String args[]){
int result=Calculate.cube(5); System.out.println(result);
}
}
Output:
125
Example://Program of changing the common property of all objects(static field).
class Student9{
int rollno; s1.display();
String name; s2.display();
static String college = "ITS"; }
static void change(){ }
college = "BBDIT";
}
Student9(int r, String n){
rollno = r;
name = n;
}
void display (){
System.out.println(rollno+""+name+"”+college);
}
public static void main(String args[]){
Student9.change(); Output:
Student9 s1 = new Student9 (111,"Karan"); 111 Karan BBDIT
Student9 s2 = new Student9 (222,"Aryan"); 222 Aryan BBDIT
Restrictions for static method
There are two main restrictions for the static method. They are:
Ø The static method can not use non static data member or call non-static
method directly.
Ø this and super cannot be used in static context.
class A{
int a=40;//non static
class Bike{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
System.out.println(speedlimit);
}
public static void main(String args[]){
new Bike10();
}
}
output:
70
static blank final variable
A static final variable that is not initialized at the time of
declaration is known as static blank final variable. It can be
initialized only in static block.
Example
class A{
static final int data;//static blank final variable
static{
data=50;
}
public static void main(String args[]){
System.out.println(A.data);
}
}
output:
50
Q) What is final parameter?
If you declare any parameter as final, you cannot change the value of
it.
class Bike11{
int cube(final int n){
n=n+2;//can't be changed as n is final n*n*n;
}
public static void main(String args[]){
Bike11 b=new Bike11();
b.cube(5);
}
}
Output:Compile Time Error
Q) Can we declare a constructor final?
• No, because constructor is never inherited.
3.3.Array :1D & 2D
An array is a collection of similar type of elements that have contiguous
memory location.
Ø In Java array is an object the contains elements of similar data type. It is a
data structure where we store similar elements. We can store only fixed set of
elements in a java array.
Ø Array in java is index based, first element of the array is stored at 0 index.
//printing 2D array
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}
}
Output:
123
245
445
Copying an array
We can copy an array to another by the arraycopy method of System class.
Syntax of arraycopy method
public static void arraycopy(
Object src, int srcPos,Object dest, int destPos, int length
)
Example
class TestArrayCopyDemo {
public static void main(String[] args) {
char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e','i', 'n', 'a', 't', 'e', 'd' };
javac Demo.java
Method Description
public String next() it returns the next token from the scanner.
public String nextLine() it moves the scanner position to the next line and
returns the value as a string.
public byte nextByte() it scans the next token as a byte.
public short nextShort() it scans the next token as a short value.
public int nextInt() it scans the next token as an int value.
public long nextLong() it scans the next token as a long value.
public float nextFloat() it scans the next token as a float value.
public double nextDouble() it scans the next token as a double value.
Example to get input from console
Example of the Java Scanner class which reads the int, string and double value as
an input:
import java.util.Scanner;
class ScannerTest{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
System.out.println("Enter your rollno");
int rollno=sc.nextInt();
System.out.println("Enter your name");
String name=sc.next();
System.out.println("Enter your fee");
double fee=sc.nextDouble();
System.out.println("Rollno:"+rollno+" name:"+name+" fee:"+fee);
sc.close(); Output:
} Enter your rollno 111
}
Enter your name Ratan
Enter your fee
450000
Rollno:111 name:Ratan fee:450000
Java Scanner Example with delimiter
Let's see the example of Scanner class with delimiter. The \s represents whitespace.
import java.util.*;
public class ScannerTest{
public static void main(String args[]){
String input = "10 tea 20 coffee 30 tea buiscuits";
System.out.println(s.nextInt());
System.out.println(s.next());
System.out.println(s.nextInt());
System.out.println(s.next());
s.close();
}
}
Output:
10
tea
20
coffee
InputStreamReader Class
The InputStreamReader class reads characters from a byte input stream. It reads
bytes and decodes them into characters using a specified charset. The decoding
layer transforms bytes to chars according to an encoding standard . There are
many available encodings to choose from.
System.out.println("name="+name);
System.out.println("rollno="+roll);
System.out.println("Fee="+fee);
}
}
Input Stream Reader Class constructors
Constructor Description
InputStreamReader(InputStream in) This creates an InputStreamReader
that uses the default charset.
Closing an InputStreamReader
When you are finished reading characters from the InputStreamReader you
should remember to close it. Closing an InputStreamReader will also close the
InputStream instance from which the InputStreamReader is reading.
inputStreamReader.close();
3.6.Constructors, overloading of methods and constructors
Method Overloading
Ø If a class have multiple methods by same name but different parameters, it is known
as Method Overloading.
Ø If we have to perform only one operation, having same name of the methods
increases the readability of the program.
Advantage of method overloading?
Ø Method overloading increases the readability of the program.
Different ways to overload the method
By changing number of arguments in function
By changing the data type in function
Example of Method Overloading by changing the no. of arguments
.class Calculation{
void sum(int a,int b){
System.out.println(a+b);
}
void sum(int a,int b,int c){
System.out.println(a+b+c);
}
}
}
output:
30
40
Example of Method Overloading by changing data type of argument
class Calculation2{
void sum(int a,int b){
System.out.println(a+b);
}
void sum(double a,double b){
System.out.println(a+b);
}
public static void main(String args[]){
obj.sum(20,20);
}
}
output:
21
40
Why Method Overloaing is not possible by changing the return type of method?
class Calculation3{
int sum(int a,int b){
System.out.println(a+b);
}
double sum(int a,int b){
System.out.println(a+b);
}
Yes, by method overloading. You can have any number of main methods in a
class by method overloading.
Example:
class Overloading1{
public static void main(int a){
System.out.println(a);
}
}
}
Output:
40
60
Example of Method Overloading with TypePromotion if matching found
If there are matching type arguments in the method, type promotion is not
performed.
class OverloadingCalculation2{
void sum(int a,int b){
System.out.println("int arg method invoked");
}
void sum(long a,long b){
System.out.println("long arg method invoked");
}
public static void main(String args[]){
OverloadingCalculation2 obj=new OverloadingCalculation2();
obj.sum(20,20);//now int arg sum() method gets invoked
}
}
Output:
int arg method invoked
Example of Method Overloading with Type Promotion in case ambiguity
class OverloadingCalculation3{
void sum(int a,long b){
System.out.println("a method invoked");
}
void sum(long a,int b){
System.out.println("b method invoked");
}
Creating an inner class is quite simple. You just need to write a class within a
class. Unlike a class, an inner class can be private and once you declare an
inner class private, it cannot be accessed from an object outside the class.
Example:
class Outer_Demo {
int num;
// inner class
private class Inner_Demo {
public void print() {
System.out.println("This is an inner class");
}
} // Accessing the display_Inner()
// Accessing he inner class from the method //method.
void display_Inner() { outer.display_Inner();
Inner_Demo inner = new Inner_Demo(); }
}
inner.print();
} Output
} This is an inner class.
public class My_class {
public static void main(String args[]) {
// Instantiating the outer class
Outer_Demo outer = new Outer_Demo();
Accessing the Private Members
As mentioned earlier, inner classes are also used to access the private members of a
class.
Suppose, a class is having private members to access them. Write an inner class in it,
return the private members from a method within the inner class, say, getValue(), and
finally from another class (from which you want to access the private members) call
the getValue() method of the inner class.
To instantiate the inner class, initially you have to instantiate the outer class. Thereafter,
using the object of the outer class, following is the way in which you can instantiate the
inner class.
// inner class
public class Inner_Demo {
public int getNum() {
System.out.println("This is the getnum method of the inner class");
return num;
}
}
}
public class My_class2 {
Output:
The value of num in the class Test is: 175
Method-local Inner Class
In Java, we can write a class within a method and this will be a local type. Like local
variables, the scope of the inner class is restricted within the method.
A method-local inner class can be instantiated only within the method where the inner
class is defined. The following program shows how to use a method-local inner class.
Example:
public class Outerclass {
// instance method of the outer class
void my_Method() {
int num = 23;
// method-local inner class
class MethodInner_Demo {
public void print() {
System.out.println("This is method inner class "+num);
}
} // end of inner class
// Accessing the inner class
MethodInner_Demo inner = new MethodInner_Demo();
inner.print();
}
public static void main(String args[]) { Output:
Outerclass outer = new Outerclass();
outer.my_Method(); This is method inner class 23
}
}
Anonymous Inner Class
An inner class declared without a class name is known as an anonymous inner class.
In case of anonymous inner classes, we declare and instantiate them at the same time.
Generally, they are used whenever you need to override the method of a class or an
interface.
Syntax:
AnonymousInner an_inner = new AnonymousInner() {
public void my_method() {
........
........
}
};
Example:
abstract class AnonymousInner {
public abstract void mymethod();
}
public class Outer_class {
public static void main(String args[]) {
AnonymousInner inner = new AnonymousInner() {
public void mymethod() {
System.out.println("This is an example of anonymous inner class");
}
};
inner.mymethod();
}
}
Output:
This is an example of anonymous inner class
In the same way, you can override the methods of the concrete class as well as the
interface using an anonymous inner class.
Anonymous Inner Class as Argument
Generally, if a method accepts an object of an interface, an abstract class, or a
concrete class, then we can implement the interface, extend the abstract class, and
pass the object to the method. If it is a class, then we can directly pass it to the
method.But in all the three cases, you can pass an anonymous inner class to the
method.
syntax:
obj.my_Method(new My_Class() {
public void Do() {
.....
....
}
});
Example:
interface Message {
String greet();
}
public class My_class {
// method which accepts the object of interface Message
public void displayMessage(Message m) {
System.out.println(m.greet() +", This is an example of anonymous inner class as an
argument");
}
public static void main(String args[]) {
// Instantiating the class
My_class obj = new My_class();
// Passing an anonymous inner class as an argument
obj.displayMessage(new Message() {public String greet() { return "Hello";}});
}
}
Output
Hello This is an example of anonymous inner class as an argument
Static Nested Class
Ø A static inner class is a nested class which is a static member of the outer class.
Ø It can be accessed without instantiating the outer class, using other static members.
Ø Just like static members, a static nested class does not have access to the instance
variables and methods of the outer class.
Syntax
class MyOuter {
static class Nested_Demo {
}
}
Example:
public class Outer {
static class Nested_Demo {
public void my_method() {
System.out.println("This is my nested class");
}
}
public static void main(String args[]) {
Outer.Nested_Demo nested = new Outer.Nested_Demo();
nested.my_method();
}
}
Output:
This is my nested class