0% found this document useful (0 votes)
9 views43 pages

Unit-I Java Notes-2-38

Java is an object-oriented programming language developed by Sun Microsystems in 1995, known for its platform independence and robust features. It utilizes a combination of compilation and interpretation, producing bytecode that can be executed on any machine with a Java Runtime Environment. Key features include automatic memory management, exception handling, and a rich set of data types, making it suitable for various applications from web to mobile development.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views43 pages

Unit-I Java Notes-2-38

Java is an object-oriented programming language developed by Sun Microsystems in 1995, known for its platform independence and robust features. It utilizes a combination of compilation and interpretation, producing bytecode that can be executed on any machine with a Java Runtime Environment. Key features include automatic memory management, exception handling, and a rich set of data types, making it suitable for various applications from web to mobile development.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Unit-I

Introduction:
 Java is an Object-oriented Programming language originally developed by Sun Micro
System and released in 1995, later acquired by Oracle.
 Java is a popular and powerful language used in app development, desktop
computing, and gaming. It was created by James Gosling, Mike Sheridan, and Patrick
Naughton.
 Java was developed as a part of the Green project. Initially, it was called Oak, later it
was changed to Java in 1995.
 Java was created based on C and C++. Java uses C syntax and many of the object-
oriented features are taken from C++.

History of Java:
 James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language
project in June 1991. The small team of sun engineers called Green Team.
 Originally designed for small, embedded systems in electronic appliances like set-top
boxes.
 Firstly, it was called “Greentalk” by James Gosling, and file extension was .gt.
 After that, it was called Oak and was developed as a part of the Green project. In
1995, Oak was renamed as “Java” because it was already a trademark by Oak
Technologies.
 Java is an island of Indonesia It is famous for its coffee beans

Java Essentials:
Java is a platform-independent, object-oriented programming language. Java
encompasses the following features:
 A High-level Language :- Java is a high-level language that looks very similar to C and
C++ but offers many unique features of its own.
 Java Bytecode :- Bytecode in Java is an intermediate code generated by the compiler,
such as Sun’s javac, that is executed by the JVM.

1
 Java Virtual Machine (JVM) :- JVM acts as an interpreter for the bytecode, which
takes bytecodes as input and executes it as if it was a physical process executing
machine code.
Java is designed to be architecturally neutral so that it can run on multiple platforms. The
same runtime code can run on any platform that supports Java.
Java Runtime Environment (JRE) includes JVM, class libraries, and other supporting files.
JRE = JVM + Core Java API libraries
JDK = JRE + development tools like compilers

Tools such as javac (compiler), java (interpreter), and others are provided in a bundle,
popularly known as Java Development Kit (JDK).
JAVA VIRTUAL MACHINE: -
 Java Virtual Machine (JVM) is a engine that provides runtime environment to drive
the Java Code or applications. It converts Java bytecode into machines language. JVM
is a part of Java Run Environment (JRE).
 In other programming languages, the compiler produces machine code for a particular
system. However, Java compiler produces code for a Virtual Machine known as Java
Virtual Machine.
Java bytecode executes on a virtual machine. The virtual machine runs on top of the
operating system.
This virtual machine is an emulation of a real Java
processor—a machine within a machine.

 The JVM is responsible for interpreting Java bytecode, and translating this into actions
or operating system calls.
 The JVM is responsible for catering to the differences between different platforms and
architectures which a user is using.

2
 JVM is platform dependent
 The JVM forms a part of a large system, the JRE. JRE varies according to the underlying
operating system and computer architecture.

JAVA FEATURES:
Here we list the basic features that make Java a powerful, object-oriented, and popular
programming language.
1. Platform Independence:

 Java is platform independent because it is


different from other languages like C, C++, etc.
which are compiled into platform specific
machines, Java is compiled to an intermediate
form called the bytecode.
 On compilation Java program is compiled into
bytecode. This bytecode is platform independent
and can be run on any machine, plus this
bytecode format also provide security. Any
machine with Java Runtime Environment can run
Java Programs.

2. Object Oriented:
 Java is a pure object-oriented language.
 In java, everything is an object. It supports all the features of the object-oriented
programming paradigm.
 The primitive data types java also implemented as objects using wrapper classes
 Java has been developed in a way that it allows the user to not only learn object-
oriented programming but to apply and practice it.

3
3. Both Compiled and Interpreted:
Java incorporates the elements of both interpretation and compilation.
 Java compiler converts Java Source code into Java bytecode. Bytecode is not machine
understandable
 This bytecode file (.class file) can be run on any operating system by using the Java
interpreter (java) for that platform.
 An interpreter reads one line of a program and executes it before going to the next
line. Interpreter converts bytecode into machine code and displays output.
 The biggest advantage of a compiled language is its fast performance, The
