0% found this document useful (0 votes)
14 views

Java OOPs Concept

The document discusses Java concepts like object oriented programming, JVM architecture, JRE, classes, objects, methods, variables, method overloading, instance variables, and static variables. It provides example code to demonstrate these concepts.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Java OOPs Concept

The document discusses Java concepts like object oriented programming, JVM architecture, JRE, classes, objects, methods, variables, method overloading, instance variables, and static variables. It provides example code to demonstrate these concepts.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 68

JAVA

bject Oriented Programming System (OOPs)


JVM: (Java Virtual Machine) Architecture

 Java Virtual Machine


 Internal Architecture of JVM
 JVM (Java Virtual Machine) is an abstract machine. It is a specification that
provides runtime environment in which java byte code can be executed.

What is JRE?

 JRE stands for Java Run-time Environment.


 It is the part of the Java Development Kit (JDK).
 It is a freely available software distribution which has Java Class Library,
specific tools, and a stand-alone JVM.
 It is the most common environment available on devices to run java programs.
 The source Java code gets compiled and converted to Java byte code.
 If you wish to run this byte code on any platform, you require JRE.
 The JRE loads classes, verify access to memory, and retrieves the system
resources.
 JRE acts as a layer on the top of the operating system.

// wajp to print a simple name on the screen

class Program

public static void main(String args[])

System.out.print("Hi everyone we are starting java");

steps to write and execute java program

1. Write a java program in editor

2. Save the program with filename.java (ex-Program.java)

3. Open the command prompt and go to your file location


JAVA
ex-c:>d:

d:>cd java10am

4. compile the program

d:>java10aam>javac Program.java

5. Execute the program

d:>java10am>java Program

// wajp to print multiple messages on the screen.

class Program1

public static void main(String args[])

System.out.println("Hi everyone we are starting java");

System.out.println("at prsoftware training institute Hyderabad");

Difference between print and println

 print will print the data on the same line


 println will print the data on seprate line

//wajp to print numbers in multiple ways

class ProgramOne

public static void main(String args[])

System.out.printf("%d %d\n",10,20);
JAVA
System.out.println(10+" "+20);

System.out.println(10+"+"+20+"="+(10+20));

// wajp to print numbers in multiple ways

class Program1

public static void main(String args[])

int n1=10,n2=20;

System.out.printf("n1=%d n2=%d",n1,n2);

System.out.println("n1="+n1+" n2="+n2);

System.out.println("my values are"+n1+" and "+n2);

System.out.println(n1+" and "+n2+" are my numbers");

Method

 A method is a block of code which only runs when it is called. [OR]


 It is collection of statement to perform a specific task.

Syntax

return_type methodname()

statements;

}
JAVA
Class

 Class is a collection of data members and methods


 Here class is keyword.
 When we create the class memory will not be created
 In one program we can create only one same class.
 Every class will start with capital letter if two words then each word First letter
will be capital.

Syntax

class classname

data members;

methods;

Object

 Object is an instance of a class or variable of class.


 When we create the class, memory will not create for that class.
 To create a memory for the class we need to create an object.

Syntax

classname objname=new classname()

Variable

 variable is nothing but name of the memory location

Rules

1. Variable name must start with alphabet


2. Variable name can't start with number
3. We can't give space in between variable name
4. We can't use keywords as variable name
JAVA
Methods

 Method is a collection of statement to perform a specific task.

Methods are two types

1. Static method
2. Instance method.

1 Static method

 When we want to call logic one time then we go for static. When we want to
initialise static variable then we should create static method.
 A method which we will call w.r.t class name is known as static method.
 It is preceded with static keyword.
 One static method can call another static method directly if it is in same class.
 One static method can call another static method of another class by using
class name.
 One static method can call another non static method w.r.t object of the class.

2 Instance Method

 When we need to call logic repeatedly then we should use instance method
 A method which we will call w.r.t object is known as instance method.

Syntax

return_type methodname()

statements;

//Example program

class MainDemo

static void demo()

{
JAVA
System.out.println("this is demo method");

void display()

System.out.println("this is display method");

MainDemo.demo();//display calling demo by using class name because


demo is static method

void show()

System.out.println("this is show method");

display(); //show calling display directly because both are instance


method

static void fun()

System.out.println("this is fun method");

MainDemo m=new MainDemo();

m.show(); //fun calling show method by using object because show is


instance method

public static void main(String args[])

System.out.println("this is main method");

fun();//main calling fun directly because it is static method

}
JAVA
// Example program 2

class MetDemo

void display()

System.out.println(" i am in display non static");

void fun()

display();

MetDemo.show();

System.out.println("i am in fun non static");

static void show()

System.out.println("i am show static");

public static void main(String args[])

show();

MetDemo m=new MetDemo();

m.fun();

}
JAVA
// wajp to create multiple method in a class.

class Program1

void display()

