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

Java Module I and II

Uploaded by

athullyamolsr06
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Java Module I and II

Uploaded by

athullyamolsr06
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

TechView Computer Institute Programming in Java

Module I
What is Java?
Java is a popular programming language, created in 1995.

It is owned by Oracle, and more than 3 billion devices run Java.

It is used for:

 Mobile applications (specially Android apps)


 Desktop applications
 Web applications
 Web servers and application servers
 Games
 Database connection

Java is a programming language and a platform. Java is a high level, robust, object-oriented and secure
programming language.

Java was developed by Sun Microsystems (which is now the subsidiary of Oracle) in the year 1995. James
Gosling is known as the father of Java.

Platform: Any hardware or software environment in which a program runs, is known as a platform. Since
Java has a runtime environment (JRE) and API, it is called a platform.

The major features of Java programming


Object Oriented
In Java, everything is an Object. Java can be easily extended since it is based on the Object model.
Platform Independent
Unlike many other programming languages including C and C++, when Java is compiled, it is not compiled
into platform specific machine, rather into platform-independent byte code. This byte code is distributed
over the web and interpreted by the Virtual Machine (JVM) on whichever platform it is being run on.
Simple
Java is designed to be easy to learn. If you understand the basic concept of OOP Java, it would be easy to
master.
Secure
With Java's secure feature it enables to develop virus-free, tamper-free systems. Authentication techniques
are based on public-key encryption.

TechView Computer Institute Page


TechView Computer Institute Programming in Java

Architecture-neutral
Java compiler generates an architecture-neutral object file format, which makes the compiled code
executable on many processors, with the presence of Java runtime system.
Portable
Being architecture-neutral and having no implementation dependent aspects of the specification makes Java
portable. The compiler in Java is written in ANSI C with a clean portability boundary, which is a POSIX
subset.
Robust
Java makes an effort to eliminate error-prone situations by emphasizing mainly on compile time error
checking and runtime checking.
Multithreaded
With Java's multithreaded feature it is possible to write programs that can perform many tasks
simultaneously. This design feature allows the developers to construct interactive applications that can run
smoothly.
Interpreted
Java byte code is translated on the fly to native machine instructions and is not stored anywhere. The
development process is more rapid and analytical since the linking is an incremental and light-weight
process.
High Performance
With the use of Just-In-Time compilers, Java enables high performance.
Distributed
Java is designed for the distributed environment of the internet.
Dynamic
Java is considered to be more dynamic than C or C++ since it is designed to adapt to an evolving
environment. Java programs can carry an extensive amount of run-time information that can be used to
verify and resolve accesses to objects at run-time.

First Java Program | Hello World Example


To create a simple java program, you need to create a class that contains the main method.

The requirement for Java Hello World Example


For executing any java program, you need to
o Install the JDK if you don't have installed it, download the JDK and install it.
o Set path of the jdk/bin directory. http://www.javatpoint.com/how-to-set-path-in-java
o Create the java program
o Compile and run the java program

TechView Computer Institute Page


TechView Computer Institute Programming in Java

Program:
class Simple{
public static void main(String args[]){
System.out.println("Hello Java");
}
}

Save this file as Simple.java

To compile: javac Simple.java


To execute: java Simple
Output:Hello Java

Compilation Flow:

When we compile Java program using javac tool, java compiler converts the source code into byte code.

o class keyword is used to declare a class in java.


o public keyword is an access modifier which represents visibility. It means it is visible to all.
o static is a keyword. If we declare any method as static, it is known as the static method. The core
advantage of the static method is that there is no need to create an object to invoke the static method.
The main method is executed by the JVM, so it doesn't require to create an object to invoke the main
method. So it saves memory.
o void is the return type of the method. It means it doesn't return any value.
o main represents the starting point of the program.
o String[] args is used for command line argument. We will learn it later.

TechView Computer Institute Page


TechView Computer Institute Programming in Java

o System.out.println() is used to print statement. Here, System is a class, out is the object of
PrintStream class, println() is the method of PrintStream class. We will learn about the internal
working of System.out.println statement later.

What is JVM?

JVM (Java Virtual Machine) is an abstract machine that enables your computer to run a Java program.