disadvantages include slower debugging and reduced portability to other platforms.
 In interpretation, The best part is: debugging is fast. Also, the programs are easily
transportable to other platforms (if an interpreter is available). The drawback is its
slow performance.
 Both Interpreter and machine code generator will work together and convert the
bytecode into machine readable form (i.e. Binary form)

4. Java Is Robust:
Java is a robust language because Java supports automatic memory management and
exception handling.

 Java automatically manages the allocation and deallocation of memory for the
program. Deallocation is completely automatic, because Java provides garbage
collection for unused objects.
 Java provides exception handling environment to avoid runtime errors.
5. Java Language Security features:
 Java has several language features that protect the integrity of the security system
and prevent
several common attacks.
Security Through Definition: Java is strict in its definition of the language:
 All primitive data types in the language have a specific size.
 All operations are defined to be performed in a specific order.
Security Through Lack of Pointer Arithmetic
Java does not have pointer arithmetic, so Java programmers cannot forge a pointer to
memory.
Security Through Garbage Collection
Garbage collection makes Java programs more secure and robust by automatically freeing
memory.
Security Through Strict Compile-Time Checking
The Java compiler performs extensive, stringent compile-time checking so that as many
errors as possible can be detected by the compiler.
6. Java is Multithreaded:
 A thread is a subprocess. Java supports multithreading,
4
 MULTITHREADING in Java is a process of executing two or more threads
simultaneously to maximum utilization of CPU

1.2 PROGRAM STRUCTURE :

 A Java application consists of a collection of


classes.
 A class is a template. An object is defined as an
instance of the class.
 Each instance (object) contains the members
(fields and methods) specified in the class.
 A field is one that holds a value.
 A method defines operations on the fields and
values that are passed as arguments to the
method

1.6.1 Execution Process of Java Program


The following three steps are used to create and execute a java program.
 Create a source code (.java file).
 Compile the source code using javac command.
 Run or execute .class file uisng java command.
Creating source code:
A java program must be written using any word processor (notepad / wordpad/ Ms-word)
 Open a Notepad
 Write the source code in the notepad as follows

class Example
{
public static void main(String args[ ])
{
[Link]("This is a simple Java program");
}
}
Saving the Source Code
 Select File | Save As from the notepad menu.
 In the ‘File name’ field, type [Link] ([Link]) .
 Click enter to save the file.
Note: Remember the path where you are saving the file.

Compiling source code:


 Java programs are compiled using DOS.
 For opening DOS, type cmd at the run prompt ( Windows + R) and move to the

5
folder that contains the saved [Link] file.
 Now compile the program using javac.

Syntax: javac [Link]

Key Notes: The file was saved in a folder “ java Programs” in the F drive.
cd\ command takes you to the top of the directory tree. In this case, to the "C:" drive .
To change the drive from "C:" to "F:", you should type "F:" and then press Enter .
To enter into folder , type cd Foldername and press enter.(Ex: cd Java Programs).

The javac compiler creates a file called [Link] (in the same directory).
This class contains the bytecode version of the program.

6
Running source code:
This bytecode will be executed by the Java interpreter using java followed by the class
name as shown below.
Syntax: java classname