System.out.println("Hello i am in program1 display");

void show()

System.out.println("Hello i am in program1 show");

void fun()

System.out.println("Hello i am in program1 fun");

class Program2

public static void main(String args[])

Program1 p=new Program1();

p.display();

p.show();

p.fun();

}
JAVA
Method overloading

Method Overloading allows different methods to have the same name, but
different signatures where the signature can differ by the number of input parameters
or type of input parameters, or a mixture of both.

1. No of parameter
2. Order of parameter
3. Type of parameter

//wajp for method overloading

class Program1

void display()

System.out.println("display without parameter");

void display(int a)

System.out.println("a="+a);

void display(float a)

System.out.println("a="+a);

void display(int a,int b)

System.out.println("a="+a+" b="+b);

void display(float a,int b)

{
JAVA
System.out.println("a="+a+" b="+b);

class Program2

public static void main(String args[])

Program1 p=new Program1();

p.display();

p.display(10);

p.display(10,10);

p.display(10.5f);

p.display(10.5f,10);

Types of variable

Instance variable

 Instance variable are object level variable which will create memory for every
object saprately.
 instance variable are not preceded with static keywords

Static variable

 Static variables are preceded with static keyword and it will create only one
copy of a memory for a program
 It can call with respect to class name or object name
 Static variables are called as class level variable and instance variable are
called object level variable.
JAVA
//wajp for instance variable and static variable

class Employee

String name;

int mobile; //instance variable

static String dept="Cse"; //static variable

Employee(String name, int mobile) {

this.name = name;

this.mobile = mobile;

void getdisplay()

System.out.println("name:-"+name);

System.out.println("depy:-"+Employee.dept);

System.out.println("mobile:-"+mobile);

public class EmpDemo {

public static void main(String[] args)

Employee e=new Employee("prem",9030);

e.getdisplay();

Employee e1=new Employee("rama",9030);

e1.getdisplay();

}
JAVA
Constructor

 It is used to set the default values for the data members.

Rules

1. Constructor name must be same as class name.


2. Constructor will call automatically when object is created.
3. Constructor will not have return type.
4. Constructor will call only when object is created.

Types of Constructors

1. Default constructor
2. Parameterized constructor

Default constructor

 When we want set same default values for all object then we will go with
default constructor.

//wajp for constructor

import java.util.Scanner;

class Demo1

int a,b;

Scanner s=new Scanner(System.in);

Demo1()

a=100;

b=200;

void readNumber()

System.out.println("Enter the two number");

a=s.nextInt();
JAVA
b=s.nextInt();

void display()

System.out.println(a+" "+b);

public class ConDemo

public static void main(String[] args)

Demo1 d=new Demo1();

d.display();

Parameterised constructor

 When constructor had parameter then it is known as parameterized


constructor.
 When we want to set different default values for every object then we should
go for parameterized constructor.

//wajp for parameterized constructor

import java.util.Scanner;

class Demo1

int a,b;

Scanner s=new Scanner(System.in);


JAVA
Demo1(int x,int y)

a=x;

b=y;

void display()

System.out.println(a+" "+b);

public class ConDemo

public static void main(String[] args)

Demo1 d=new Demo1(10,20);

d.display();

Demo1 d1=new Demo1(20,30);

d1.display();

Demo1 d2=new Demo1(45,65);

d2.display();

}
JAVA
Mixed constructor or constructor overloading

 When we have multiple constructors with different data types then it is known
as mixed constructor or constructor overloading.

//wajp for mixed constructor or constructor


import java.util.Scanner;

class Demo1

int a,b;

Scanner s=new Scanner(System.in);

Demo1() //defalt constructor

a=1;

b=1;

System.out.println("default constructor "+a+" "+b);

Demo1(int x,int y) //parameterised constructor

a=x;

b=y;

System.out.println("parameterised constructor "+a+" "+b);

Demo1(int y) //parameterised constructor

a=1;

b=y;
JAVA
System.out.println("1 parameter constructor"+a+" "+b);

public class ConDemo

public static void main(String[] args) {

Demo1 d=new Demo1();

Demo1 d1=new Demo1(20,30);

Demo1 d2=new Demo1(100);

"This keyword"

Whenever class level variables and method level variables are same then use
"this " keyword with class level variables.

class Demo1 {

int a,b;

Demo1(int a,int b)

this.a=a;

this.b=b;

void display()

System.out.println(a+" "+b);

}
JAVA
public class ConDemo

public static void main(String[] args)

Demo1 d1=new Demo1(20,30);

d1.display();

Inheritance
It is the mechanism in java by which one class is allowed to inherit the
features (fields and methods) of another class.

Important terminology:

Super Class: The class whose features are inherited is known as a super class (or a
base class or a parent class).

Sub Class: The class that inherits the other class is known as a sub class (or a
derived class, extended class, or child class). The subclass can add its
own fields and methods in addition to the super class fields and
methods.

Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to


create a new class and there is already a class that includes some of
the code that we want, we can derive our new class from the existing
class. By doing this, we are reusing the fields and methods of the
existing class.

Types of inheritance

It is divided into 5 types

1. Single inheritance

2. Multilevel inheritance

3. Multiple inheritance

4. Hierarchical inheritance

5. Hybrid inheritance
JAVA
Single inheritance
If we have one parent and one child class is known as single inheritance.

Multilevel inheritance
When we have one parent class, one child class and multiple intermediate
classes then it is known as multilevel inheritance.

Multiple inheritance
When two class details are coming into one class is known as multiple
inheritance and this does not support in java

Note: it is not possible because if two classes are having same method then there
will be problem in child class.

Hierarchical inheritance
when one class giving features to multiple classes is known hierarchical inheritance

Hybrid inheritance
combination of any two inheritance is known as hybrid inheritance

//wajp for single inheritance

class Iphone1

void display()

System.out.println("16 inches");

void camera()

System.out.println("camera 15mg px");

}
JAVA
class Iphone2 extends Iphone1

void selfiecamera()

System.out.println("selfiecamera available");

public class Phone {

public static void main(String[] args)

Iphone1 i1=new Iphone1();

i1.display();

i1.camera();

Iphone2 i2=new Iphone2();

i2.display();

i2.camera();

i2.selfiecamera();

//wajp for multilevel inheritance

class Iphone1

void display()

System.out.println("16 inches");
JAVA
}

void camera()

System.out.println("camera 15mg px");

class Iphone2 extends Iphone1

void selfiecamera()

System.out.println("selfiecamera available");

class Iphone3 extends Iphone2

void facerec()

System.out.println("face recog");

public class Phone {

public static void main(String[] args)

Iphone2 i2=new Iphone2();

i2.display();
JAVA
i2.camera();

i2.selfiecamera();

i2.facerec();

//wajp for heirachical inheritance

class charger

void charging()

System.out.println("charging ");

class Iphone extends charger

void iphone()

System.out.println("iphone details");

class Samsung extends charger {

void sam()

System.out.println("Samsung details");

}
JAVA
}

public class Phone {

public static void main(String[] args)

Iphone i=new Iphone();

i.charging();

i.iphone();

Samsung s=new Samsung();

s.charging();

s.sam();

IS-A RELATIONSHIP
When we take one class properties into another class by using inheritance is known as IS-A
Relationship.

HAS-A RELATIONSHIP
When we take one class properties into another class by creating object of one class into the
method of another class is known as HAS-A Relationship.

//wajp for Has-A relationship

class Iphone1

void display()

System.out.println("16 inches");

}
JAVA
void camera()

System.out.println("camera 15mg px");

class Iphone2

void selfiecamera()

System.out.println("selfiecamera available");

Iphone1 i1=new Iphone1();

i1.display();

i1.camera();

public class Phone

public static void main(String[] args)

Iphone2 i2=new Iphone2();

i2.selfiecamera();

}
JAVA
Method overriding
when parent class and child has same method then it is known as method overriding.

