Unit 1 OOP Java
Unit 1 OOP Java
Introduction to Java
Java is a general-purpose, object-oriented, secure, and robust programming language.
Developed by James Gosling at Sun Microsystems in 1991; originally named Oak, renamed to Java in
1995 due to legal reasons.
Initially designed for consumer electronic devices like TVs and VCRs.
Java overcomes portability and reliability issues found in C and C++.
Java programs run in different execution environments because it is strongly typed and uses bytecode
for machine-independent execution.
Compile time: source code → platform-independent bytecode.
Runtime: loading/linking classes, optional machine code generation, and dynamic optimization.
Its key feature is platform independence—Java programs can run on any system with the Java Virtual
Machine (JVM).
Java Features
1. Compiled and Interpreted: Java uses both a compiler (creates bytecode) and an interpreter/JVM
(executes bytecode).
2. Platform Independent: Bytecode is not machine-specific so any system with a JVM can run the same
bytecode. It follows WORA(Write Once, Run Anywhere.)
3. Portable: Java programs run on any system and has high high portability due to JVM.
4. Object-Oriented: Everything is based on objects and classes. So it can use OOP concepts like
encapsulation, inheritance, and polymorphism.
5. Robust and Secure: Provides strong type checking, exception handling, Garbage collection, No
pointers. JVM verifies bytecode for safety and security.
6. Distributed: Allows programs to access remote objects and useful for collaborative and network-based
applications.
7. Simple : Easier than C/C++ and reducing programmer effort.
8. Multithreaded and Interactive: Supports multithreading, Provides built-in support for thread handling
and synchronization.
9. High Performance: JIT (Just-In-Time) compilation improves performance, Multithreading increases
overall program efficiency.
10. Dynamic and Extensible: Java can load new classes and methods at runtime. Easily adaptable and
expandable.
Java Applications
1. Mobile Applications
2. Desktop GUI Applications
3. Web-based Applications
4. Enterprise Applications
5. Scientific Applications
JE (Java Environment)
JE includes large no. of development tools and hundred of classes and methods.
Tools are part of JDK (java development toolkit) and classes and methods are part of JSL (API) .
JE = JSL + JDK
Full Form:
JDK : Java Development Toolkit
JSL : Java Standard Library
API : Application Programming Interface
No Tools Description
1 appletviewer It enables user to run java applets.
2 javac javac translates java source code to byte code files that the interpreter
(java compiler) can understand.
3 java It runs applets and application by reading and interpreting byte codes.
(java interpreter)
4 javap It enables users to convert byte code files into a program description.
(java disassembler)
5 javah It Produces header files for use with native methods.
(for C header files)
6 javadoc It creates HTML format documentation from java source code files.
(for creating HTML
Documents)
● Byte Code
Java program may contain many classes of which only one class defines a main method.
Class contain data members and methods that operate on data members of class.
Method may contain data type declaration and executable [Link] program define classes and put
them together.
Documentation section:
This section comprises a set of comment lines giving the name of the program, author and other
details, which the programme would like to refer to at a large stage.
Comments must explain why and what of classes and how to algorithms.
Java supports three types of comment line:
Package statement:
The statement declares a package name and informs the compiler that the classes defined here belong to this
package.
package student ; //student is package
package statement is optional.
Import statements:
After package statement (but before class definitions) be a number of import statements. This is similar to the
#include statement in C.
import [Link];
This statement instructs the interpreter to load the test class contained in the package Student.
Using import statement ,we can access to classes that are part of the other named packages.
Interface statement:
Interface is like a class but includes a group of method declarations. This is also an optional section.
It is used only when we want to implement the multiple inheritance feature in the program
Class definitions:
A java program may contain multiple class definitions. Classes are the primary and essential elements of a
Java program. The number of classes used depends on the complexity of the problem.
Main method class:
Every java stand alone program requires a main method as its starting point, this class is essential part of a
java program.
Simple java program may contain only this part.
The main method creates objects of various classes and creates communications between them.
On reaching the end of main ,the program terminates and control passes back to th e operating system.
Machine neutral
The compiler converts the source code files into byte code files. These codes are machine independent and
therefore can be run on any machine. That is, a program compiled on an IBM machine will run on a Linux
machine.
Java interpreter reads the byte code files and translates them into machine code for the specific machine on
which the java program is running.
class Test
{
public static void main(String args[ ])
{
[Link]( “welcome to Java”);
}
}
1) First line : class Test
declares a class which is an object oriented construct.
java is true object oriented language and therefore everything must be placed inside a class.
class is keyword and it declares that a new class definition follows.
Test java identifier(name) specifies name of the class to be defined.
2) Second line : Opening brace : {
3) Third Line : public static void main (String args[ ])
Every java program must include main( ) method.
It is the starting point for interpreter to begin the execution of program.
A java application can have any number of classes but only one of them class must include main method to
initiate the execution.(java applets will not use the main method at all).
4) Output line:
[Link] (“Hello”);
Note: java program must name same as in class which includes main( ) method otherwise interpreter cannot
run that class.
Example 1: write a java program takes 2 variable by user input using command line and find sum.
class CmdDemo
{
public static void main ( String args [ ] )
{
int a,b ,sum;
a= Integer .parseInt (args[0]);
b= Integer .parseInt (args[1]);
sum= a+b;
Example :2
class Cmd1
{
public static void main (String args[ ])
{
int count=0;
String str;
count=[Link]; //to find how many arguments are passed to command line
Read statement
We may also give values to variables interactively through the keyboard using readLine( ) method.
readline( ) is invoked using an object of the class DataInputStream.
readLine( ) reads the input from the keyboard as a string which is then converted to the corresponding
data type using the data wrapper classes.
We have used the keywords try and catch to handle any errors that might occur during the reading
process.
Example :
import java. io .DataInputStream;
class Reading
{
public static void main (String args [ ])
{
DataInputStream obj=new DataInputStream([Link]);
int i=0;
float f=0.0 F;
try
{
[Link] (“enter an integer no “);
i = [Link] ( obj. readLine( ) );
[Link] (“enter float no “);
f = [Link] ([Link] ( ) ).floatValue( );
}
catch(Exception e)
{
[Link] ( “enter proper value” );
}
[Link]( “int no i= “+ i );
[Link]( “float no f= “ +f);
}
}
Output:
E :\ java program\ javac [Link]
E :\ java program\ java Reading
enter an integer no
56
enter float no
23.455
int no i= 56
float no f=23.455f
● Primitive types (byte, short, int, long, float, double, char, boolean).
• Floating point no. are treated as double precision , so to force them to be in single
precision mode ,we must append f or F.
Ex: 1.23f , 7.6512F
• NaN: Not a Number (special value supported by floating point data type)
It is used to represent result of operation such as dividing by zero ,where actual number is
not produced.
Character type
• char is used ,Size : 2 byte
• It holds single character only.
Boolean type
• It is used to test a particular condition during execution of program.
• It has two values : true or false
• boolean keyword is used
• Size: 1 bit ( 0 or 1).All comparison operators return boolean type variable. So, there
are 8 basic(primitive ) data type in java.
PREPARED BY: VPMP POLYTECHNIC, GANDHINAGAR 10
Object Oriented Programming – Java DI04000021
1) reserved keywords
2) identifiers
3) literals
4) operators
5) separators
2) Identifiers
• Identifiers are programmer designed tokens.
• It is used for naming classes ,methods , variables , objects , label , package and interface in
program.
Example:
▫ average , sum ,dayTemprature , totalMarks
3) Literals
• Sequence of characters (digits , letters ,and other character) that represent constant
values to be stored in variables.
• Five types:
PREPARED BY: VPMP POLYTECHNIC, GANDHINAGAR 12
Object Oriented Programming – Java DI04000021
▫ Integer literals
▫ Floating_point literals
▫ Character literals
▫ String literals
▫ Boolean literals
4) Operators
• All operator is a symbol that takes one or more arguments and operates on them to produce a
result.
5) Separators
• They are symbols used to indicate where groups of code are divided and arranged.
Sr. No. Name
1 Parentheses ( )
2 Braces { }
3 Brackets [ ]
4 Semicolon ;
5 Comma ,
6 Period .
2.2 Constant
• Constant in java refers to fixed values do not change during execution of program.
1) Integer Constant
2) Real constant
3) Single constant
4) String constant
1) Integer constant:
Integers:
a. Decimal : 0 to 9 [ ex. 123, 012 , 16789 ]
b. Octal : [ ex. 037 , o ,0435 ]
c. Hexadecimal : [ 0x2 , 0x9F , 0x ,oxbcd ]
2) Real constant
• Floating point / Real point constants Ex.
0.083 , -0.75 , 215. , .95 , -.71
syntax : mantissa e Exponent
• Ex.
▫ .65e4 , 12e-4 , 1.5 e+5 , 3.18E3
• Floating point contain 4 parts:
▫ A whole number
▫ A decimal number
▫ A fractional part
▫ An exponent
Ex.
“hello java” , “1997” ,”?----” , “5+3” , “x”
Variable
• It is a data name used to store a data value.
• Variable may take different values at different times during execution of program.
Rules for declaration
1. Not start with digit
2. Upper case and lower case letters are distinct
3. Not should be a keyword
4. No white spaces
5. Variable name can be of any length
PREPARED BY: VPMP POLYTECHNIC, GANDHINAGAR 14
Object Oriented Programming – Java DI04000021
Declaration of variable
Syntax:
type variable1, variable2,……;
Ex: int count; float x , y ; double p1; byte b; char ch;
Giving values to variable
1. By using assignment statement Syntax : variable name=value;
Ex: i=0,x=0.0f;
int i=0; char ch=„X‟;
2. By using read statement: (readLine() method)
readLine() method reads input from keyboard as a string which is then converted to
corresponding data type using wrapper classes.
3. By passing parameter in command line as its argument
Variable classified as
1. instance variable
2. Class variable
3. Local variable
1) Instance variable:
• Declared inside class
• They are creating when object are instantiated and therefore they are associated with objects.
• It takes different values for different objects.
2) Class variable
• Declared inside class
• They are global to class and belongs to the entire set of object that class creates.
• Only one memory location is created for each class variable
3) Local variable
• Variable declared and used inside methods.
• They work only inside that specific method.
Type value
byte Zero:(byte) 0
short Zero:(short) 0
int Zero : 0
long Zero: 0L or 0l
double 0.0d
float 0.0f
char Null character or „\u0000‟
boolean false
Reference null
From To
byte short , char , int , long , float , double
float double
• It is possible to assign value of one type to a other type without casting, is known as
automatic type conversion.
• It is possible only if destination type has enough precision to store source type.
• Example:
byte b= 75;
int a = b;
Two operations :
1) Widening(promotion)
2) Narrowing
• Widening: process of assigning smaller type to larger type is widening or promotion.
Ex: byte b=5;
int a=b;
• Narrowing: process of assigning larger type to smaller type is known as narrowing.
● Brief overview of Operators (Arithmetic, Bitwise, Rational, Logical, Assignment, Conditional, Ternary,
Increment and Decrement).
An operator is some special characters (symbol) that tells the computer to perform certain
mathematical or logical manipulations.
Types of Operators
1) Arithmetic Operators
2) Relational operators
3) Logical Operators
4) Assignment Operators
5) Increment & Decrement Operators
PREPARED BY: VPMP POLYTECHNIC, GANDHINAGAR 17
Object Oriented Programming – Java DI04000021
6) Conditional Operators
7) Bitwise Operators
8) Special Operators
1) Arithmetic Operators
Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo Divisions
Operator Meaning
< Is less than
<= Is less than or equal to
> Is greater than
>= Is greater than or equal to
== Is equal to
!= Is not equal to
3) Logical Operators
C has three logical operators.
Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT
The Logical operator && and || are used when we want to test more than one
condition and make decisions.
Ex: a>b && x==10
In logical AND operator is used to perform more than one condition and take one
decision.
In logical OR operator is used to perform more than one condition and take one
decision.
Logical NOT operator is used to negate the answer of operation.
4) Assignment Operators
Used to assign the result of an expression to a variable.
C has a set of “shorthand” assignment operators.
a=a+1 a+=1
a=a-1 a-=1
a=a*(n+1) a*=n+1
a=a/(n+1) a/=n+1
a=a%b a%=b
One‟s complement
Symbol : ~
It complements bits 1to 0 and 0 to 1.
Right Shift with zero fill
The right shift operation causes all the bits in the operand op to be shifted to the right by n
positions.
The rightmost n bits in the original bit pattern will be lost and the leftmost n bit positions
that are vacated will be filled with 0s.
2) Special operators
1) instanceOf operator
2) dot operator
1. instanceOf operator :
It is an object reference operator.
It returns true if object on left side is instance of class given on right side.
It defines whether object belongs to particular class or not.
Ex:
person instanceOf Student
If object person belongs to class Student then returns true , else returns
false.
2. Dot ( . ) operator :
• It is used to access the instance variable and method of class objects.
• It is also access classes and sub package from package.
▫ [Link];
▫ [Link]();
Control Flow
● if-else (simple & nested & ladder).
The if Statement
Use the if statement to specify a block of Java code to be executed if a condition is true.
Syntax:
o if (condition) {
o // block of code to be executed if the condition is true
o }
Note that if is in lowercase letters. Uppercase letters (If or IF) will generate an error.
Example below, we test two values to find out if 20 is greater than 18. If the condition is true, print some
text:
if (20 > 18) {
[Link]("20 is greater than 18");
}
PREPARED BY: VPMP POLYTECHNIC, GANDHINAGAR 21
Object Oriented Programming – Java DI04000021
switch(expression)
{
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
This is how it works:
The switch expression is evaluated once.
The value of the expression is compared with the values of each case.
If there is a match, the associated block of code is executed.
The break and default keywords are optional, and will be described later in this chapter
The example below uses the weekday number to calculate the weekday name:
Example
int day = 4;
switch (day) {
case 1:
[Link]("Monday");
break;
case 2:
[Link]("Tuesday");
break;
case 3:
[Link]("Wednesday");
break;
case 4:
[Link]("Thursday");
break;
case 5:
[Link]("Friday");
break;
case 6:
[Link]("Saturday");
break;
case 7:
[Link]("Sunday");
break;
}
While Loop
Loops can execute a block of code as long as a specified condition is reached.
Loops are handy because they save time, reduce errors, and they make code more readable.
The while loop loops through a block of code as long as a specified condition is true:
Syntax
while (condition)
{
// code block to be executed
}
In the example below, the code in the loop will run, over and over again, as long as a variable (i) is less
than 5:
Example
int i = 0;
while (i < 5) {
[Link](i);
i++;
}
When you know exactly how many times you want to loop through a block of code, use the for loop
instead of a while loop:
Syntax
for (statement 1; statement 2; statement 3)
{
// code block to be executed
}
Statement 1 is executed (one time) before the execution of the code block.
Statement 2 defines the condition for executing the code block.
Statement 3 is executed (every time) after the code block has been executed.
The example below will print the numbers 0 to 4:
Example
for (int i = 0; i < 5; i++)
{
[Link](i);
}
Java Break
PREPARED BY: VPMP POLYTECHNIC, GANDHINAGAR 24
Object Oriented Programming – Java DI04000021
You have already seen the break statement used in an earlier chapter of this tutorial. It was used to
"jump out" of a switch statement.
The break statement can also be used to jump out of a loop.
This example stops the loop when i is equal to 4:
Example
for (int i = 0; i < 10; i++) {
if (i == 4)
{
break;
}
[Link](i);
}
2. Java Continue
The continue statement breaks one iteration (in the loop), if a specified condition occurs, and
continues
with the next iteration in the loop.
This example skips the value of 4:
Example
for (int i = 0; i < 10; i++)
{
if (i == 4)
{
continue;
}
[Link](i);
}
1.5 Arrays
● 1D arrays: declaration, initialization, traversal.
Java Arrays
Arrays are used to store multiple values in a single variable, instead of declaring separate variables for
each value.
Type of Array
1. One Dimensional Array
2. MultiDimensional Array
A one-dimensional array stores a list of values of the same data type in a single row.
Syntax
dataType[] arrayName;
or
dataType arrayName[];
Example Program
public class OneDArrayExample {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
// Accessing elements
[Link]("First element: " + numbers[0]);
// Using loop
for (int i = 0; i < [Link]; i++) {
[Link](numbers[i]);
}
}
}
Output
First element: 10
10
20
30
40
50
A two-dimensional array stores data in rows and columns (like a table or matrix).
Syntax
dataType[][] arrayName;
Declaration and Initialization
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
Example Program
public class TwoDArrayExample {
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Accessing elements
[Link]("Element at [1][2]: " + matrix[1][2]);
}
}
}
Output
Element at [1][2]: 6
1 23
456
789
Multidimensional Arrays
A multidimensional array is an array of arrays.
Multidimensional arrays are useful when you want to store data as a tabular form, like a table with rows
and columns.
To create a two-dimensional array, add each array within its own set of curly braces:
Example:
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
myNumbers is now an array with two arrays as its elements.
Access Elements
To access the elements of the myNumbers array, specify two indexes: one for the array, and one for the
element inside that array. This example accesses the third element (2) in the second array (1) of
myNumbers:
Example
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
[Link](myNumbers[1][2]);