When you run the Java program, Java compiler first compiles your Java code to bytecode. Then, the JVM
translates bytecode into native machine code (set of instructions that a computer's CPU executes directly).

Java is a platform-independent language. It's because when you write Java code, it's ultimately written for
JVM but not your physical machine (computer). Since JVM executes the Java bytecode which is platform-
independent, Java is platform-independent.

JRE (Java Runtime Environment) is a software package that provides Java class libraries, Java Virtual
Machine (JVM), and other components that are required to run Java applications.
Java Comments

Comments can be used to explain Java code, and to make it more readable. It can also be used to prevent
execution when testing alternative code.

Single-line comments start with two forward slashes (//).

Any text between // and the end of the line is ignored by Java (will not be executed).

This example uses a single-line comment before a line of code:

Example

// This is a comment

System.out.println("Hello World");

TechView Computer Institute Page


TechView Computer Institute Programming in Java

Multi-line comments start with /* and ends with */.

Any text between /* and */ will be ignored by Java.

This example uses a multi-line comment (a comment block) to explain the code:

Java Variables and Data Types

Variables are containers for storing data values. A variable in Java must be a specified data type.

Data types specify the different sizes and values that can be stored in the variable. There are two types of
data types in Java:

1. Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float and
double.
2. Non-primitive data types: The non-primitive data types include Classes, Interfaces, and Arrays.

In Java, there are different types of variables, for example:

 String - stores text, such as "Hello". String values are surrounded by double quotes
 int - stores integers (whole numbers), without decimals, such as 123 or -123
 float - stores floating point numbers, with decimals, such as 19.99 or -19.99
 char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotes
 boolean - stores values with two states: true or false

Example

Create a variable called name of type String and assign it the value "John":

String name = "John";

System.out.println(name);

int myNum = 5; // Integer (whole number)

float myFloatNum = 5.99f; // Floating point number

char myLetter = 'D'; // Character

boolean myBool = true; // Boolean

String myText = "Hello"; // String

There are 8 types of primitive data types:

TechView Computer Institute Page


TechView Computer Institute Programming in Java

o boolean data type


o byte data type
o char data type
o short data type
o int data type
o long data type
o float data type
o double data type

Data Type Default Value Default size

boolean false 1 bit

char '\u0000' 2 byte

byte 0 1 byte

short 0 2 byte

int 0 4 byte

long 0L 8 byte

float 0.0f 4 byte

double 0.0d 8 byte

Java Operators
Operators are used to perform operations on variables and values.
There are many types of operators in Java which are given below:

o Unary Operator,
o Arithmetic Operator,
o Shift Operator,
o Relational Operator,
o Bitwise Operator,

TechView Computer Institute Page


TechView Computer Institute Programming in Java

o Logical Operator,
o Ternary Operator and
o Assignment Operator.

Java Operator Precedence

Operator Type Category Precedence

Unary postfix expr++ expr--

prefix ++expr --expr +expr -expr ~ !

Arithmetic multiplicative */%

additive +-

Shift shift << >> >>>

Relational comparison < > <= >= instanceof

equality == !=

Bitwise bitwise AND &

bitwise exclusive OR ^

bitwise inclusive OR |

Logical logical AND &&

logical OR ||

Ternary ternary ?:

Assignment assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=

Arithmetic Operators

Arithmetic operators are used to perform arithmetic operations on variables and data. For example,

TechView Computer Institute Page


TechView Computer Institute Programming in Java

Operator Operation

+ Addition

- Subtraction

* Multiplication

/ Division

% Modulo Operation (Remainder after division)

Assignment Operators

Assignment operators are used in Java to assign values to variables. For example,

int age;
age = 5;

Operator Example Equivalent to

= a = b; a = b;

+= a += b; a = a + b;

-= a -= b; a = a - b;

*= a *= b; a = a * b;

/= a /= b; a = a / b;

%= a %= b; a = a % b;

Relational Operators

Relational operators are used to check the relationship between two operands.

TechView Computer Institute Page


TechView Computer Institute Programming in Java

Operator Description Example

== Is Equal To 3 == 5 returns false

!= Not Equal To 3 != 5 returns true

> Greater Than 3 > 5 returns false

< Less Than 3 < 5 returns true

>= Greater Than or Equal To 3 >= 5 returns false

<= Less Than or Equal To 3 <= 5 returns false

Logical Operators

Logical operators are used to check whether an expression is true or false . They are used in decision
making.
Operator Example Meaning

&& (Logical expression1 && true only if both expression1 and expression2 are
AND) expression2 true

|| (Logical OR) expression1 || expression2 true if either expression1 or expression2 is true

! (Logical NOT) !expression true if expression is false and vice versa

Unary Operators

Unary operators are used with only one operand. For example, ++ is a unary operator that increases the
value of a variable by 1. That is, ++5 will return 6.
Different types of unary operators are:

Operator Meaning

+ Unary plus: not necessary to use since numbers are positive without using it

TechView Computer Institute Page


TechView Computer Institute Programming in Java

- Unary minus: inverts the sign of an expression

++ Increment operator: increments value by 1

-- Decrement operator: decrements value by 1

! Logical complement operator: inverts the value of a boolean

Bitwise Operators

Bitwise operators in Java are used to perform operations on individual bits.

The various bitwise operators present in Java are:

Operator Description

~ Bitwise Complement

<< Left Shift

>> Right Shift

>>> Unsigned Right Shift

& Bitwise AND

^ Bitwise exclusive OR

Other operators

Besides these operators, there are other additional operators in Java.

Java instanceof Operator

The instanceof operator checks whether an object is an instanceof a particular class.

Ternary Operator

The ternary operator (conditional operator) is shorthand for the if-then-else statement. For example,

TechView Computer Institute Page


TechView Computer Institute Programming in Java

variable = Expression ? expression1 : expression2

Here's how it works.

 If the Expression is true, expression1 is assigned to the variable.


 If the Expression is false, expression2 is assigned to the variable.

Java Arrays

Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each
value.

To declare an array, define the variable type with square brackets:

dataType[] arrayName;

 dataType - it can be primitive data types like int, char, double, byte, etc. or Java objects
 arrayName - it is an identifier
Example:

 String[] cars;

In Java, we can declare and allocate memory of an array in one single statement. For example,

 double[] data = new double[10];

In Java, we can initialize arrays during declaration. For example,

int[] age = {12, 4, 5, 2, 5};

In the Java array, each memory location is associated with a number. The number is known as an array
index. We can also initialize arrays in Java, using the index number. For example,

int[] age = new int[5];

// initialize array
age[0] = 12;

TechView Computer Institute Page


TechView Computer Institute Programming in Java

age[1] = 4;
age[2] = 5;

 Array indices always start from 0. That is, the first element of an array is at index 0.
 If the size of an array is n, then the last element of the array will be at index n-1.
The syntax for accessing elements of an array,

 // access array elements


 array[index]

A multidimensional array is an array of arrays. Each element of a multidimensional array is an array itself.
For example,

 int[][] a = new int[3][4];

Here, we have created a multidimensional array named a. It is a 2-dimensional array, that can hold a
maximum of 12 elements,

Java Class and Objects

Java is an object-oriented programming language.

Everything in Java is associated with classes and objects, along with its attributes and methods.

A Class is like an object constructor, or a "blueprint" for creating objects.

TechView Computer Institute Page


TechView Computer Institute Programming in Java

Create a Class

To create a class, use the keyword class:

class ClassName {
// fields
// methods
}

 fields are used to store data

 methods are used to perform some operations

Example:

class Bicycle {

// state or field
private int gear = 5;

// behavior or method
public void braking() {
System.out.println("Working of Braking");
}
}

Java Objects

An object is called an instance of a class.

Creating an Object in Java

className object = new className();


Example:
// for Bicycle class
Bicycle sportsBicycle = new Bicycle();

Bicycle touringBicycle = new Bicycle();

TechView Computer Institute Page


TechView Computer Institute Programming in Java

We have used the new keyword along with the constructor of the class to create an object. Constructors are
similar to methods and have the same name as the class.

Access Members of a Class

We can use the name of objects along with the . operator to access members of a class.

class Bicycle {

// field of class
int gear = 5;

// method of class
void braking() {
...
}
}

// create object
Bicycle sportsBicycle = new Bicycle();

// access field and method


sportsBicycle.gear;
sportsBicycle.braking();

Java Constructors

A constructor in Java is a special method that is used to initialize objects. The constructor is called when an
object of a class is created. It can be used to set initial values for object attributes.
A constructor has the same name as that of the class and does not have any return type.
Example:

class Test {

Test() {

// constructor body

}}

TechView Computer Institute Page


TechView Computer Institute Programming in Java

Rules for creating Java constructor

There are two rules defined for the constructor.

1. Constructor name must be the same as its class name


2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and synchronized

Types of Java constructors

There are two types of constructors in Java:

1. Default constructor (no-arg constructor)


2. Parameterized constructor

Java Default Constructor

A constructor is called "Default Constructor" when it doesn't have any parameter.

The default constructor is used to provide the default values to the object like 0, null, etc., depending on the
type.

Syntax of default constructor:


<class_name>(){}

Example:
class Geek
{
int num;
String name;

Geek()
{
System.out.println("Constructor called");
}
}
class GFG
{
public static void main (String[] args)
{
// this would invoke default constructor.

TechView Computer Institute Page


TechView Computer Institute Programming in Java

Geek geek1 = new Geek();


}
}

Java Parameterized Constructor

A constructor which has a specific number of parameters is called a parameterized constructor.

The parameterized constructor is used to provide different values to distinct objects.


If we want to initialize fields of the class with your own values, then use a parameterized constructor.
Example:
class Geek
{
// data members of the class.
String name;
int id;

Geek(String name, int id)


{
this.name = name;
this.id = id;
}
}

class GFG
{
public static void main (String[] args)
{
// this would invoke the parameterized constructor.
Geek geek1 = new Geek("adam", 1);
System.out.println("GeekName :" + geek1.name +
" and GeekId :" + geek1.id);
}
}

Java Copy Constructor

There is no copy constructor in Java. However, we can copy the values from one object to another like copy
constructor in C++.

There are many ways to copy the values of one object into another in Java. They are:

o By constructor
o By assigning the values of one object into another

TechView Computer Institute Page


TechView Computer Institute Programming in Java

o By clone() method of Object class

In this example, we are going to copy the values of one object into another using Java constructor.

//Java program to initialize the values from one object to another object.
class Student6{
int id;
String name;
//constructor to initialize integer and string
Student6(int i,String n){
id = i;
name = n;
}
//constructor to initialize another object
Student6(Student6 s){
id = s.id;
name =s.name;
}
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


Student6 s1 = new Student6(111,"Karan");
Student6 s2 = new Student6(s1);
s1.display();
s2.display();
}
}

finalize() method in Java


The finalize() method of Object class is a method that the Garbage Collector always calls just before the
deletion/destroying the object which is eligible for Garbage Collection, so as to perform clean -up activity.
Clean-up activity means closing the resources associated with that object like Database Connection or
Network Connection.

Syntax:
protected void finalize throws Throwable{}

TechView Computer Institute Page


TechView Computer Institute Programming in Java

Since Object class contains the finalize method hence finalize method is available for every java class
since Object is the superclass of all java classes. Since it is available for every java class hence Garbage
Collector can call the finalize method on any java object
Why finalize method is used()?
finalize() method releases system resources before the garbage collector runs for a specific object. JVM
allows finalize() to be invoked only once per object.

Module II
Inheritance in Java
Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a parent
object. It is an important part of OOPs (Object Oriented programming system).

Important terminology:
 Super Class: The class whose features are inherited is known as superclass(or a base class or a parent
class).
 Sub Class: The class that inherits the other class is known as a subclass(or a derived class, extended
class, or child class). The subclass can add its own fields and methods in addition to the superclass
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.

How to use inheritance in Java(Deriving a Class in Java)


A class can be derived from the base class in Java by using the extends keyword. This keyword is basically
used to indicate that a new class is derived from the base class using inheritance. It can also be said that it is
used to extend the functionality of the class.
The keyword used for inheritance is extends.

Syntax :
class derived-class extends base-class
{
//methods and fields
}
Example:

class Vehicle {

protected String brand = "Ford"; // Vehicle attribute

TechView Computer Institute Page


TechView Computer Institute Programming in Java

public void honk() { // Vehicle method

System.out.println("Tuut, tuut!");

class Car extends Vehicle {

private String modelName = "Mustang"; // Car attribute

public static void main(String[] args) {

// Create a myCar object

Car myCar = new Car();

// Call the honk() method (from the Vehicle class) on the myCar object

myCar.honk();

// Display the value of the brand attribute (from the Vehicle class) and the value of the modelName from
the Car class

System.out.println(myCar.brand + " " + myCar.modelName);

Types of inheritance in java

On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical.

In java programming, multiple and hybrid inheritance is supported through interface only.

TechView Computer Institute Page


TechView Computer Institute Programming in Java

Single Inheritance Example

When a class inherits another class, it is known as a single inheritance. In the example given below, Dog
class inherits the Animal class, so there is the single inheritance.

File: TestInheritance.java

class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}

Multilevel Inheritance Example

When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in the example
given below, BabyDog class inherits the Dog class which again inherits the Animal class, so there is a
multilevel inheritance.

File: TestInheritance2.java

TechView Computer Institute Page


TechView Computer Institute Programming in Java

class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}

Hierarchical Inheritance Example

When two or more classes inherits a single class, it is known as hierarchical inheritance. In the example
given below, Dog and Cat classes inherits the Animal class, so there is hierarchical inheritance.

File: TestInheritance3.java

class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();

TechView Computer Institute Page


TechView Computer Institute Programming in Java

c.meow();
c.eat();
//c.bark();//C.T.Error
}}

Why multiple inheritance is not supported in java?

To reduce the complexity and simplify the language, multiple inheritance is not supported in java.

The final Keyword


If you don't want other classes to inherit from a class, use the final keyword:

If you try to access a final class, Java will generate an error:

final class Vehicle {

...

class Car extends Vehicle {

...

Interface in Java

An Interface in Java programming is defined as an abstract type used to specify the behavior of a class. A Java
interface contains static constants and abstract methods. A class can implement multiple interfaces. In Java,
interfaces are declared using the interface keyword. All methods in the interface are implicitly public and
abstract.

Why use Java interface?

There are reasons to use interface. They are given below.

TechView Computer Institute Page


TechView Computer Institute Programming in Java

 It is used to achieve abstraction.


 By interface, we can support the functionality of multiple inheritance.

Syntax for Declaring Interface


interface {
//methods
}

To use an interface in your class, append the keyword "implements" after your class name followed by the
interface name.

Example for Implementing Interface


// Interface
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void sleep(); // interface method (does not have a body)
}

// Pig "implements" the Animal interface


class Pig implements Animal {
public void animalSound() {
// The body of animalSound() is provided here
System.out.println("The pig says: wee wee");
}
public void sleep() {
// The body of sleep() is provided here
System.out.println("Zzz");
}
}

class Main {
public static void main(String[] args) {
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
myPig.sleep();
}
}

The relationship between classes and interfaces

As shown in the figure given below, a class extends another class, an interface extends another interface, but
a class implements an interface.

TechView Computer Institute Page


TechView Computer Institute Programming in Java

Method overriding in java

Declaring a method in sub class which is already present in parent class is known as method overriding.
Overriding is done so that a child class can give its own implementation to a method which is already
provided by the parent class.

Usage of Java Method Overriding

 Method overriding is used to provide the specific implementation of a method which is already
provided by its superclass.
 Method overriding is used for runtime polymorphism

Rules for Java Method Overriding

1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
3. There must be an IS-A relationship (inheritance).

Example of method overriding

In this example, we have defined the run method in the subclass as defined in the parent class but it has
some specific implementation. The name and parameter of the method are the same, and there is IS-A
relationship between the classes, so there is method overriding.

//Java Program to illustrate the use of Java Method Overriding

//Creating a parent class.

class Vehicle{
//defining a method
void run(){System.out.println("Vehicle is running");}
}
//Creating a child class
class Bike2 extends Vehicle{
//defining the same method as in the parent class

TechView Computer Institute Page


TechView Computer Institute Programming in Java

void run(){System.out.println("Bike is running safely");}

public static void main(String args[]){


Bike2 obj = new Bike2();//creating object
obj.run();//calling method
}
}

Method Overloading in Java

Method Overloading is a feature that allows a class to have more than one method having the same name, if
their argument lists are different.

Advantage of method overloading

Method overloading increases the readability of the program.

Different ways to overload the method

There are two ways to overload the method in java

1. By changing number of arguments


2. By changing the data type

1) Method Overloading: changing no. of arguments

In this example, we have created two methods, first add() method performs addition of two numbers and
second add method performs addition of three numbers.

In this example, we are creating static methods so that we don't need to create instance for calling methods.

class Adder{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}
2) Method Overloading: changing data type of arguments