class Iphone1 {

void display() {

System.out.println("16 inches");

void camera()

System.out.println("camera 15mg px");

class Iphone2 extends Iphone1

void camera()

System.out.println("camera 20px");

public class Phone {

public static void main(String[] args)

Iphone2 i2=new Iphone2();

i2.display();

i2.camera();

}
JAVA
super in java
variable level
When parent class and child class variable are same, and from child class
you want to call parent class variable then we will used super with parent class
variable.

class Iphone

int a=10000;

class Iphone2 extends Iphone

int a=20000;

void camera()

System.out.println("Iphone a="+super.a);

System.out.println("Iphone2 a="+a);

public class Demo

public static void main(String[] args)

Iphone2 i=new Iphone2();

i.camera();

}
JAVA
method level
When parent class and child class has same method, and from child class
you want to call parent class method then we will use super with parent class
method.

//write a program for super keyword

class Iphone

void display()

System.out.println("5 inch display");

void camera()

System.out.println("16mp camera");

class Iphone2 extends Iphone

void camera()

System.out.println("32mp camera");

super.camera();

public class Demo

{
JAVA
public static void main(String[] args)

Iphone2 i=new Iphone2();

i.display();

i.camera();

Final in java
final supports at three levels

1.variable level

2.method level

3.class level

1.variable level

If we make any variable as final then we can't change value of a variable.

class Iphone

final int a=20;

void camera()

System.out.println("a="+a);

}
JAVA
public class Demo

public static void main(String[] args)

Iphone i=new Iphone();

i.camera();

2.final at method level

If we make any method as final then we can't override that method only you can use
that method in child classes.

//write a program for final keyword at method level

class Iphone

final void camera()

System.out.println("Iphone Camera");

public class Demo {

public static void main(String[] args)

Iphone2 i=new Iphone2();

i.camera();

}
JAVA
3.class level

If you make any class as final then we can't inherite that class properties into child
classes.

//write a program for final keyword at class level

final class Iphone

void camera()

System.out.println("Iphone Camera");

public class Demo

public static void main(String[] args)

Iphone2 i=new Iphone2();

i.camera();

class Employee1

final int a=10; //final at variable

void getdisplay()

System.out.println("A:-"+a);

}
JAVA
public class EmpDemo1

