Unit - 1
Unit - 1
For example, a Dog is part of the classification Mammal, which in turn is part of the Animal
class. Without the use of hierarchies, each object would need to define all of its characteristics
explicitly. However, by use of inheritance, an object need only define those qualities that make
it unique within its class. It can inherit its general attributes from its parent. Thus, inheritance
makes it possible for one object to be a specific instance of a more general case. There are five
types: Single, Multilevel, Hierarchical, Multiple and Hybrid.
For e.g., a dog’s sense of smell is polymorphic. If the dog smells a cat, it will bark and run after
it. If the dog smells its food, it will salivate and run to its bowl. The same sense of smell is at
work in both situations. The difference is what is being smelled, that is, the type of data being
operated upon by the dog’s nose.
Consider a stack (which is a last-in, first-out LIFO list). We might have a program that re-
quires three types of stacks. One stack is used for integer values, one for floating-point values,
and one for characters. The algorithm that implements each stack is the same, even though the
data being stored differs.
1.4 JAVA BUZZWORDS:
Simple:
Secure:
Portable:
• Java programs can execute in any environment for which there is a Java run-time
system.
• Java programs can run on any platform (Linux, Window, Mac)
• Java programs can be transferred over world wide web (e.g applets)
Object-oriented:
Robust:
• Java encourages error-free programming by being strictly typed and performing run-
time checks.
Multithreaded:
Architecture-neutral:
High performance:
Dynamic:
• Java programs carry substantial amounts of run-time type information with them that
is used to verify and resolve accesses to objects at run time.
Platform Independence: Java is renowned for its platform independence. Java programs are
compiled into bytecode, which can run on any system with a Java Virtual Machine (JVM). This
"write once, run anywhere" capability makes Java highly portable across different operating
systems and hardware architectures.
Syntax and Structure: Java's syntax is derived from C and C++, making it relatively easy for
programmers familiar with those languages to learn Java. Programs are organized into classes,
which contain methods (functions) and variables (fields). Java code is compiled into bytecode
before execution.
Standard Library: Java has an extensive standard library known as the Java Development Kit
(JDK). It provides a wide range of pre-built classes and APIs for tasks such as input/output,
networking, database connectivity, multithreading, graphical user interfaces (GUIs), and more.
The JDK also includes the Java Runtime Environment (JRE) required to run Java programs.
Exception Handling: Java has a robust exception handling mechanism. It allows developers
to handle exceptional situations during program execution, providing a structured way to catch
and handle errors, exceptions, and unexpected events.
Multithreading: Java provides built-in support for multithreading, enabling the concurrent
execution of multiple threads within a program. This allows for efficient utilization of system
resources and the development of concurrent and parallel applications.
Security: Java incorporates various security features, such as bytecode verification, class
loading restrictions, and a security manager. These measures help to create a secure execution
environment and protect against malicious code execution.
Large Community and Ecosystem: Java has a vast and active community of developers,
which has resulted in a rich ecosystem of libraries, frameworks, and tools. These resources
offer extensive support, open-source contributions, and a wide range of solutions for diverse
application development needs.
Application Domains: Java is used for a variety of applications, including enterprise software
development, web development (Java EE), mobile app development (Android), scientific and
numerical computing, game development, and more.
Data Types:
Java is a statically typed and also a strongly typed language. In Java, each type of data (such
as integer, character, hexadecimal, etc.) is predefined as part of the programming language and
all constants or variables defined within a given program must be described with one of the
data types. Data types represent the different values to be stored in the variable. In java, there
are two categories of data types:
• Array
• Class
• String
• Interface
Java defines eight primitive types of data: byte, short, int, long, char, float, double, and boolean.
The primitive types are also commonly referred to as simple types and they are grouped into
the following four groups:
i) Integers - This group includes byte, short, int, and long. All of these are signed, positive and
negative values. The width and ranges of these integer types vary widely, as shown in the
following table:
Name Width in bits Range
long 64 –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
int 32 –2,147,483,648 to 2,147,483,647
short 16 –32,768 to 32,767
byte 8 –128 to 127
ii) Floating-point numbers – They are also known as real numbers. This group includes float
and double, which represent single- and double-precision numbers, respectively. The width and
ranges of them are shown in the following table:
Name Width in bits Range
double 64 4.9e–324 to 1.8e+308
float 32 1.4e–045 to 3.4e+038
iii) Characters - This group includes char, which represents symbols in a character set, like
letters and numbers. char is a 16-bit type. The range of a char is 0 to 65,536. There are no
negative chars.
iv) Boolean - This group includes Boolean. It can have only one of two possible values, true
or false.
Variables:
A variable is the holder that can hold the value while the java program is executed. A variable
is assigned with a datatype. It is name of reserved area allocated in memory. In other words, it
is a name of memory location. There are three types of variables in java: local, instance and
static.
A variable provides us with named storage that our programs can manipulate. Each variable in
Java has a specific type, which determines the size and layout of the variable’s memory; the
range of values that can be stored within that memory; and the set of operations that can be
applied to the variable.
Before using any variable, it must be declared. The following statement expresses the basic
form of a variable declaration –
Here data type is one of Java’s data types and variable is the name of the variable. To de- clare
more than one variable of the specified type, use a comma-separated list.
Example
Types of Variables
• local variable
• instance variable
• static variable
Local Variable:
• Local variables are created when the method, constructor or block is entered
• Local variable will be destroyed once it exits the method, constructor, or block.
• Local variables are visible only within the declared method, constructor, or block.
• There is no default value for local variables, so local variables should be declared and
an initial value should be assigned before the first use.
• A variable declared inside the class but outside the method, is called instance variable.
Instance variables are declared in a class, but outside a method, constructor or any block.
• A slot for each instance variable value is created when a space is allocated for an
• Instance variables are created when an object is created with the use of the keyword
‘new’ and destroyed when the object is destroyed.
• Instance variables hold values that must be referenced by more than one method,
constructor or block, or essential parts of an object’s state that must be present throughout the
class.
• The instance variables are visible for all methods, constructors and block in the class.
It is recommended to make these variables as private. However, visibility for subclasses can be
given for these variables with the use of access modifiers.
○ Booleans it is false,
• Instance variables can be accessed directly by calling the variable name inside the class.
However, within static methods (when instance variables are given accessibility), they should
be called using the fully qualified name. ObjectReference.VariableName.
Static variable:
• Class variables also known as static variables are declared with the static keyword in a
class, but outside a method, constructor or a block.
• Only one copy of each class variable per class is created, regardless of how many
objects are created from it.
• Static variables are rarely used other than being declared as constants. Constants are
variables that are declared as public/private, final, and static. Constant variables never change
from their initial value.
• Static variables are stored in the static memory. It is rare to use static variables other
than declared final and used as either public or private constants.
• Static variables are created when the program starts and destroyed when the program
stops.
• Visibility is same as instance variables. However, most static variables are declared
public since they must be available for users of the class.
○ Booleans, it is false;
• Values can be assigned during the declaration or within the constructor. Additionally,
values can be assigned in special static initializer blocks.
• Static variables can be accessed by calling with the class name ClassName.
VariableName.
• When declaring class variables as public static final, then variable names (constants)
are all in upper case. If the static variables are not public and final, the naming syntax is the
same as instance and local variables.
Array:
Array is a collection of elements of similar data type stored in contiguous memory location.
The array size is fixed i.e we can’t increase/decrease its size at runtime. It is index based and
the first element is stored at 0th index.
Advantages of Array:
• Code Optimization: Multiple values can be stored under common name. Date retrieval
or sorting is an easy process.
• Random access: Data at any location can be retrieved randomly using the index.
Disadvantages of Array:
• Inefficient memory usage: Array is static. It is not resizable at runtime based on number
of user’s input. To overcome this limitation, Java introduce collection concept.
Types of Arrays
• Multidimensional Array
• Dynamic Array
• Jagged Array
Syntax:
Or
Here datatype can be a primitive data type like: int, char, Double, byte etc. arrayName is an
identifier.
Example:
int[] a;
Instantiation of an Array: Array can be created using the new keyword. To allocate memory
for array elements we must mention the array size. The size of an array must be specified by
an int value and not long or short. The default initial value of elements of an array is 0 for
numeric types and false for boolean.
Syntax:
arrayName=new datatype[size];
Or
int[] a=new int[5]; //defining an integer array for 5 elements Alternatively, we can create
and initialize array using following syntax.
Syntax:
Or
dataType[] arrayName={
Example:
int[] a={12,13,14};
The built-in length property is used to determine length of the array i.e. number of ele- ments
present in an array.
Accessing array elements: The array elements can be accessed by using indices. The index
starts from 0 and ends at (array size-1). Each element in an array can be accessed using for
loop.
Example:
class Main{
//printing array
System.out.println(a[i]);
}}
Sample Output:
10
20
30
40
The for-each loop: The for-each loop is used to traverse the complete array sequentially
without using an index variable. It’s commonly used to iterate over an array or a Collections
class (eg, Array- List).
Syntax:
for(type var:arrayName){
Example:
class Main{
sum+=i;
System.out.println(“Sum:”+sum);
}}
Sample Output:
Sum:100
Multidimensional Arrays: Multidimensional arrays are arrays of arrays with each element of
the array holding the reference of other array. These are also known as Jagged Arrays.
Syntax:
Example:
class TwoDimEx
// printing 2D array
System.out.print(arr[i][j] + “ “);
System.out.println();
}}}
Sample Output:
1 1 12
2 16 1
12 42 2
Jagged Array: Jagged array is an array of arrays with different row size i.e. with different
dimensions.
Example:
class Main {
int[][] a = {
{11, 3, 43},
{3, 5, 8, 1},
{9},
};
}}
Sample Output:
Length of row 1: 3
Length of row 2: 4
Length of row 3: 1
Example:
class Main{
int min=a[0];
for(int i=1;i<a.length;i++)
if(min>a[i])
min=a[i];
System.out.println(“Minimum:”+min);
int a[]={12,13,14,5};
}}
Sample Output:
Minimum:5
Example:
class Main{
for(int j=i+1;j<=a.length-1;j++) {
if(a[i]>a[j]){
tmp=a[i];
a[i]=a[j];
a[j]=tmp;
}}}
int a[]={33,43,24,5};
Operator in java is a symbol that is used to perform operations. Java provides a rich set of
operators to manipulate variables.For example: +, -, *, / etc.
All the Java operators can be divided into the following groups −
Arithmetic Operators:
• Multiplicative : * / %
• Additive :+-
Relational Operators
Bitwise Operators
Logical Operators
Assignment Operators:
• =
Ternary operator:
• ?:
Unary operator:
Arithmetic operators are used to perform arithmetic operations in the same way as they are
used in algebra. The following table lists the arithmetic operators −
Example:
The Relational Operators: The following relational operators are supported by Java language.
Example:
int A=10,B=20;
Operator Description Example Output
Checks if the values of two operands are equal or
== (equal to) not, if yes then condition becomes true. (A == B) true
}}
Bitwise Operators:
Java supports several bitwise operators, that can be applied to the integer types, long, int, short,
char, and byte. Bitwise operator works on bits and performs bit-by-bit operation.
Example:
a = 0011 1100
b = 0000 1101
~a = 1100 0011
int A=60,B=13;
>> (right The left operands value is moved right A >> 2 will give 15 15
by the number of bits speci- fied by the
shift) which is 1111 (in binary form:
right operand.
1111)
>>> (zero The left operands value is moved right A >>>2 will give 15 15
fill right by the number of bits speci- fied by the
shift) which is 0000 1111 (in binary form:
right operand and shifted values are
filled up with zeros. 0000 1111)
int a = 10;
int b = 20;
System.out.println(“a|b = “ + (a | b));
System.out.println(“a^b = “ + (a ^ b));
System.out.println(“~a = “ + ~a);
}}
Logical Operators:
A=true;
B=false;
Assignment Operators:
C <<= 2 is same
<<= Left shift AND assignment operator.
asC = C << 2
C >>= 2 is same
>>= Right shift AND assignment operator.
asC = C >> 2
C &= 2 is same
&= Bitwise AND assignment operator.
asC = C & 2
c = b;
System.out.println(“Value of c = “ + c);
a += 1;
b -= 1;
e *= 2;
f /= 2;
}}
Ternary Operator:
Conditional Operator ( ? : )
Since the conditional operator has three operands, it is referred as the ternary operator. This
operator consists of three operands and is used to evaluate Boolean expressions. The goal of
the operator is to decide, which value should be assigned to the variable. The operator is written
as –
Example:
int a, b;
a = 10;
b = (a == 0) ? 20: 30;
System.out.println( “b : “ + b );
}}
Unary Operators:
Unary operators use only one operand. They are used to increment, decrement or negate a
value.
Operator Description
- Unary minus negating the values
+ Unary plus converting a negative value to positive
++ :Increment operator incrementing the value by 1
— : Decrement operator decrementing the value by 1
! : Logical not operator inverting a boolean value
// Java program to illustrate unary operators
}}
Operator precedence determines the grouping of operands in an expression. This affects how
an expression is evaluated. Certain operators have higher precedence than others; for example,
the multiplication operator has higher precedence than the addition operator –
x = 10 + 5 * 2;
is evaluated. So, the output is 20, not 30. Because operator * has higher precedence than +.
The following table shows the operators with the highest precedence at the top of the table and
those with the lowest at the bottom. Within an expression, higher precedence operators will be
evaluated first.
Java Control statements control the flow of execution in a java program, based on data val- ues
and conditional logic used. There are three main categories of control flow statements;
Selection statements: The selection statements check the condition only once for the program
execution.
If Statement:
The if statement executes a block of code only if the specified expression is true. If the value
is false, then the if block is skipped and execution continues with the rest of the pro- gram.
<statement action>
if (a > b)
System.out.println(“a > b”);
if (a < b)
}}
The if/else statement is an extension of the if statement. If the condition in the if statement fails,
the statements in the else block are executed. The if-else statement has the following syntax:
if (<conditional expression>)
<statement action>
else
<statement action>
else
}}}
The switch case statement is also called as multi-way branching statement with several choices.
A switch statement is easier to implement than a series of if/else statements. The switch
statement begins with a keyword, followed by an expression that equates to a no long integral
value.
After the controlling expression, there is a code block that contains zero or more labeled cases.
Each label must equate to an integer constant and each must be unique. When the switch
statement executes, it compares the value of the controlling expression to the values of each
case label.
The program will select the value of the case label that equals the value of the control- ling
expression and branch down that path to the end of the code block. If none of the case label
values match, then none of the codes within the switch statement code block will be executed.
Java includes a default label to use in cases where there are no matches. A nested switch within
a case block of an outer switch is also allowed. When executing a switch statement, the flow
of the program falls through to the next case. So, after every case, you must insert a break
statement.
default: <statement>
} // end switch
status = 1;
}
else if (b > c)
status = 2;
else
status = 3;
switch (status)
break;
default:System.out.println(“Cannot be determined”);
}}}
Iteration statements: Iteration statements execute a block of code for several numbers of times
until the condition is true.
While Statement
The while statement is one of the looping constructs control statement that executes a block of
code while a condition is true. The loop will stop the execution if the testing expres- sion
evaluates to false. The loop condition must be a boolean expression.
<statements>
int count = 1;
System.out.println(count++);}
}}}
The do-while loop is similar to the while loop, except that the test condition is performed at the
end of the loop instead of at the beginning. The do—while loop executes atleast once without
checking the condition.
It begins with the keyword do, followed by the statements that making up the body of the loop.
Finally, the keyword while and the test expression completes the do-while loop. When the loop
condition becomes false, the loop is terminated and execution continues with the statement
immediately following the loop.
do
<loop body>
int count = 1;
do {
System.out.println(count++);
} while (count <= 10);
}}
For Loop
The for loop is a looping construct which can execute a set of instructions for a specified
number of times. It’s a counter controlled loop.
<loop body>
• initialization statement executes once before the loop begins. The <initialization>
section can also be a comma-separated list of expression statements.
• test expression. As long as the expression is true, the loop will continue. If this
expression is evaluated as false the first time, the loop will never be executed.
• Increment (Update) expression that automatically executes after each repetition of the
loop body.
• All the sections in the for-header are optional. Any one of them can be left empty, but
the two semicolons are mandatory.
System.out.println(count);
}}}
Transfer statements: Transfer statements are used to transfer the flow of execution from one
statement to an- other.
Continue Statement
A continue statement stops the current iteration of a loop (while, do or for) and causes execution
to resume at the top of the nearest enclosing loop. The continue statement can be used when
you do not want to execute the remaining statements in the loop, but you do not want to exit
the loop itself.
The syntax of the continue statement is
It is possible to use a loop with a label and then use the label in the continue statement. The
label name is optional, and is usually only used when you wish to return to the outermost loop
in a series of nested loops.
System.out.println(“Odd Numbers”);
if (i % 2 == 0)
continue;
System.out.println(i + “\t”);
}}}
Break Statement
The break statement terminates the enclosing loop (for, while, do or switch statement). Break
statement can be used when we want to jump immediately to the statement following the
enclosing control structure. As continue statement, can also provide a loop with a label, and
then use the label in break statement. The label name is optional, and is usually only used when
you wish to terminate the outermost loop in a series of nested loops.
System.out.println(“Numbers 1 - 10”);
if (i == 11)
break; // Rest of loop body skipped when i is even
System.out.println(i + “\t”);
}}}
The transferred statements such as try-catch-finally, throw will be explained in the later
chapters.
Java Comments
The java comments are statements that are not executed by the compiler and interpreter. The
comments can be used to provide information or explanation about the variable, method, class
or any statement. It can also be used to hide program code for specific time.
The single line comment is used to comment only one line. A single-line comment begins with
a // and ends at the end of the line.
Syntax Example
//Comment //This is single line comment
This type of comment must begin with /* and end with */. Anything between these two
comment symbols is ignored by the compiler. A multiline comment may be several lines long.
Syntax Example
/*Comment starts /* This is a
continues comment */
Commnent ends*/
c) Java Documentation Comment
This type of comment is used to produce an HTML file that documents our program. The
documentation comment begins with a /** and ends with a */.
Syntax Example
/**Comment start /**
* This
*such as <h1> */
*comment ends*/
A class is an entity that determines how an object will behave and what the object will contain.
A class is the basic building block of an object-oriented language such as Java. It is acting as a
template that describes the data and behavior associated with instances of that class.
When you instantiate a class means creating an object. The class contains set of variables and
methods.
The data associated with a class or object is stored in variables; the behaviour associated with
a class or object is implemented with methods. A class is a blueprint from which individual
objects are created.
class MyClass {
// field,
//constructor, and
// method declarations
Example:
class Myclass{
}}
The keyword class begins the class definition for a class named name. The variables and
methods of the class are embraced by the curly brackets that begin and end the class definition
block. The “Hello World” application has no variables and has a single method named main.
class name {
...
3. Superclass (if any): The name of the class’s parent (superclass), if any, preceded by
the keyword extends. A class can only extend (subclass) one parent.
1.10 CONSTRUCTORS:
Every class has a constructor. If the constructor is not defined in the class, the Java com- piler
builds a default constructor for that class. While a new object is created, at least one constructor
will be invoked. The main rule of constructors is that they should have the same name as the
class. A class can have more than one constructor.
Constructors are used for initializing new objects. Fields are variables that provide the state of
the class and its objects, and methods are used to implement the behavior of the class and its
objects.
• Constructor(s) of a class must have same name as the class name in which it resides.
Example
public myclass() {
// Constructor
}}
1. No-argument constructor:
A constructor that has no parameter is known as default constructor. If the constructor is not
defined in a class, then compiler creates default constructor (with no arguments) for the class.
If we write a constructor with arguments or no-argument then compiler does not create
default constructor. Default constructor provides the default values to the object like 0, null
etc. depending on the type.
import java.io.*;
class myclass
int num;
String name;
System.out.println(“Constructor called”);
}}
class myclassmain
{
// Default constructor provides the default values to the object like 0, null
System.out.println(m1.num);
System.out.println(m1.name);
}}
2. Parameterized Constructor
int num;
}}
class myclassmain{
}}
There are no “return value” statements in constructor, but constructor returns current class
instance. We can write ‘return’ inside a constructor.
Constructor Overloading
Like methods, we can overload constructors for creating objects in different ways. Compiler
differentiates constructors on the basis of numbers of parameters, types of the parameters and
order of the parameters.
import java.io.*;
class myclass
// Constructor with one argument but with different type than previous.
}}
class myclassmain
}}
• Constructor(s) must have the same name as the class within which it defined while it
• Constructor(s) do not any return type while method(s) have the return type or void if
• Constructor is called only once at the time of Object creation while method(s) can be
called any numbers of time.
Creating an Object
The class provides the blueprints for objects. The objects are the instances of the class. In Java,
the new keyword is used to create new objects.
1.11 METHODS:
A method is a collection of statement that performs specific task. In Java, each method is a part
of a class and they define the behavior of that class. In Java, method is a jargon used for method.
Advantages of methods
Types of methods
The standard library methods are built-in methods in Java programming to handle tasks such
as mathematical computations, I/O processing, graphics, string handling etc. These methods
are already defined and come along with Java class libraries, organized in packages. In order
to use built-in methods, we must import the corresponding packages. Some of library methods
are listed below.
Packages Library Methods Descriptions
java.lang.Math acos() Computes arc cosine of the argument
All maths related methods exp() Computes the e raised to given power
are defined in this class
abs() Computes absolute value of argument
log() Computes natural logarithm
sqrt() Computes square root of the argument
pow() Computes the number raised to given
power
java.lang.String charAt() Returns the char value at the specified
index.
All string related methods concat()
are defined in this class compareTo() Concatenates two string
Example:
Program to compute square root of a given number using built-in method. public class MathEx
{
Sample Output:
User-defined methods
The methods created by user are called user defined methods. Every method has the following.
Method Declaration
Syntax:
return_type method_name(parameter_list);
Here, the return_type specifies the data type of the value returned by method. It will be void if
the method returns nothing. method_name indicates the unique name assigned to the method.
parameter_list specifies the list of values accepted by the method.
Method Definition
Method definition provides the actual body of the method. The instructions to complete a
specific task are written in method definition. The syntax of method is as follows:
Syntax:
Here,
Modifier – Defines the access type of the method i.e accessibility re- gion of method
in the application
return_type – Data type of the value returned by the method or void if method returns
nothing
method_name – Unique name to identify the method. The name must follow the rules of
identifier
method body – block of code enclosed within { and } braces to perform specific task
The first line of the method definition must match exactly with the method prototype. A method
cannot be defined inside another method.
Method Call
A method gets executed only when it is called. The syntax for method call is.
Syntax:
method_name(parameters);
When a method is called, the program control transfers to the method definition where the
actual code gets executed and returns back to the calling point. The number and type of
parameters passed in method call should match exactly with the parameter list mentioned in
method prototype.
Example:
Method calls are implemented using stack. When a method is called, the parameters passed in
the call, local variables defined inside method, and return value of the method are stored in
stack frame. The allocated stack frame gets deleted automatically at the end of method
execution.
The methods in C are classified based on data flow between calling method and called method.
They are:
In this type of method, no value is passed in between calling method and called method. Here,
when the method is called program control transfers to the called method, executes the method,
and return back to the calling method.
Example:
Program to compute addition of two numbers (no argument and no return value)
public void add(){ // method definition with no arguments and no return value
int a=10,b=20;
System.out.println(“Sum:”+(a+b));
}}
Sample Output:
Sum:30
In this type of method, no value is passed from calling method to called method but a value is
returned from called method to calling method.
Example:
Program to compute addition of two numbers (no argument and with return value)
int a=10,b=20;
return(a+b);
int sum=0;
sum=obj.add();
System.out.println(“Sum:”+sum);
}}
Sample Output:
Sum:30
In this type of method, parameters are passed from calling method to called method but no
value is returned from called method to calling method.
Example:
Program to compute addition of two numbers (with argument and without return value)
System.out.println(“Sum:”+(x+y));
int a=10,b=20;
Sample Output:
Sum:30
In this type of method, there is data transfer in between calling method and called method.
Here, when the method is called program control transfers to the called method with argu-
ments, executes the method, and return the value back to the calling method.
Example:
Program to compute addition of two numbers (with argument and return value)
public int add(int x,int y){ // function definition with arguments and return value
System.out.println(“Sum:”+obj.add(a,b));
}}
Sample Output:
Sum:30
Access specifiers or access modifiers in java specifies accessibility (scope) of a data mem- ber,
method, constructor or class. It determines whether a data or method in a class can be used or
invoked by other class or subclass.
1. Private
2. Default (no speciifer)
3. Protected
4. Public
The details about accessibility level for access specifiers are shown in following table.
Private data fields and methods are accessible only inside the class where it is declared i.e
accessible only by same class members. It provides low level of accessibility. Encapsulation
and data hiding can be achieved using private specifier.
Example:
x=a; y=b;
}}
}}
In this example, we have created two classes PrivateEx and Main. A class contains private data
member, private constructor and public method. We are accessing these private members from
outside the class, so there is compile time error.
If the specifier is mentioned, then it is treated as default. There is no default specifier keyword.
Using default specifier we can access class, method, or field which belongs to same package,
but not from outside this package.
Example:
class DefaultEx{
System.out.println(obj.y);
}}
Sample Output:
10
In the above example, the scope of class DefaultEx and its data y is default. So it can be
accessible within the same package and cannot be accessed from outside the package.
Protected methods and fields are accessible within same class, subclass inside same pack- age
and subclass in other package (through inheritance). It cannot be applicable to class and
interfaces.
Example:
obj.show();
}}
Sample Output:
In Base
In this example, show() of class Base is declared as protected, so it can be accessed from outside
the class only through inheritance. Chapter 2 explains the concept of inheritance in detail.
The public access specifier has highest level of accessibility. Methods, class, and fields
declared as public are accessible by any class in the same package or in other package.
Example:
System.out.println(obj.no);
Sample Output:
10
In this example, public data no is accessible both by member and non-member of the class.
1.13 STATIC MEMBERS:
The static keyword indicates that the member belongs to the class instead of a specific instance.
It is used to create class variable and mainly used for memory management. The static keyword
can be used with:
Static variable: Variable declared with keyword static is a static variable. It is a class level
variable commonly shared by all objects of the class.
• Memory allocation for such variables only happens once when the class is loaded in the
memory.
• scope of the static variable is class scope (accessible only inside the class)
• Automatically initialized to 0.
Example:
Without static With static
StaticEx(){ StaticEx(){
System.out.println(no); System.out.println(no);
no++; no++;
} }
} }
public static void main(String[] args) public static void main(String[] args)
{ {
} }
} }
10 10
10 11
10 12
Static Method: The method declared with static keyword is known as static method. main() is
most common static method.
• A static method can directly access only static variables of class and directly invoke
only static methods of the class.
• It can be called through the name of class without creating any instance of that class.
For example, ClassName.methodName()
Example:
class StaticEx{
static int x;
int y=10;
System.out.println(“Non static method “+x); // non-static method can access static variable
}}
obj.show();
}}
Sample Output:
Static Method 0
In this example, class StaticEx consists of a static variable x and static method display(). The
static method cannot access a non-static variable. If you try to access y inside static method
display(), it will result in compilation error.
static context*/
Static Block: A static block is a block of code enclosed in braces, preceded by the keyword
static.
• The statements within the static block are first executed automatically before main
when the class is loaded into JVM.
• JVM combines all the static blocks in a class as single block and executes them.
• Static methods can be invoked from the static block and they will be executed as and
when the static block gets executed.
Syntax:
static{
…………….
Example:
System.out.println(“Constructor”);
}
static {
static{
static{
System.out.println(“Static in main”);
}}
Sample Output:
Static in main
Constructor
Nested class is a class declared inside another class. The inner class must be a static class
declared using keyword static. The static nested class can refer directly to static members of
the enclosing classes, even if those members are private.
Syntax:
class OuterClass{
……..
}}
We can create object for static nested class directly without creating object for outer class.
For example:
OuterClassName.InnerClassName=new OuterClassName.InnerClassName();
Example:
class Outer{
int y=20;
System.out.println(x+y); // nested class accessing its own data & outer class static data
}}}
class Main{
obj.show();
}}
Sample Output:
30
Static Import: The static import allows the programmer to access any static members of
imported class directly. There is no need to qualify it by its name.
Syntax:
• Less coding is required if you have accessed any static member of a class often.
Disadvantage:
Example:
class StaticImportEx{
}}
Sample Output:
Javadoc is a tool which comes with JDK and it is used for generating Java code documentation
in HTML format from Java source code, which requires documentation in a predefined format.
JavaDoc comments, which use a slash-star-star, star-slash ( /** … */ ) syntax, serve a different
purpose from inline comments and multi-line Java comments. Whereas inline and block Java
comments are read by other developers who maintain the code, JavaDoc comments are for
developers who use your code.
Javadoc comments are used to document Java classes, interfaces, methods, fields, and
constructors. They help in providing information about the purpose, behavior, parameters,
return values, and usage of the code elements. This documentation is especially useful for
developers who want to use the code or for those who need to maintain it.
/**
*/
// Class implementation
The class and interface documentation in Javadoc comments provides an overview of the
purpose and behavior of the class or interface. It typically includes a high-level description of
what the class or interface does and may include additional details such as usage guidelines,
examples, or any relevant information for developers using or extending the class/interface.
2) Method Documentation:
/**
*/
// Method implementation
Method documentation in Javadoc comments describes the purpose and behavior of a method.
It includes a description of what the method does, what parameters it takes (if any), what it
returns (if applicable), and any exceptions it might throw. These comments provide important
information for developers who want to use the method, helping them understand how to use
it correctly and handle any exceptions that may occur.
3) Field Documentation:
/**
*/
private int myField;
Field documentation in Javadoc comments provides information about a class's field (variable).
It typically includes a description of the field's purpose, any constraints or rules associated with
the field, and any other relevant details about the field's usage.
4)Constructor Documentation:
/**
*/
// Constructor implementation
Constructor documentation in Javadoc comments explains the purpose and behavior of a class
constructor. It includes a description of what the constructor does, what parameters it takes (if
any), and any additional information developers need to know when using the constructor to
create instances of the class.
In summary, Javadoc comments play a crucial role in documenting Java code and are an
essential part of creating well-documented APIs. They serve as a valuable reference for
developers, making it easier for them to understand, use, and maintain the code written by
others. Properly documented code with Javadoc comments is considered a best practice in Java
development.