In this example, we have created two methods that differs in data type. The first add method receives two
integer arguments and second add method receives two double arguments.

TechView Computer Institute Page


TechView Computer Institute Programming in Java

class Adder{

static int add(int a, int b){return a+b;}


static double add(double a, double b){return a+b;}
}
class TestOverloading2{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}}

Difference between method overloading and method overriding in java

Constructor Overloading in Java


In Java, a constructor is just like a method but without return type. It can also be overloaded like Java
methods.

Constructor overloading in Java is a technique of having more than one constructor with different parameter
lists. They are arranged in a way that each constructor performs a different task. They are differentiated by
the compiler by the number of parameters in the list and their types.

Example of Constructor Overloading

//Java program to overload constructors

class Student5{
int id;

TechView Computer Institute Page


TechView Computer Institute Programming in Java

String name;
int age;
//creating two arg constructor
Student5(int i,String n){
id = i;
name = n;
}
//creating three arg constructor
Student5(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}

public static void main(String args[]){


Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
s1.display();
s2.display();
}
}

Access Modifiers in Java

The access modifiers in Java specifies the accessibility or scope of a field, method, constructor, or class. We
can change the access level of fields, constructors, methods, and class by applying the access modifier on it.

There are four types of Java access modifiers:

1. Private: The access level of a private modifier is only within the class. It cannot be accessed from
outside the class.
2. Default: The access level of a default modifier is only within the package. It cannot be accessed
from outside the package. If you do not specify any access level, it will be the default.
3. Protected: The access level of a protected modifier is within the package and outside the package
through child class. If you do not make the child class, it cannot be accessed from outside the
package.
4. Public: The access level of a public modifier is everywhere. It can be accessed from within the class,
outside the class, within the package and outside the package.