public static void main(String[] args)

Employee1 e=new Employee1();

e.getdisplay();

POLYMORPHISM
The process of representing one form in multiple ways is known as polymorphism.

In java original method represent one form and overrided method represent multiple
ways.

In Java polymorphism is mainly divided into two types:

1. Compile-time Polymorphism (method overloading)


2. Runtime Polymorphism (method overriding)

DYNAMIC BINDING
The process of binding appropriate version of derived classes which are inherited
from base class with base class object is known as dynamic binding.

 In dynamic binding we always create the object of base class.

 It is always used for executing polymorphic based applications.

advantage using dynamic binding

1. Less memory space

2. Less execution time

3. Performance will increase


JAVA
//wajp for polymorphism and dynamic binding

class BaseClass

void sum()

System.out.println("this is sum");

class Child1 extends BaseClass

void sum()

int a=10;

int b=20;

System.out.println(a+b);

class Child2 extends BaseClass

void sum()

float a=10;

float b=20;

System.out.println(a+b);

}
JAVA
public class LambdaDemo {

public static void main(String[] args) {

BaseClass b=new BaseClass();

b.sum();

b=new Child1();

b.sum();

b=new Child2();

b.sum();

Abstraction
Abstract Method

If a method does not have body is known as abstract method abstract method
preceded with abstract keyword.

Ex : abstract void display();

Classes are divided into two types

1. Concrete class
2. Abstract class

Concrete class

 If a class has fully defined methods then it known as concrete class.

example

class Demo1 {

void display()

System.out.println("Hello");

}
JAVA
Abstract Class

 If a class has atleast one abstract method then it is known as abstract class.
 If class is abstract you can't create object of that class
 If your inheriting abstract class feature then you must override abstract
method otherwise your class will become abstract class.

example

abstract class AbsDemo

abstract void display();

//wajp for abstract class

abstract class BaseClass

abstract void display();

abstract void show();

abstract class Child1 extends BaseClass

void display()

int a=10;

int b=20;

System.out.println(a+b);

class Child2 extends Child1


JAVA
{

void show()

System.out.println("this is show Overrided method");

public class AbsDemo {

public static void main(String[] args)

Child2 b=new Child2();

b.display();

b.show();

Null body method

when we write empty body method in class then it is known as null body method.

example

class Demo1

void display()

}
JAVA
Interface
 Interface is a collection of abstract method.
 We can't create the object of interface.
 To use interface details we will use implements keyword.

in interface writing abstract to method is optional even if you don't write your method
will be public abstract void display();

Syntax

interface interface_name

abstract method

//wajp for interface

interface I1

void display();

interface I1

public abstract void display();

interface I2 extends I1

public abstract void show();

abstract class Idemo implements I1,I2

{
JAVA
public void display()

System.out.println("Overrided method of display");

class Idemo1 extends Idemo

public void show()

System.out.println("Overrided method of show");

class Imain

public static void main(String args[])

Idemo1 i1=new Idemo1();

i1.display();

i1.show();

}
JAVA
interface to interface

It means taking one interface details into another interface.

we use extends keyword to take one interface details into another interface.

example

interface I1

interface I2 extends I1

default method
when we want to make any method optional in interface then we will make
that method as default method in interface.

Once we make any method as default then overriding that method is optional.

example

interface I1

void display();

default void show() //void show is default method.

System.out.println("show method is default method");

}
JAVA
//wajp for default method

interface I1

void display();

default void show()

System.out.println("show method is default method");

class InDemo implements I1

public void display()

System.out.println("i am overrided method display");

class IMain

public static void main(String args[])

InDemo i1=new InDemo();

i1.display();

}
JAVA
Lambda Expressions
 Lambda Expressions were added in Java 1.8.

 A lambda expression is a short block of code which takes in parameters and


returns a value.

 Lambda expressions are similar to methods, but they do not need a name and
they can be implemented right in the body of a method.

Syntax

The simplest lambda expression contains a single parameter and an expression:

parameter -> expression

//java program for lambda expression

interface I1

void display();

public class LambdaDemo

public static void main(String[] args)

I1 i=()->System.out.println("i1 data written in this display function");

i.display();

i.display();

}
JAVA
//java program for lambda expression with parameter