Explanation:
1. The program begins with the program is
class Example
This line uses the keyword class to declare that a new class is being defined followed by
the class name, i.e., Example.
2. The next line is {
The entire class definition, including all its members, will be between the opening curly
brace ( { ) and the closing curly brace ( } ).

3. This line shows the main method for the class.


public static void main(String args[ ])
This is the line from where the program will start its execution. All applications in Java start
execution from main().
Every complete Java Application must contain a root class where the execution can begin. A
root class must contain a main method defined with the header, as shown in this line.

public It is an access specifier used to specify that the code can be called from anywhere.
It is called by the JVM.
static It is declared static because it allows main()to be called without having to
instantiate the class (i.e. object of the class) .

void It does not return a value. The keyword void simply tells the compiler that main()does
not return anything back to the caller, i.e., JVM.
String args[] It holds optional command line arguments passed to the class through
the Java command line.

4. It shows a print statement


[Link]("This is a simple Java program");

This line prints the string "This is a simple Java Program" on the standard output.
System is a predefined class.
The string (mentioned in double quotes) passed to the println method is displayed as it
is on the standard output.
All statements in Java are terminated by a semicolon (;).
Lines other than println() don’t end with a semicolon because they are technically not
statements.

7
1.3 DIFFERENCES BETWEEN JAVA AND C++

C+ JAVA
+
C++ is platform-dependent. Java is platform-independent.
C++ is mainly used for system programming. Java is mainly used for application
programming. It is widely used in window,
web-based,
enterprise and mobile applications.
C++ supports the goto statement. Java doesn't support the goto statement.
C++ supports multiple inheritance. Java doesn't support multiple inheritance
through class. It can be achieved by interfaces
in java.
C++ supports pointers. You can write pointer
There are no pointers in Java.
program in C++.
C++ uses compiler only. Java uses compiler and interpreter both.
C++ supports both call by value and call by Java supports call by value only. There is no call
reference. by reference in java.
C++ supports structures and unions. Java doesn't support structures and unions.

1.4 VARIABLES
Variable is a symbolic name refer to a memory location used to store values that can change during
the execution of a program.

In java, we use the following syntax to create variables.

Syntax:
data_type variable_name;
(or)
data_type variable_name_1, variable_name_2,...;
(or)
data_type variable_name = value;

8
(or)
data_
type
varia
ble_n
ame_1
=
value
,
varia
ble_n
ame_2
=
value
,...;

9
Example:

A variable declaration involves specifying the type (data type), name (identifier), and value (literal)
according to the type of the variable.

1.5 DATA TYPES :


Java programming language has a rich set of data types. The data type is a category of data stored in
variables. In java, data types are classified into two types and they are as follows.

 Primitive Data Types


 Non-primitive Data Types

Primitive Data Types


The primitive data types are built-in data types and they specify the type of value stored in a variable
and the memory size. The primitive data types do not have any additional methods.
In java, primitive data types includes byte, short, int, long, float, double, char, and boolean.

10
The following table provides more description of each primitive data type.
Default
Data type Meaning Memory size Range
Value
Whole
byte 1 byte -128 to +127 0
numbers
Whole
short 2 bytes -32768 to +32767 0
numbers
Whole
int 4 bytes -2,147,483,648 to +2,147,483,647 0
numbers
Whole -9,223,372,036,854,775,808 to
long 8 bytes 0
numbers +9,223,372,036,854,775,807
Fractional
float 4 bytes - 0.0
numbers
Fractional
double 8 bytes - 0.0
numbers
Single
char 2 bytes 0 to 65535 blank
character
unsigned
boolean 1 bit 0 or 1 0 (false)
char

class PrimitiveDt
{
public static void main(String args[])
{
[Link]("Size of byte is " + [Link] + " bits");
[Link]("Size of short is " + [Link] + " bits");
[Link]("Size of int is " + [Link] + " bits");
[Link]("Size of long is " + [Link] + " bits");
[Link]("Size of float is " + [Link] + " bits");
[Link]("Size of double is " + [Link] + "
bits"); [Link]("Size of char is " + [Link] +
" bits");
}
}

 To find and print size of any primitive data type we take help of its associated
11
wrapper class.

12
 Inside each wrapper class (Except Boolean type) there is SIZE property, which returns
amount of memory being allocated for that specific type of data in bits.

1.6 IDENTIFIER:
 Identifiers are names assigned to variables, constants, methods, classes, packages, and
interfaces.
 No limit has been specified for the length of a variable name. Identifiers can have letters,
numbers, underscores, and any currency symbol.
 Identifiers may only begin with a letter, underscore, or a dollar sign. Digits cannot be the first
character in an identifier.

Rules for Naming


1. The first character of an identifier must be a letter, an underscore, or a dollar sign ($).
2. The subsequent characters can be a letter, an underscore, dollar sign, or a digit. Note that
white spaces are not allowed within identifiers.
3. Identifiers are case-sensitive. This means that Total_Price and total_price are different
identifiers.
1.7 Keywords:
Keywords are predefined identifiers, which are used for a specific purpose and cannot be used
for identifying used defined classes, variables, methods, packages, and interfaces. All keywords are in
lower case.

FLOW OF CONTROL
Control flow statements help programmers make decisions about which statements to
execute and to change the flow of execution in a program.
The categories of control flow statements available in Java are
 Conditional Statements
 Loops
 Branch Statements
13
Conditional Statements
In java, the selection statements are also known as decision making statements or branching
statements. The selection statements are used to select a part of the program to be
executed based on a condition. Java provides the following selection statements.

 if statement
 if-else statement
 if-else if statement
 switch statement

[Link] if statement
It consists only true part, If the condition is True, then the block of statements is executed.
Syntax:
if(condition)
{

------- //Block of Statements


}
Example Program:
class If
{
public static void main(String args[])
{
if(20>18)
[Link]("20 is greater than 18");
}}
}

14
[Link] if…else statement
If the condition is True, then the true block of statements is executed and if it is False, then
the false block of statements is executed.
Syntax:
if(condition)
{
------- //Block of Statements
}
else
{
------- //Block of Statements
}

Example Program:

class Ifelse
{
public static void
main(String args[])
{ if(18>
20)
[Link]("18 is greater than
20"); else
[Link]("18 is less than 20");
}
}

[Link] if else if statement


Writing an if-statement inside else of an if statement is called if-else-if statement.

Syntax:
if(condition)
{
------- //Block of Statements
}
else if(condition)
{

15
}
else
{

}
------- //Block of Statements
------- //Block of StatementsExample Program:

class Ifelseif
{
public static void main(String args[])
{
int x=20, y=18,
z=22; if(x>y && x>z)
{
[Link]("Largest Number is "+x);
}
else if(y>z)
{
[Link]("Largest Number is "+y);
}
else
{
[Link]("Largest Number is "+z);
}
}
}

16
[Link] Switch statement
Java has a shorthand for multiple if statement-the switch statement. Using the switch
statement, one can select only one option from more number of options very easily.

Syntax:
switch(condition or value)
{
case value1: statement 1;
break;
case value2: statement 2;
break;
.
.
default: statement n;
}

Example Program:

class SwitchCaseDemo
{
public static void main(String args[])
{
char
c='B';
switch(c)
{
case 'A': [Link]("You entered
Sunday"); break;
case 'B': [Link]("You entered
Monday"); break;
case 'C': [Link]("You entered
Tuesday"); break;
case 'D': [Link]("You entered
Wednesday"); break;
case 'E': [Link]("You entered Thursday");
break;
case 'F': [Link]("You entered
Friday"); break;
case 'G': [Link]("You entered
Saturday"); break;
default: [Link]("Wrong choice");
}
}
}
17
1.13.2 Loops
The java programming language provides a set of iterative statements that are used to
execute a statement or a block of statements repeatedly as long as the given condition is
true. The iterative statements are also known as looping statements or repetitive
statements. Java provides the following iterative statements.
 while statement
 do-while statement
 for statement
 for-each statement

[Link] for Loop
The for statement is used to execute a single statement or a block of statements
repeatedly as long as the given condition is TRUE. To execute a code for a known number of
times, for loop is the right choice.
The for loop groups the following three common parts together into one statement:
(a) Initialization
(b) Condition
(c) Increment or decrement
Syntax:
for(initialization;Condition;Inc/Dec)
{

------- //Block of Statements


}

Example
:

18
Example Program 1:

class ForDemo
{
public static void main(String args[])
{
for(int i=1; i<=5; i++)
{
[Link]("I value" is "+i);
}
}
}

while Loop
The while statement is used to execute a single statement or block of statements repeatedly as
long as the given condition is TRUE. The while statement is also known as Entry control looping
statement.

Syntax:
while(Condition)
{

------- //Block of Statements


}

Example Program 1:

class Demo
{
public static void main(String args[])
{
int i=1;
while(i<=10
)
{
[Link]("i=
"+i); i++;
}
}
}

19
do-while Loop
A do-while loop is also used to repeatedly execute (iterate) a block of statements. But, in a
do- while loop the condition is evaluated at the end of the iteration. The do-while statement
is also known as the Exit control looping statement.

Syntax:
do
{

------- //Block of Statements


} while(Condition);

Example Program:

class DoWhile
{
public static void main(String args[])
{
int
i=1;
do
{
[Link]("i=
"+i); i++;
}while(i<=10);
}
}

for-each Loop
The Java for-each statement was introduced since Java 5.0 version. It provides an approach to
traverse through an array or collection in Java. The for-each statement also known as
enhanced for statement.
This loop is used to access each value successively in a collection of values (like array).

Syntax:
for(datatype Variablename : Array)
{

------- //Block of Statements


}

20
Example Program

class Foreach
{
public static void main(String args[])
{
int arr[]={10,20,30,40,50};
for(int i : arr)
{
[Link]("i= "+i);
}
}
}

Branching Mechanism
The java programming language supports jump statements that used to transfer execution control
from one line to another line.
Two types of branching statements are available in Java—break and continue.

break Statement
The break statement in java is used to terminate a switch or looping statement. That means the
break statement is used to come out of a switch statement and a looping statement like while, do-
while, for, and for-each.
Syntax: break;

Example Program 1:

class Break
{
public static void main(String args[])
{
int i;
for(i=1;i<=10;i++)
{
if(i==5)
{
break;
}
[Link]("i = "+i);
}
}
}

21
[Link] continue Statement
The continue statement is used in loop control structure when you need to jump to the next
iteration of the loop immediately.
Syntax : Continue;
Example Program 1:
class ContinueExample
{
public static void main(String[] args)
{
for(int i=1;i<=10;i++)
{
if(i==5)
{
continue;
}
[Link](i);
}
}
}

2. OPERATORS :
 An operator performs an action on one or more operands.
 An operator that performs an action on one operand is called a unary operator (+, –, ++, – –).
 An operator that performs an action on two operands is called a binary operator (+, –, / , * ,
and more).
 An operator that performs an action on three operands is called a ternary operator (? :).
 Java provides all the three operators.
2.1 Binary Operators
Java provides arithmetic, assignment, relational, shift, conditional, bitwise, and member access
operators.

2.1.1 Arithmetic Operators


In java, arithmetic operators are used to performing basic mathematical operations like addition,
subtraction, multiplication, division, modulus, increment, decrement, etc.
Operator Meaning Example
+ Addition 10 + 5 = 15
- Subtraction 10 - 5 = 5
* Multiplication 10 * 5 = 50
/ Division 10 / 5 = 2
% Modulus - Remainder of the Division 5%2=1

22
class ArithmeticDemo
{
public static void main(String args[])
{
int a=25,b=10;
[Link]("Addition is "+
(a+b));
[Link]("Subtrction is "+(a-
b)); [Link]("Multiplication is
"+(a*b)); [Link]("Division is
"+(a/b)); [Link]("Remainder is
"+(a%b));
}
}

2.1.2 Relational Operators


The relational operators are the symbols that are used to compare two values. That means the
relational operators are used to check the relationship between two values. Every relational
operator has two possible results either TRUE or FALSE.

Operator Meaning Example


Returns TRUE if the first value is smaller than second value otherwise 10 < 5 is
<
returns FALSE FALSE
Returns TRUE if the first value is larger than second value 10 > 5 is
>
otherwise returns FALSE TRUE
Returns TRUE if the first value is smaller than or equal to second value 10 <= 5 is
<=
otherwise returns FALSE FALSE
Returns TRUE if the first value is larger than or equal to second value 10 >= 5 is
>=
otherwise returns FALSE TRUE
10 == 5 is
== Returns TRUE if both values are equal otherwise returns FALSE
FALSE
23
10 != 5 is
!= Returns TRUE if both values are not equal otherwise returns FALSE
TRUE

24
class RelationalDemo
{
public static void main(String args[])
{
int a=10,b=20;
[Link]("Equality Operator: a==b " +(a==b));
[Link]("Not Equality Operator: a!=b " +(a==b));
[Link]("Less Than Operator: a < b " +(a<b));
[Link]("Greater Than Operator: a > b " +(a>b));
[Link]("Less Than or equal to Operator: a <= b " +
(a<=b)); [Link]("Greater Than or equal to
Operator: a >= b "
+(a>=b));
}
}

2.1.3 Boolean Logical Operators


The logical operators are the symbols that are used to combine multiple conditions into one
condition. The following table provides information about logical operators.

Operator Meaning Example


Logical AND - Returns TRUE if all conditions are TRUE otherwise returns false & true
&
FALSE => false
Logical OR - Returns FALSE if all conditions are FALSE otherwise returns false | true
|
TRUE => true
Logical XOR - Returns FALSE if all conditions are same otherwise returns true ^ true
^
TRUE => false
Logical NOT - Returns TRUE if condition is FLASE and returns FALSE if it is !false =>
!
TRUE true
short-circuit AND - Similar to Logical AND (&), but once a decision is false & true
&&
finalized it does not evaluate remaining. => false
short-circuit OR - Similar to Logical OR (|), but once a decision is finalized false | true
||
it does not evaluate remaining. => true

25
class LogicalDemo
{
public static void main(String args[])
{
boolean a=true,b=false;
[Link]("Logical OR: "+ (a|
b)); [Link]("Logical XOR:
"+ (a^b)); [Link]("Logical
AND: "+ (a&b));
[Link]("Logical NOT: "+ (!
a));
}
}

2.1.4 Bitwise Operators


The bitwise operators are used to perform bit-level operations in the java programming language.
When we use the bitwise operators, the operations are performed based on binary values.
The following table describes all the bitwise operators in the java programming language.
Let us consider two variables A and B as A = 25 (11001) and B = 20 (10100).
Operator Meaning Example

⇒ 16
A&B
& The result of Bitwise AND is 1 if all the bits are 1 otherwise it is 0
(10000)

⇒ 29
A|B
| The result of Bitwise OR is 0 if all the bits are 0 otherwise it is 1
(11101)

⇒ 13
A^B
^ The result of Bitwise XOR is 0 if all the bits are same otherwise it is 1
(01101)

⇒ 6 (00110)
The result of Bitwise once complement is negation of the bit ~A
~
(Flipping)

26
⇒ 100
A << 2
Shift the bits left by b positions. Zero bits are added from the LSB
<<
side. Bits are discarded from the MSB side.
(1100100)

⇒ 6 (00110)
Shift the bits right by b positions. Sign bits are copied from the MSB A >> 2
>>
side. Bits discarded from the LSB side.

27
class BitwiseDemo
{
public static void main(String args[])
{
int a=25,b=20;
[Link]("Bitwise AND : "+
(a&b)); [Link]("Bitwise OR:
"+(a|b)); [Link]("Bitwise
XOR: "+(a^b));
[Link]("Bitwise NOT: "+
(~a)); [Link]("a<<2: "+
(a<<2)); [Link]("a>>2: "+
(a>>2));
}
}

2.1.5 Unary Operators

Unary operators, as the name suggest, are applied to only one operand. They are ++, - -, !, and ~.

Increment and decrement operators can be applied to all integers and floating-point types. They can
be used either in prefix (– –x, ++x) or postfix (x– –, x++) mode.
Prefix Increment / Decrement Operation
int x = 2;
int y = ++x; // x = 3, y = 3
int z = --x; // x = 1, z = 1
Postfix Increment / Decrement Operation
int x = 2;
int y = x++; // x == 3, y == 2
int z = x--; // x = 1, z = 2
2.1.6 Ternary Operators
Ternary operators are applied to three operands. This conditional operator (? :) decides, on the
basis of the first expression, which of the two expressions to be evaluated.

operand1 ? operand2 : operand3


operand1 must be of boolean type or an expression producing a boolean result. If operand1
28
is true, then operand2 is returned. If operand1 is false, then operand3 is returned.

29
class ConditionalOp
{
public static void main(String args[])
{
int a=10, b=20, c;
c=(a>b)?a:b;
[Link](c);
}
}

Part-II Notes(Unit-1)
Class
A class is a blueprint or prototype that defines the variables and methods common to all objects of a
certain kind. Class can be thought of as a user defined data type and an object as a variable of that
data type, which can contain data and methods.
Class declaration in JAVA
 A class is declared using class keyword followed by the name of the class.
Syntax of declaration of class
class classname
{
//Variables declaration
//Methods declaration
}
Example
class Myfirstprogram
{
public static void main (String args[])
{
[Link](“this is my first JAVA program!");
}}
Declaring classes in Java
The class declaration can specify more about the class like we can:
 Declare superclass of a class

 list the interfaces implemented by the class


 declare whether the class is public, abstract or final
30
class declaration syntax as:
[modifiers] class ClassName[extends SuperClassName] [ implements InterfaceNames]
{
....………
................
}
 The items between [and ] are optional. A class declaration defines the following aspects of the
class:
 modifiers declare whether the class is public, protected, default, abstract, or final
 ClassName sets the name of the class you are declaring
 SuperClassName is the name of ClassName's superclass
 InterfaceNames is a comma-delimited list of the interfaces implemented by ClassName

Parts of a class
The class contains TWO different sections:
 variable declarations and method declaration.

 The variables of a class describe its state


 and methods describe its behavior.

classDeclaration
{
memberVariableDeclarations
methodDeclarations
}
Java supports 3 types of variables
 Local variables – local variables are defined inside the methods

 Instance variables – instance variables are declared inside a class and outside the
methods.
 Class variables – class variables are declared with the static keyword inside the class
& outside the method

Object
An object is an instance of a class. The real-world objects have state and behavior.
For example, Bikes have state (gear, accelerator, two wheels, number of gears, brakes) and
behavior (braking, accelerating, slowing down and changing gears).

Creating objects
SYNTAX:
Classname objectname=new classname();
 Java object created with a statement like this one:
31
Demo obj1 = new Demo( );
 This statement creates a new object.
 This single statement declares, instantiates, and initializes the object.

Declaring an object
 object declarations is same as variable declarations for e.g.
Demo obj1;
 Generally the declaration is as follows:

type name;
Where type is the type of the object (i.e. class name) and name is the name of the reference variable
used to refer the object

Initializing an object
 By initializing an object, instance variables are assigned some values. This task is
accomplished using a constructor. This object creation can be used in programming code in
two ways:
Demo obj1 = new Demo( );

 Here all the three operations, object declaration, object instantiation and object initialization
are done by one statement only.
Student s; // s is a reference variable
s= new Student(); // allocate an object to reference variable s
The above two steps can be combined and rewritten in a single statement as;
Student s=new Student();
Now we can access the properties and methods of a class by using object with dot operator as
[Link]();
[Link]();
[Link]()
U can take either this example or from running notes

Above process actually takes place in following way


class Student
{
int roll_no;
string name;
void display()
{
[Link](“student rollno is:”, +roll_no);
[Link](“student name is:”, +name);
}
}
class Mstudent
32
{
public static void main(String args[])
{
Student s=new Student();
[Link]();
}
}

Instance Variable
 A class can have many instances, each instance having its own set of variables. E.g.
class Student
{
int roll_no; // Instance variable
string name;
void display()
{
[Link](“student rollno is:”, +roll_no);
[Link](“student name is:”, +name);
}
}
class Mstudent
{
public static void main(String args[])
{
Student s=new Student();
[Link]();
}
}
Object Class
1 Object is an instance of a class. Class is a blueprint or template from
which objects are created.
2 Object is a real world entity such as Class is a group of similar objects.
pen, laptop, mobile, bed, keyboard,
mouse, chair etc.
3 Object is a physical entity. Class is a logical entity.
4 Object is created through new Class is declared using class
keyword mainly e.g. keyword e.g.
Student s1=new Student(); class Student
{
}
5 Object is created many times as per Class is declared once.
requirement.
6 Object allocates memory when it is Class doesn't allocated memory when
created. it is created.
7 There are many ways to create There is only one way to define class in
object in java such as new keyword, java using class keyword.
newInstance() method, factory method
and deserialization.

33
Methods
Methods are similar to a function in any other programming languages. None of the methods can be
declared outside the class.
Syntax: return_type method_name (argument list)
{
//statements;
}
 Return Type: Can be either void or if a value is returned, it can be either a primitive type or a
class.
 Method Name: The method name must be a valid Java identifier.
 Parameter List: Each parameter in parameter list is separated by a comma.
 Curly Braces: The method body is contained in a set of curly braces (opening ‘{‘ and closing
‘}’).

Method example
class Rectangle
{
int l,b;
void setData(int x, int y) // set length and breadth
{
l=x;
b=y;
}
float calculateArea() // calculateArea method
{
float area =l*b;
return (area);
}
}

public static void main(String args[])


{
Rectangle obj=new Rectangle();
[Link](4.3, 4);
float area= [Link]();
[Link]("Area of rectangle:"+ area);
}}

34
Method invocation
 Methods cannot run on their own, they need to be invoked by the objects they are a part of.

 When an object calls a method, it can pass on certain values to the methods (if methods accept them)
 The methods can also return values from themselves if they wish to.
 Data that are passed to a method are known as arguments or parameters.
 You must also know about different types of parameters:
 Formal Parameters: the identifier used in a method to stand for the value that is passed into the method
by a caller
E.g. void setData(int x,int y)
{
l=x;
b=y;
}
 Actual Parameters: The actual value that is passed into the method by a caller
 E.g. [Link](4.3f, 4)
 The number and type of the actual and formal parameters should be same for a method.

Method overloading
Method overloading is a concept supported by JAVA. Method overloading is defined as two methods can
have the same name but different signature i.e. different number or type of parameters. Method overloading is
used when objects are required to perform similar task but by using different input parameter.
When a method in an object is called, java matches up the method name first and then the number and
types of parameters decide which one of the definitions to execute. Overloaded method can be created by
providing several different method definitions in the class, all with the same name but different parameters
list.
class Overload
{
void test()
{
[Link](“No parameters”);
}
void test(int x)
{
[Link](“x:”,+x);
}
void test(int x, int y)
{
[Link](“x and y:”,+x,+y);
}}
class overloading
{
public static void main(String args[])
35
{
Overload obj= new Overload();
double result();
[Link]();
[Link](100);
[Link](100,200);
}}
Method overloading can be done in three ways by changing:
1. The number of parameters in two methods.
2. The data types of the parameters of methods.
3. The Order of the parameters of methods.

import [Link].*;

class Overloadexample

// adding two integer values.

public int add(int a, int b) // number of parameters in method

int sum = a+b;

return sum;

public double add(double a, double b)// data types of the parameters of methods.

double sum = a+b;

return sum;

public void Identity1(String name, int id) //Order of the parameters of methods.

[Link]("String name :"+ name +" "+"Id :"+ id);

public void Identity2(int id, String name){

36
[Link]("String name :"+ name +" "+"Id :"+ id);

class Moverload{

public static void main (String[] args) {

Overloadexample obj = new Overloadexample();

int sum1 = [Link](1,2);

[Link]("sum of the two integer value :" + sum1);

double sum2 = [Link](1.3f,2.3f);

[Link]("sum of the three integer value :" + sum2);

obj.Identity1("abc", 1);

obj.Identity2(1, "abc");

Constructors
Java has a mechanism, for automatically initializing the values for an object, as soon as the
object is created. This mechanism is known as constructor. A constructor is similar to the
method, which is used to initialize the object.
Constructors have the same name as the class. Every time an object is created using the new ()
keyword, at least one constructor is called.
Constructors have no return type, not even void, as the implicit return type of a class constructor
is the class type itself. At the time of calling constructor, memory for the object is allocated in
the memory.
There are two rules defined for the constructor.
1. Constructor name must be the same as its class name
2. A Constructor doesn’t have any return type
3. A Java constructor cannot be abstract, static, final
Types of Java constructors
There are two types of constructors in Java:
1. Default constructor (no-argument constructor)
2. Parameterized constructor
Default Constructor:
A constructor is called Default Constructor when it does not have any parameter.
The below example defines an explicit default constructor that does not accept any argument but initializes
the instance variables to the specified values.
class Room
{
37
int length, breadth, height, volume;
Room( )
{
length = 14;
breadth = 12;
height = 10;
}
int volComp( )
{
volume = length * breadth * height;
return volume;
}
public static void main (String args[ ])

{
Room r1 = new Room();
Room r2 = new Room();
[Link](&quot;The volume of the room is” +[Link]( ));
[Link](&quot;The volume of the room is” +[Link]( ));
}
}
If there is no constructor in a class, compiler automatically creates a default constructor.
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. However,
we can provide the same values also.
class Room
{
int length, breadth, height, volume;
Room(int l, int b, int h )
{
length = l;
breadth =b;
height = h;
}
int volComp( )
{
volume = length * breadth * height;
return volume;
}
public static void main (String args[ ])
{
Room r1 = new Room(10,20,30);
Room r2 = new Room(2,4,5);
[Link](“The volume of the room is “ +[Link]( ));
[Link](“The volume of the room is “+[Link]( ));
}

38
}
In the above program to compute volume each time different values are initialized for different
objects.

Constructor overloading
Constructors can also be overloaded. Constructors are declared just as we declare methods,
except that constructors don’t have any return type. Constructors for a class have the same name as the class
but they can have different signature i.e. different types of arguments or different number of arguments. Such
constructors can be termed as overloaded constructors.

class Rectangle
{
int l, b;

Rectangle() // constructor without parameter


{
l = 10;
b = 20;
}
Rectangle(int x) // constructor with one parameter
{
l =b = x;
}
Rectangle(int x, int y) // constructor with two parameters
{
l = x;
b = y;
}
int area()
{
return l*b;
}
}
class ConstOverloading
{
public static void main(String args[])
{
Rectangle rect1=new Rectangle();
[Link](“The area of a rectangle using first constructor is:”+[Link]());
Rectangle rect2=new Rectangle(4);
[Link](“The area of a rectangle using second constructor is:”+[Link]();
Rectangle rect3=new Rectangle(10,20);
[Link](“The area of a rectangle using third constructor is:”+[Link]());
}
}

39
Instance Variable and Local variable
 A class can have many instances, each instance having its own set of variables.
 A class can have variables which are declared inside a method called local variables, and are
accessible only inside the method.
class Student
{
int roll_no=1; // Instance variable
string name=BCA;
void display()
{
int marks=99;
[Link](“student rollno is:”, +roll_no);
[Link](“student name is:”, +name);
[Link](“student marks is:”, +marks);
}
}
class Mstudent
{
public static void main(String args[])
{
Student s=new Student();
[Link]();
}
}

Static variables:
Java does not allow global variables. To achieve this we make instance variable in the class
static.. The static keyword in Java is used for memory management mainly. We can apply static keyword
with variables, methods, blocks and nested classes. To make an instance variable static we precede the
declaration with static.

static int x=10;

static variables are called as class variables. The static variable gets memory only once in the class area at
the time of class loading.
Can Write programs from running notes

Static methods
The members that are declared as static members. Like static variables static methods can be
called without using the objects. They are also available for use by other classes.
class Math1
{
Static float mul(float x, float y)
{
return x*y;
40
}
static float divide(float x, float y)
{
return x/y;
}
}
class Sample
{
public static void main(String args[])
{
float a=[Link](3.5,2.5);
float b=[Link](a,3.0);
[Link](“b is” +b);
}
}
Static methods are called using class names. Static methods have several restrictions such as
1. They can only call other static methods.
2. They can only access static data
3. They cannot refer to this or Super keyword in anyway

Final keyword
The keyword final is used to restrict the user. We can use final with
1. Variables
2. Methods and
3. Classes
1. If we use final with variables, we cannot change the value of final
variable, it becomes constant.
– E.g. final int MAX=100;

class A
{
final int MAX=100;//final variable
void run(){
MAX=400;
}
public static void main(String args[])
{

A obj=new A();
[Link]();
}
}//end of class
2. If we make a method as final we cannot do method overriding.
Syntax:
final void show (final int x)
{

41
// statements
}
Example:
class A
{
final void show() // final method
{
[Link](“final method”);
}
class B extends A
{
void show()
{
[Link](“override method”);
}}
classMclass
{
public static void main(String args[])
{
B obj=new B();
[Link]();
}
}//end of class

3. If we make any class final we cannot extend that class i.e it disallow
inheritance
final class Demo
{
//statements

}
final class A
{
}
Example:
class B extends A
{
void run()
{
[Link](“subclass method&quot;);
}
public static void main(String args[])
{
B b=new B();
} }
Access Protection

42
Access protection defines how much an element (class, method, variable) is exposed to other
classes and packages.
There are four types of access specifiers
Public Applied to variables, constructors, methods and classes
Protecte Applied to variables, constructor, methods and inner classes (not top level
d classes)
Default Applied to variables, constructors, methods and classes
Private Can be applied to variables, methods and inner classes (not top level classes)

 Public means accessibility for all


 Private means accessibility from within the class only
 Default (blank) access specifiers are accessible only from within the package
 Protected means accessibility outside the packages but only to subclasses

Can write programs from running notes

Object class Read from Running Notes

43

You might also like