TechView Computer Institute Page


TechView Computer Institute Programming in Java

1) Private

The private access modifier is accessible only within the class.

Example

class A{
private int data=40;
private void msg(){System.out.println("Hello java");}
}

public class Simple{


public static void main(String args[]){
A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}
}
2) Default

If you don't use any modifier, it is treated as default by default. The default modifier is accessible only
within package. It cannot be accessed from outside the package. It provides more accessibility than private.
But, it is more restrictive than protected, and public.

3) Protected

The protected access modifier is accessible within package and outside the package but through inheritance
only.

The protected access modifier can be applied on the data member, method and constructor. It can't be
applied on the class.

It provides more accessibility than the default modifer.

4) Public
The public access modifier is accessible everywhere. It has the widest scope among all other modifiers.

TechView Computer Institute Page


TechView Computer Institute Programming in Java

Example

//save by A.java

package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java

package mypack;
import pack.*;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}

Java Package

A java package is a group of similar types of classes, interfaces and sub-packages.

Package in java can be categorized in two form, built-in package and user-defined package.

There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.

Advantage of Java Package

1) Java package is used to categorize the classes and interfaces so that they can be easily maintained.

2) Java package provides access protection.

3) Java package removes naming collision.

TechView Computer Institute Page


TechView Computer Institute Programming in Java

Simple example of java package

The package keyword is used to create a package in java.


//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}

import Keyword

The import keyword is used to import a package, class or interface.

How to access package from another package?

The different ways to access the package from outside the package.

1. import package.*;
2. import package.classname;

Example

//save by A.java

package pack;
public class A{

TechView Computer Institute Page


TechView Computer Institute Programming in Java

public void msg(){System.out.println("Hello");}


}
//save by B.java
package mypack;
import pack.A; //import pack.*;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}

Abstract class in Java


A class which is declared as abstract is known as an abstract class. It can have abstract and non-abstract
methods. It needs to be extended and its method implemented. It cannot be instantiated.

 An abstract class must be declared with an abstract keyword.


 It can have abstract and non-abstract methods.
 It cannot be instantiated.
 It can have constructors and static methods also.
 It can have final methods which will force the subclass not to change the body of the method.

Example of abstract class

abstract class A{}

Abstract Method in Java

A method which is declared as abstract and does not have implementation is known as an abstract method.

Example of abstract method

abstract void printStatus();//no method body and abstract

TechView Computer Institute Page

You might also like