interface I1 {

void sum(int a,int b);

public class LambdaDemo

public static void main(String[] args)

I1 i=(a,b)->System.out.println("sum="+(a+b));

i.sum(10,20);

i.sum(100, 200);

//java program to square of a number using lambda expression

interface I1

int sqrt(int a);

public class LambdaDemo

public static void main(String[] args)

I1 i= (a)->a*a;

System.out.println(i.sqrt(5));

}
JAVA
GENERIC CLASS
A Generic class simply means that the items or functions in that class can
be generalized with the parameter(example T) to specify that we can add any type
as a parameter in place of T like Integer, Character, String, Double or any other
user-defined type.

class Test <T>

T obj;

Test(T obj)

this.obj = obj;

public T getObject()

return this.obj;

// Driver class to test above

class Main

public static void main (String[] args)

Test <Integer> iObj = new Test<Integer>(15);

System.out.println(iObj.getObject());
JAVA
Test <String> sObj =new Test<String>("prsoftwares");

System.out.println(sObj.getObject());

Test <Float> sObj1 =new Test<Float>(10.5f);

System.out.println(sObj1.getObject());

Inner Classes (Nested Classes)


 Java inner class or nested class is a class that is declared inside the class or
interface.
 We should go with this concept when one class is dependent on another class.
 We use inner classes to logically group classes and interfaces in one place to be
more readable and maintainable.
 Additionally, it can access all the members of the outer class, including private
data members and methods.

//wajp for Inner Class

class University

void show()

System.out.println("University Information");

class College

void department()

{
JAVA
System.out.println("Department Information");

public class InnerClass

public static void main(String[] args)

University u=new University();

u.show();

University.College cg=u.new College();

cg.department();

Exception Handling
Errors are two types

1. Compile time error

2. Run time error

Compile time error


When we compile the program and we are getting an error due to wrong syntax then
it is known as compile time error.

Example: semilcolon missing, bracket missing, Etc…

Run time error


Due to wrong input given by user if we are getting system error messages is known
as run time error.
JAVA
Exception Handling
Converting system error messages into user friendly messages is known as
exception handling.

syntax

try

Block of statements which generate exception

catch (Type_of_exception1 object1)

Block of statements which provides user friendly messages;

finally

Block of statements which releases the resources;

Try block:

3. This is the block in which we write the block of statements which are to be
monitored by JVM at run time i.e., try block must contain those statements which
causes problems at run time.

4. If any exception is taking place the control will be jumped automatically to


appropriate catch block.

5. If any exception is taking place in try block execution will be terminated and the
rest of the statements in try block will not be executed at all and the control will
go to catch b lock.

6. For every try block we must have at least one catch block. It is highly
recommended to write ‘n’ number of catch’s for ‘n’ number of problematic
statements.
JAVA
Catch block:

1. This is used for providing user friendly messages by catching system error
messages.

2. In the catch we must declare an object of the appropriate execution class and it
will be internally referenced JVM whenever the appropriate situation taking place.

3. If we write ‘n’ number of catch’s as a part of JAVA program then only one catch
will be executing at any point.

4. After executing appropriate catch block even if we use return statement in the
catch block the control never goes to try block.

Finally block:

1) This is the block which is executing compulsory whether the exception is taking
place or not.

2) This block contains same statements which releases the resources which are
obtained in try block (resources are opening files, opening databases, etc.).

3) Writing the finally block is optional.

//wajp for try and catch block

import java.util.Scanner;

import java.util.InputMismatchException;

public class EmpDemo1

public static void main(String[] args)

Scanner s=new Scanner(System.in);

try

int a,b;

System.out.println("Enter the number");


JAVA
a=s.nextInt();

System.out.println("Enter the number");

b=s.nextInt();

System.out.println(a/b);

catch(InputMismatchException e)

System.out.println("please Enter only numbers");

catch(ArithmeticException e) {

System.out.println("please dont Enter zero for denominator");

finally

System.out.println("database closed compulsory logic");

throws keyword: This is the keyword which gives an indication to the calling function
to keep the called function under try and catch blocks.

Syntax:

<Return type> method name (number of parameters if any) throws type of

exception1,type of exception2,………type of exception;


JAVA
PACKAGE
A package is a collection of classes, interfaces and sub-packages. A sub-
package in turns divides into classes, interfaces, sub-sub-packages, etc.

1. User defined packages


2. Predefined packages

Learning User about JAVA is nothing but learning about various packages. By
default one

Predefined package is imported for each and every JAVA program and whose
name is java.lang.*.

Whenever we develop any java program, it may contain many number of user
defined classes and user defined interfaces. If we are not using any package name
to place user defined classes and interfaces, JVM will assume its own package
called NONAME package.

In java we have two types of packages they are predefined or built-in or core
packages and user or secondary or custom defined packages.

USER DEFINED PACKAGES

A user defined package is one which is developed by java programmers


supplied as a part of their project to reused classes, interfaces and sub packages.
Which are commonly used. Any class or interface is commonly used by many java
programmers that class or interface must be placed in packages.

Syntax:

package pack1[.pack2[.pack3……[.packn]…..]];

Here, package is a keyword which is used for creating user defined packages,
pack1 represents upper package and pack2 to packn represents sub packages.

For example:

package p1; statement-1

package p1.p2; statement-2

Rules:-

1. Package must be first executable statement


2. In package every class and methods must be public
JAVA
The statements 1 and 2 are called package statements.

//wajp for creating a package

package prsoftwares.demo;

import java.util.Scanner;

public class PackDemo1

Scanner s=new Scanner(System.in);

int a,b;

public void sum()

System.out.println("Enter the two numbers");

a=s.nextInt();

b=s.nextInt();

System.out.println(a+b);

compile program by following command

javac -d . PackDemo1.java

//wajp to import above created package

import prsoftwares.demo.PackDemo1;

class PackagDemo {

public static void main(String args[]) {

PackDemo1 p=new PackDemo1();

p.sum();

}
JAVA
//wajp to write interface in package

package prsoftwares.demo;

public interface I1

void display();

//import above interface

import prsoftwares.demo.I1;

class InDemo implements I1

public void display()

System.out.println("i am in display method");

class MainI1

public static void main(String args[])

InDemo i=new InDemo();

i.display();

}
JAVA
ACCESS MODIFIER
In order to use the data from one package to another package or within the
package, we have to use the concept of access modifiers.

In JAVA we have four types of access specifiers. They are

1. Private : Private data accessible only within same class outside class
we can't access.
2. Defaults : This data can be access within same package. Outside the
package is not possible.
3. Protected : Protected data is accessible within the same file outside
package it is possible only if inherit parent class properties. But
independent class can't call.
4. Public : Public data is accessible anywhere in the package or outside
the package.

Access Within Within Outside package by Outside package


Modifier class package subclass only

Private Y N N N

Default Y Y N N

Protected Y Y Y N

Public Y Y Y Y

Access specifiers make us to understand how to access the data within the
package (class to class, interface to interface and interfaces to class) and across the
package (class to class, interface to interface and interfaces to class).

In other words access specifiers represent the visibility of data or accessibility of data.

Syntax for declaring a variable along with access specifiers:

[Access specifiers] [Static] [Final] data type v1 [=val1], v2 [=val2] … vn [=valn];


JAVA
package prsoftwares.demo;

public class MyDemo1

private int a=10;

public int b=20;

protected int c=30;

int d=40;

public void display()

System.out.println("data called in same class");

System.out.println(a+" "+b+" "+c+" "+d);

------------------------------

package prsoftwares.demo;

import prsoftwares.demo.MyDemo1;

public class MyDemo2 extends MyDemo1

public void show()

System.out.println("data called in derived class");

System.out.println(b+" "+c+" "+d);

------------------------------------
JAVA
import prsoftwares.demo.MyDemo1;

class MyDemo3 extends MyDemo1

public void fun()

System.out.println("data called other package derived class");

System.out.println(b+" "+c);

class MainDemo

public static void main(String args[])

MyDemo3 m1=new MyDemo3();

m1.fun();

MyDemo1 m=new MyDemo1();

System.out.println(m.b);

Encapsulation
Encapsulation in Java is a mechanism of wrapping the data (variables) and
code acting on the data (methods) together as a single unit. In encapsulation, the
variables of a class will be hidden from other classes, and can be accessed only
through the methods of their current class. Therefore, it is also known as data
hiding.
JAVA
public class EncapTest
{
private String name;
private String idNum;
private int age;
public int getAge()
{
return age;
}
public String getName()
{
return name;
}
public String getIdNum()
{
return idNum;
}

public void setAge( int newAge)


{
age = newAge;
}

public void setName(String newName)


{
name = newName;
}

public void setIdNum( String newId)


{
idNum = newId;
}
}
JAVA
PROPERTIES CLASS
The properties object contains key and value pair both as a string. The
java.util.Properties class is the subclass of Hashtable.

It can be used to get property value based on the property key. The
Properties class provides methods to get data from the properties file and store data
into the properties file. Moreover, it can be used to get the properties of a system.

An Advantage of the properties file

Recompilation is not required if the information is changed from a properties


file: If any information is changed from the properties file, you don't need to
recompile the java class. It is used to store information which is to be changed
frequently.

//wajp to use properties file in your program

import java.io.FileReader;

import java.util.Properties;

class TestMain

public static void main(String args[])

try

FileReader mr=new FileReader("D:\\java11am\\myfile.properties");

Properties p=new Properties();

p.load(mr);

System.out.println(p.getProperty("drivername"));

System.out.println(p.getProperty("username"));

System.out.println(p.getProperty("password"));
JAVA
System.out.println(p.getProperty("dbname"));

catch(Exception e)

System.out.println("this is exception");

String and stringBuffer


In order to deal with strings we have two classes. They are java.lang.String
and java.lang.StringBuffer.

What is the difference between String and StringBuffer classes?

Answer: String class is by default immutable (non-modifiable) and StringBuffer class


is mutable(modifiable).

Instance methods:

public char charAt (int); 1

public int length (); 2

public boolean equals (String); 3

public boolean equalsIgnoreCase (String); 4

public String concat (String); 5

public boolean startsWith (String); 6

public boolean endsWith (String); 7

StringBuffer class:

Whenever we create an object of StringBuffer we get 16 additional characters


memory space. Hence an object of StringBuffer is mutable object.
JAVA
StringBuffer API:

1. StringBuffer ()

2. StringBuffer (String)

3. StringBuffer (char [])

4. StringBuffer (int size)

COLLECTION
Collection

Whenever we want to store different types of data into the single unit then we
will use collection framework concept.

 It is dynamic in nature.
 We can add or remove data at any point of time for that collection has given
predefined methods.
 It has sorting and searching techniques inbuilt.

It is divided into two types

1D COLLECTION

2D COLLECTION

COLLECTION FRAMEWORK:

Collection framework is the standardized mechanism of grouping of similar or


dissimilar type of objects into a single object. This single object is known as
collection framework object.

Goals of collection frameworks:

1. Collection framework improves the performance of JAVA, J2EE projects


(when we want to transfer the bulk amount of data from client to server and
server to client, using collection framework we can transfer that entire data at
a time).
2. Collection framework allows us to prove similar or dissimilar type of objects.
3. Collection framework is dynamic in nature i.e., they are extends (arrays
contains the size which is fixed in nature and they allows similar type of data).
JAVA
4. Collection framework contains adaptability feature (adaptability is the process
of adding one collection object at the end of another collection object).
5. Collection framework is algorithmic oriented (collection framework contains
various sorting and searching techniques of data structures as a predefined
concepts).
6. In order to deal with collection framework we must import a package called
java.util.*

Collection framework is divided into two categories. They are new collection
framework and legacy (old) collection framework.

NEW COLLECTION FRAMEWORK:


New collection framework is again broadly divided into two categories. They
are one dimensional collection framework and two dimensional collection framework.

One dimensional collection frame work:


A one dimensional collection framework is one in which the data is organized
either in the form of row or in the form of column by containing similar or dissimilar
categories of objects into a single object. This single object is known as one
dimensional collection framework object. One dimensional collection framework
contains one dimensional collection framework interfaces and one dimensional
collection frame work classes.

a) One dimensional collection framework interfaces:

As a part of one dimensional collection framework interfaces in JAVA we have five


interfaces. They are collection, list, set, sorted set and queue.

Interfaces Classes

---------------------------------------------------------------------------------------------

Collection AbstractCollection implements Collection

List AbstractList extends AbstractCollection implements List

Set AbstractSet extends AbstractCollection implements Set

SortedSet AbstractSequentialList extends AbstractList implements S ortedSet

LinkedList extends AbstractSequential

ArrayList extends AbstractSequential


JAVA
HashSet extends AbstractSet

TreeSet extends AbstractSet

----------------------------------------------------------------------------------------------------------

//wajp for Retrieve elements in the list.

import java.util.ArrayList;

import java.util.Iterator;

import java.util.Scanner;

public class Test

public static void main(String[] args)

ArrayList ll=new ArrayList();

System.out.println(ll);

ll.add(10);

ll.add(10.5f);

ll.add("Megha");

ll.add('a');

Iterator itr=ll.iterator();

while(itr.hasNext())

System.out.println(itr.next());

}
JAVA
//wajp for adding only integer values to Array list

import java.util.ArrayList;

import java.util.Iterator;//Iterator=interface

import java.util.Scanner;

public class Test

public static void main(String[] args)

ArrayList<Integer> ll=new ArrayList<Integer>();

System.out.println(ll);

ll.add(10);

ll.add(80);

ll.add(50);

ll.add(90);

Iterator itr=ll.iterator();

while(itr.hasNext())

System.out.println(itr.next());

}
JAVA
HashSet V/S TreeSet

HashSet TreeSet

It extends AbstractSet. It extends AbstractSet and implements


SortedSet.

It follows hashing mechanism to organize It follows binary trees (AVL trees) to


its data. organize the data.

We cannot determine in which order it It always displays the data in sorted


displays its data. order.

Retrieval time is more. Retrieval time is less.

The operations like insertion,deletion and The operations like deletion and
modifications takes and modifications modifications takes more amount of time.
take very less time.

Creating HashSet is nothing but creating Creating TreeSet is nothing but creating
an object of HashSet () class. an object of TreeSet () class.

Two dimensional framework or maps:


Two dimensional framework organize the data in the form of (key,value) pair. The
value of key is an object and they must be unique. The value of value is also an
object which may or may not be unique. Two dimensional framework contains
collection of interfaces and collection of classes which are also known as map
interfaces and map classes.
JAVA
MULTI THREADING:
Thread:
1. A flow of control is known as thread.

2. If a program contains multiple flows of controls for achieving concurrent


execution then that program is known as multithreaded program.

3. A program is said to be a multithreaded program if and only if in which there


exist ‘n’ number of sub-programs there exist a separate flow of control. All such
flow of controls are executing concurrently such flow of controls are known as
threads and such type of applications or programs is called multithreaded
programs.

States of a thread:
When we write any multithreading applications, there exist ‘n’ numbers of threads.

All the threads will undergo different types of states. In JAVA for a thread we have
five states. They are new, ready, running, waiting and halted or dead state.

New state: It is one in which the thread about to enter into main memory.

Ready state: It is one in which the thread is entered into memory space allocated
and it is waiting for CPU for executing.

Running state: A state is said to be a running state if and only if the thread is under
the controls of CPU.

Waiting state: It is one in which the thread is waiting because of the following factors:

a) For the repeating CPU burst time of the thread (CPU burst time is an
amount of the required by the thread by the CPU).

b) Make the thread to sleep for sleep for some specified amount of time.

c) Make the thread to suspend.

d) Make the thread to wait for a period of time.

e) Make the thread to wait without specifying waiting time.

Halted state: It is one in which the thread has completed its total execution.
JAVA
As long as the thread is in new and halted states whose execution status is false
whereas when the thread is in ready, running and waiting states that execution
states is true

//wajp for multi thread.

class Test1 extends Thread

public void run()

for(int i=0;i<10;i++)

System.out.println("this is display");

public class Test {

public static void main(String[] args)

Test1 t=new Test1();

t.start();//thread 0

for(int i=0;i<10;i++)//main thread

System.out.println("This is main method");

}
JAVA
//wajp to check current thread name:

class Test1 extends Thread

public void run()

System.out.println("Thread name="+Thread.currentThread().getName());

for(int i=0;i<10;i++)

System.out.println("this is display");

public class Test {

public static void main(String[] args)

Test1 t=new Test1();

t.start();//thread 0

System.out.println("Thread name="+Thread.currentThread().getName());

for(int i=0;i<10;i++)//main thread

System.out.println("This is main method");

}
JAVA
Creating a thread:

In order to create a thread in JAVA we have two ways. They are by using

java.lang.Thread class and by using java.lang.Runnable interface.

In multi threading we get only one exception known as


java.lang.InterruptedException.

// wajp to create a thread

class Test {

public static void main(String[] args)

Thread t=new Thread();

System.out.println("Thread name="+t.getName());

Thread t1=new Thread();

System.out.println("Thread name="+t1.getName());

Thread t2=new Thread();

System.out.println("Thread name="+t2.getName());

Thread t3=new Thread();

System.out.println("Thread name="+t3.getName());

Instance methods:

public final void setName (String);

public final String getName ();

The above two methods are used for setting the name of the thread and getting the
name from the thread respectively.
JAVA
// wajp to set and get thread name:

class Test

public static void main(String[] args) {

Thread t=new Thread();

System.out.println("Thread name="+t.getName());

t.setName("Prsoftwares");

System.out.println("Thread name="+t.getName());

//wajp to print 1-10 numbers using 1 sec gap

class Test1 extends Thread

public void run()

try

for(int i=1;i<=10;i++)

System.out.println("the value of i="+i);

Thread.sleep(1000);//1 sec gap

catch(InterruptedException i)

System.out.println(i);
JAVA
}

public class Test {

public static void main(String[] args) {

Test1 t=new Test1();

t.start();

//wajp to implement multithreading using Runnable (Interface)

class Test1 implements Runnable{

public void run(){

try{

for(int i=1;i<=10;i++)

System.out.println("the value of i="+i);

Thread.sleep(1000);//1 sec gap

catch(InterruptedException i)

System.out.println(i);

}
JAVA
}

public class Test {

public static void main(String[] args) {

Test1 t1=new Test1();

Thread t=new Thread(t1);

t.start();

Daemon Thread :

 When you want to make threads to be dependent on main thread,Then we will


use Daemon Thread Concept.

 By default every thread is non-Daemon.

 Whenever we are setting Daemon,make sure we should set before start(It is


Mandatory).

//wajp for Daemon thread.

class daemonTh1 extends Thread

public void run()

try

for(int i=1;i<=10;i++)

System.out.println("score board score="+i);

Thread.sleep(1000);//1 sec gap


JAVA
}

catch(InterruptedException i)

System.out.println(i);

public class Test {

public static void main(String[] args) {

daemonTh1 t=new daemonTh1();

t.setDaemon(true);

t.start();

for(int i=1;i<=5;i++)

try {

System.out.println("Match is going on");

Thread.sleep(500);

catch(InterruptedException ie)

System.out.println(ie);

You might also like