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

Java Unit - 1 Notes

Uploaded by

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

Java Unit - 1 Notes

Uploaded by

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

Object Oriented with java programming

Syllabus
Unit – I

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 1
Object Oriented with java programming

Introduction to Java:
What is java?
 Java is a high-level, object-oriented programming language developed by Sun
Microsystems (now owned by Oracle Corporation).It was first released in 1995 and has
since become one of the most popular programming languages in the world, known
for its platform independence, versatility, and wide range of applications.

 Java was developed by a team of engineers led by James Gosling at Sun Microsystems
in the early 1990s. The project was initially called "Oak" but was later renamed "Java"
to avoid trademark issues. The official release of Java 1.0 occurred in 1995. Over the
years, Java has evolved with contributions from various individuals and organizations,
and it is now maintained by Oracle Corporation, which acquired Sun Microsystems in
2010. James Gosling is often credited as the "father of Java" for his key role in its
creation.

 3 billion mobile phones, 125 million TV sets, and 1 billion computers run Java
programming language.

Applications of JAVA(Java is used in many areas)

 Mobile applications (specially Android apps)


 Desktop applications
 Web applications
 Web servers and application servers
 Games
 Database connection
 And much, much more!

Key Features of java:

1. "Write once, run anywhere" philosophy, meaning that Java programs can be
compiled into byte code, which can then be executed on any platform that has a Java
Virtual Machine (JVM) installed.

2. Easy to Learn: Java is designed to be simple and easy to understand, making it


accessible for beginners to learn and use.

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 2
Object Oriented with java programming

3. Object-Oriented: Java organizes code into objects, which are like building blocks that
represent real-world things. This makes it easier to manage and reuse code, like Lego
pieces fitting together.

4. Platform independent: Developer/users can run java code in any platform.

5. Safe and Secure: Java has built-in features to protect your code and data from security
threats, like viruses or hackers. It's like having a security guard watching over your
program.

6. Robust and Reliable: Java is designed to be strong and dependable, with features that
help prevent crashes and errors. It's like having a sturdy shield that protects your
program from breaking.

7. Lots of Tools and Libraries : Java comes with a lot of helpful tools and pre-made code
(libraries) that you can use to build your programs faster. It's like having a toolbox full
of handy gadgets for your project.

8. Fast Performance : While Java may not be the fastest language, it's still pretty speedy,
especially with modern improvements. It's like a car that may not be a race car, but it
still gets you where you need to go efficiently.

9. Works with Multiple Tasks: Java can handle doing multiple things at once
(multithreading), which is useful for tasks like downloading files while playing music.
It's like being able to cook dinner while chatting with a friend on the phone.

10. Interpreted:

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 3
Object Oriented with java programming

Java uses a combination of compilation and interpretation.

1. Compilation: When you write Java code, you first compile it using the Java compiler
(javac). The compiler translates your human-readable Java code into an intermediate
form called bytecode. Bytecode is not machine code but rather a set of instructions that
can be executed by the Java Virtual Machine (JVM).

2. Interpretation: The JVM then interprets the bytecode and executes it on the target
platform. The JVM is responsible for translating bytecode instructions into machine
code that the underlying hardware can understand. This process happens dynamically at
runtime.

Object Oriented Programming (OOPs) Concept in Java


Object-Oriented:
Java organizes code into objects, which are like building blocks that represent real-world things. This
makes it easier to manage and reuse code.

1. Object :
It is a basic unit of Object Oriented Programming and represents the real life entities. A typical Java
program creates many objects, which as you know, interact by invoking methods. An object consists
of :
1. State : It is represented by attributes of an object. It also reflects the properties of an object.
2. Behavior : It is represented by methods of an object. It also reflects the response of an object
with other objects.
3. Identity : It gives a unique name to an object and enables one object to interact with other
objects.
Example of an object : dog

2. Class:
A class is a user defined blueprint or prototype from which objects are created. It represents the set
of properties or methods that are common to all objects of one type. In general, class declarations can
include these components, in order:
 Class is user defined data type, on which objects are created.

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 4
Object Oriented with java programming

 Class is “blueprint”
 Class is a “prototype”

3. Inheritance

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

The idea behind inheritance in Java is that you can create new classes that are built upon existing
classes. When you inherit from an existing class, you can reuse methods and fields of the parent
class. Moreover, you can add new methods and fields in your current class also.
 A class inherits a property from an another class is class sub class.
 A class provide properties and methods to another class is called base class.

4. Polymorphism (Many Forms)


Polymorphism in Java is a concept by which we can perform a single action in different ways.
Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly" means many
and "morphs" means forms. So polymorphism means many forms.

There are two types of polymorphism in Java:


 compile-time polymorphism and runtime polymorphism.

We can perform polymorphism in java by method overloading and method overriding.


If you overload a static method in Java, it is the example of compile time polymorphism.

5. Abstraction
Data Abstraction may also be defined as the process of identifying only the required
characteristics of an object ignoring the irrelevant details.

Ex: A car is viewed as a car rather than its individual components.

Consider a real-life example of a man driving a car. The man only knows that pressing the
accelerators will increase the speed of car or applying brakes will stop the car but he does not
know about how on pressing the accelerator the speed is actually increasing, he does not know
about the inner mechanism of the car or the implementation of accelerator, brakes etc in the car.
This is what abstraction is.

6. Encapsulations
Encapsulation is defined as the wrapping up of data under a single unit. It is the mechanism
that binds together code and the data it manipulates.

 As in encapsulation, the data in a class is hidden from other classes, so it is also known
as data-hiding.

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 5
Object Oriented with java programming

 Encapsulation can be achieved by: Declaring all the variables in the class as private and
writing public methods in the class to set and get the values of variables.

7. Message Passing
An object oriented program consists of a set of objects that communicates with each other. The
process of programming in an object oriented language, therefore, involves the following basic
steps.

1. Creating classes that define objects and their behavior.


2. Creating objects from class definitions.
3. Establishing communication among objects.

Basics of java programming:


Structure of Java Program

Java is an object-oriented programming, platform-independent, and secure programming language


that makes it popular. Using the Java programming language, we can develop a wide variety of
applications. So, before diving in depth, it is necessary to understand the basic structure of Java
program in detail.

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 6
Object Oriented with java programming

Documentation Section:
This typically refers to the comments and documentation within a Java file that describe the purpose,
usage, and behavior of the code. It includes Javadoc comments which are used to generate
documentation. comments are: single line comment (//) multiline comments(/* */)

Package Declaration:
Every Java class belongs to a package, which is declared at the beginning of the file. Packages help
organize classes into meaningful groups and prevent naming conflicts.

Import Statements:
Java allows classes to import other classes or entire packages to use their functionalities without fully
qualifying their names. Import statements are used to include these external classes or packages.

Interface Section:
In Java, an interface is a reference type that defines a set of abstract methods. It specifies a contract
that implementing classes must adhere to, without providing any implementation details.

Class Definition:
In Java, a class is a blueprint for creating objects. It encapsulates data (in the form of fields or variables)
and behavior (in the form of methods or functions) into a single unit.

Class Variables and Variables:


Variables in Java can be declared at various levels: as class variables (static variables), which belong
to the class itself, or as instance variables, which belong to individual objects. Variables can also be
declared within methods, known as local variables.

Main Method Class:


In Java applications, the main method serves as the entry point for execution. It is a special method
that is called when the program starts and is typically declared within a class.

Methods and Behaviors:


Methods in Java are blocks of code that perform specific tasks. They encapsulate behaviors and
functionalities that can be invoked by other parts of the program. Methods can have parameters and
may return values. Behaviors refer to the actions or tasks performed by these methods.

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 7
Object Oriented with java programming

JDK,JRE,JVM:
1. Java JDK (Java Development Kit):

The Java Development Kit is a software development kit used by Java developers to develop Java
applications. It contains tools such as the Java compiler (javac), the Java interpreter (java), and other
development tools like debugger and documentation generator. JDK also includes libraries and
frameworks necessary for Java development.

2. Java JRE (Java Runtime Environment):

The Java Runtime Environment is a software package that provides the necessary runtime
environment for executing Java applications. It includes the Java Virtual Machine (JVM), class
libraries, and other supporting files. JRE is required to run Java applications on a computer.

3. JVM (Java Virtual Machine):

The Java Virtual Machine is an abstract computing machine that enables Java bytecode to be executed
on different platforms. It interprets the compiled Java bytecode into machine code that can be
understood and executed by the underlying operating system. JVM provides platform independence
for Java programs, allowing them to run on any device or operating system that has a compatible
JVM implementation.

Data Types in Java

 Java programming language has a rich set of data types.


 Data types specify the different sizes and values that can be stored in the variable.
 Every variable declared before using it in program.

There are two types of data types in Java:

1. Primitive data types: The primitive data types include boolean, char, byte, short, int, long,
float and double.

2. Non-primitive data types: The non-primitive data types include Classes, Interfaces,
and Arrays and etc.

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 8
Object Oriented with java programming

Class

Java Primitive Data Types


 In Java language, primitive data types are the building blocks of data manipulation. These are
the most basic data types available in Java language.
 Java is a statically-typed programming language. It means, all variables must be declared before
its use. That is why we need to declare variable's type and name.

There are 8 types of primitive data types:

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 9
Object Oriented with java programming

Boolean Data Type


The Boolean data type is used to store only two possible values: true and false. This data type is used
for simple flags that track true/false conditions.

Example: Boolean one = false

Byte Data Type

 The byte data type is an example of primitive data type.


 Byte can store 1 byte size or 8 bit.
 Byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and
a maximum value of 127 (inclusive).
 The byte data type is used to save memory in large arrays where the memory savings is most
required. It saves space because a byte is 4 times smaller than an integer. It can also be used in
place of "int" data type.
 Example: byte a = 10, byte b = -20

Short Data Type

 The short data type can store 2 byte or 16 bit size in memory.
 Its value-range lies between -32,768 to 32,767
 Short data type is a 16-bit signed two's complement integer. It has a minimum value of -32,768
and a maximum value of 32,767 (inclusive).
 The short data type can also be used to save memory just like byte data type. A short data type
is 2 times smaller than an integer.
 Example:short s = 10000, short r = -5000

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 10
Object Oriented with java programming

Int Data Type

 The int data type can store 4 byte or 32-bit in memory.


 Its value-range lies between - 2,147,483,648 to 2,147,483,647.
 Int data type is a 32-bit signed two's complement integer. It has a minimum value of -2^31 and
a maximum value of 2^31-1.
 Example: int a = 100000, int b = -200000

Long Data Type

 The long data type can store 5 byte or 64-bit size in memory.
 Its value-range lies between -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.
 Long data type is a 64-bit signed two's complement integer. It has a minimum value of -2^63
and a maximum value of 2^63-1. To specify a long literal, you can append an "L" or "l" to the
end of the number
 Example:long a = 100000L, long b = -200000L

Float Data Type

 The float data type is a single-precision 32-bit IEEE 754 floating point.
 Its value range is unlimited.
 It is recommended to use a float (instead of double) if you need to save memory in large arrays
of floating point numbers.
 Example: float f1 = 234.5f

Double Data Type

 The double data type is a double-precision 64-bit IEEE 754 floating point.
 Its value range is unlimited. The double data type is generally used for decimal values just like
float.
 The double data type also should never be used for precise values, such as currency. Its default
value is 0.0d.
 Example: double d1 = 12.3

Char Data Type

 The char data type is a single 16-bit Unicode character. Its value-range lies between '\u0000'
(or 0) to '\uffff' (or 65,535 inclusive).The char data type is used to store characters.
 Example: char letterA = 'A'

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 11
Object Oriented with java programming

Example on data types:

public class PrimitiveTypesExample {


public static void main(String[] args)
{
// Declaring and initializing variables for all primitive types
byte byteVar = 127;
short shortVar = 32767;
int intVar = 2147483647;
long longVar = 9223372036854775807L; // Note: L suffix to specify long literal
float floatVar = 3.14f; // Note: f suffix to specify float literal
double doubleVar = 3.14159;
char charVar = 'A';
boolean booleanVar = true;
// Printing the values of each variable
System.out.println("byteVar: " + byteVar);
System.out.println("shortVar: " + shortVar);
System.out.println("intVar: " + intVar);
System.out.println("longVar: " + longVar);
System.out.println("floatVar: " + floatVar);
System.out.println("doubleVar: " + doubleVar);
System.out.println("charVar: " + charVar);
System.out.println("booleanVar: " + booleanVar);
}
}

OUTPUT:

byteVar: 127
shortVar: 32767
intVar: 2147483647
longVar: 9223372036854775807
floatVar: 3.14
doubleVar: 3.14159
charVar: A
booleanVar: true

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 12
Object Oriented with java programming

Java Variables
 A variable is a container which holds the value while the Java program is executed. A variable
is assigned with a data type.
 Variable is a name of memory location. There are three types of variables in java: local, instance
and static.

Variable
A variable is the name of a reserved area allocated in memory. In other words, it is a name of
the memory location. It is a combination of "vary + able" which means its value can be changed.

1. int data=50;//Here data is variable

Types of Variables

There are three types of variables in Java:

o local variable
o instance variable
o static variable

1) Local Variable

A variable declared inside the body of the method is called local variable. You can use this variable
only within that method and the other methods in the class aren't even aware that the variable exists.

Scope of Local Variable:


Scope of local variable are limited to method. Such a variable is accessible only within the method or
block in which it is declared.

A local variable cannot be defined with "static" keyword.

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 13
Object Oriented with java programming

public class Area


{
public static void main(String args[])
{
int length=10; //local variable
int breadth = 5; //local variable
int rectarea = length*breadth; //local variable
System.out.println(“Area of rectangle is :”+ rectarea);
}
}

OUTPUT:

Area of rectangle is : 50

2) Instance Variable

 A variable declared inside the class but outside the body of the method, is called an instance
variable. It is not declared as static.
 It is called an instance variable because its value is instance-specific and is not shared among
instances.

Example:
public class Area
{
int length=10; //instance variable
int breadth = 5; // instance variable
public static void main( String args[] )
{
int rectarea = length*breadth; //local variable
System.out.println(“Area of rectangle is :”+ rectarea);
}
}

OUTPUT:

Area of rectangle is : 50

3) Static variable

 A variable that is declared as static is called a static variable. It cannot be local. You can create
a single copy of the static variable and share it among all the instances of the class. Memory
allocation for static variables happens only once when the class is loaded in the memory.

 Advantages of static variable


 It makes your program memory efficient (i.e., it saves memory).

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 14
Object Oriented with java programming

Example:

//Java Program to demonstrate the use of static variable


class Student
{
int rollno; //instance variable
String name;
static String college ="Tungal";//static variable

//constructor
Student(int r, String n)
{
rollno = r;
name = n;
}

//method to display the values


void display ()
{
System.out.println(rollno+" "+name+" "+college);
}
}

public class static_variable


{
public static void main(String args[])
{
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");

s1.display();
s2.display();
}
}

OUTPUT:
111 Karan Tungal
222 Aryan Tungal

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 15
Object Oriented with java programming

Java Type casting


 Converting one data type to another data type is called type casting.

Java Variable Example: Widening


public class Simple
{
public static void main(String[] args)
{
int a=10;
float f=a;
System.out.println(a);
System.out.println(f);
}
}
Output:

10
10.0
Java Variable Example: Narrowing (Typecasting)
public class Simple
{
public static void main(String[] args)
{
float f=10.5f;
//int a=f;//Compile time error
int a=(int)f;
System.out.println(f);
System.out.println(a);
}
}
Output:

10.5
10
Java Variable Example: Overflow
class Simple
{
public static void main(String[] args)
{
//Overflow
int a=130;
byte b=(byte)a;
System.out.println(a);
System.out.println(b);
}
}
Output:130
-126

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 16
Object Oriented with java programming

Java Operators:
 Operators are symbols that perform operations on variables and values. For example, + is an
operator used for addition, while * is also an operator used for multiplication.
 Operators in Java can be classified into 5 types:
1. Arithmetic Operators
2. Assignment Operators
3. Relational Operators
4. Logical Operators
5. Unary Operators
6. Bitwise Operators

1. Java Arithmetic Operators

 Arithmetic operators are used to perform arithmetic operations on variables and data. For
example,
a + b;
 Here, the + operator is used to add two variables a and b. Similarly, there are various other
arithmetic operators in Java.

Operator Operation

+ Addition

- Subtraction

* Multiplication

/ Division

% Modulo Operation (Remainder after division)

Example 1: Arithmetic Operators


class Main
{
public static void main(String[] args)
{

// declare variables
int a = 12, b = 5;

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 17
Object Oriented with java programming

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

// subtraction operator
System.out.println("a - b = " + (a - b));

// multiplication operator
System.out.println("a * b = " + (a * b));

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

// modulo operator
System.out.println("a % b = " + (a % b));
}
}
Output
a + b = 17
a-b=7
a * b = 60
a/b=2
a%b=2

2. Java Assignment Operators


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

int age;

age = 5;

Here, = is the assignment operator. It assigns the value on its right to the variable on its left. That is, 5 is
assigned to the variable age.

Let's see some more assignment operators available in Java.

Operator Example Equivalent to

= a = b; a = b;

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 18
Object Oriented with java programming

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

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

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

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

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

Example 2: Assignment Operators


class Main {
public static void main(String[] args) {

// create variables
int a = 4;
int var;

// assign value using =


var = a;
System.out.println("var using =: " + var);

// assign value using =+


var += a;
System.out.println("var using +=: " + var);

// assign value using =*


var *= a;
System.out.println("var using *=: " + var);
}
}
Output
var using =: 4
var using +=: 8
var using *=: 32

3. Java Relational Operators


Relational operators are used to check the relationship between two operands. For example,
// check if a is less than b
a < b;

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 19
Object Oriented with java programming

Here, < operator is the relational operator. It checks if a is less than b or not.
It returns either true or false.

Operator Description Example

== Is Equal To 3 == 5 returns false

!= Not Equal To 3 != 5 returns true

> Greater Than 3 > 5 returns false

< Less Than 3 < 5 returns true

Greater Than or Equal


>= 3 >= 5 returns false
To

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

Example 3: Relational Operators

class Main {
public static void main(String[] args) {

// create variables
int a = 7, b = 11;

// value of a and b
System.out.println("a is " + a + " and b is " + b);

// == operator
System.out.println(a == b); // false

// != operator
System.out.println(a != b); // true

// > operator
System.out.println(a > b); // false

// < operator
System.out.println(a < b); // true

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 20
Object Oriented with java programming

// >= operator
System.out.println(a >= b); // false

// <= operator
System.out.println(a <= b); // true
}
}

Note: Relational operators are used in decision making and loops.

4. Java Logical Operators


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

Operator Example Meaning

&& (Logical expression1 && true only if both expression1 and


AND) expression2 expression2 are true

true if either expression1 or


|| (Logical OR) expression1 || expression2
expression2 is true

true if expression is false and vice


! (Logical NOT) !expression
versa

Example 4: Logical Operators


class Main {
public static void main(String[] args) {

// && operator
System.out.println((5 > 3) && (8 > 5)); // true
System.out.println((5 > 3) && (8 < 5)); // false

// || operator
System.out.println((5 < 3) || (8 > 5)); // true
System.out.println((5 > 3) || (8 < 5)); // true
System.out.println((5 < 3) || (8 < 5)); // false

// ! operator
System.out.println(!(5 == 3)); // true
System.out.println(!(5 > 3)); // false

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 21
Object Oriented with java programming

}
}
Working of Program
(5 > 3) && (8 > 5) returns true because both (5 > 3) and (8 > 5) are true.
(5 > 3) && (8 < 5) returns false because the expression (8 < 5) is false.
(5 < 3) || (8 > 5) returns true because the expression (8 > 5) is true.
(5 > 3) || (8 < 5) returns true because the expression (5 > 3) is true.
(5 < 3) || (8 < 5) returns false because both (5 < 3) and (8 < 5) are false.
!(5 == 3) returns true because 5 == 3 is false.
!(5 > 3) returns false because 5 > 3 is true.

5. Java Unary Operators


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

Operator Meaning

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

- Unary minus: inverts the sign of an expression

++ Increment operator: increments value by 1

-- Decrement operator: decrements value by 1

! Logical complement operator: inverts the value of a boolean

Increment and Decrement Operators


Java also provides increment and decrement operators: ++ and -- respectively. ++ increases the value
of the operand by 1, while -- decrease it by 1. For example,
int num = 5;

// increase num by 1
++num;
Here, the value of num gets increased to 6 from its initial value of 5.

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 22
Object Oriented with java programming

Example 5: Increment and Decrement Operators


class Main {
public static void main(String[] args) {

// declare variables
int a = 12, b = 12;
int result1, result2;

// original value
System.out.println("Value of a: " + a);

// increment operator
result1 = ++a;
System.out.println("After increment: " + result1);

System.out.println("Value of b: " + b);

// decrement operator
result2 = --b;
System.out.println("After decrement: " + result2);
}
}

Output
Value of a: 12
After increment: 13

Value of b: 12
After decrement: 11

In the above program, we have used the ++ and -- operator as prefixes (++a, --b). We can also use
these operators as postfix (a++, b++).
There is a slight difference when these operators are used as prefix versus when they are used as a
postfix.

6. Java Bitwise Operators


Bitwise operators in Java are used to perform operations on individual bits. For example,
Bitwise complement Operation of 35

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 23
Object Oriented with java programming

35 = 00100011 (In Binary)

~ 00100011
________
11011100 = 220 (In decimal)

Here, ~ is a bitwise operator. It inverts the value of each bit (0 to 1 and 1 to 0).
The various bitwise operators present in Java are:

Operator Description

~ Bitwise Complement

<< Left Shift

>> Right Shift

>>> Unsigned Right Shift

& Bitwise AND

^ Bitwise exclusive OR

These operators are not generally used in Java. To learn more, visit Java Bitwise and Bit Shift
Operators.

7. Java Ternary Operator


The ternary operator (conditional operator) is shorthand for the if-then-else statement. For example,
variable = Expression? expression1: expression2

Here's how it works.


If the Expression is true, expression1 is assigned to the variable.
If the Expression is false, expression2 is assigned to the variable.
Let's see an example of a ternary operator.

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 24
Object Oriented with java programming

Example:
public class TernaryOperatorExample
{
public static void main(String[] args)
{
int number = 10;
String result;

// Using ternary operator to determine if the number is even or odd


result = (number % 2 == 0) ? "even" : "odd";

System.out.println("The number " + number + " is " + result + ".");


}
}

Output
even

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 25
Object Oriented with java programming

Control Statements / in java:

Java if, if...else Statement

In programming, it's often desirable to execute a certain section of code based upon whether the
specified condition is true or false (which is known only during the run time). For such cases, control
flow statements are used.
The Java if statement is used to test the condition. It checks boolean condition: true or false.
There are various types of if statement in java.
o if statement
o if-else statement
o if-else-if ladder
o nested if statement
o switch statement

Java if (if-then) Statement

The Java if statement tests the condition. It executes the if block if condition is true.
The syntax of if-then statement in Java is:

if (expression)
{
// statements
}

Here expression is a boolean expression (returns either true or false).


If the expression is evaluated to true, statement(s) inside the body of if (statements inside parenthesis)
are executed.
If the expression is evaluated to false, statement(s) inside the body of if are skipped from execution.

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 26
Object Oriented with java programming

Example 1: Java if Statement


1. class IfStatement
2. {
3. Public static void main(String[] args)
4. {
5. int number = 10;
6. if (number >0)
7. {
8. System.out.println("Number is positive.");
9. }
10. System.out.println("This statement is always executed.");
11. }
12. }// End of class

When you run the program, the output will be:

Number is positive.
This statement is always executed.

 When number is 10, the test expression number > 0 is evaluated to true. Hence, codes inside the
body of if statements are executed.

 Now, change the value of number to a negative integer. Let's say -5. The output in this case will
be: This statement is always executed.

 When number is -5, the test expression number > 0 is evaluated to false. Hence, Java compiler
skips the execution of body of if statement.

Java if...else (if-then-else) Statement


The Java if-else statement also tests the condition. It executes the if block if condition is true
otherwise else block is executed.
The syntax of if-then-else statement is:
if (expression)
{
// codes
}
else
{
// some other code
// Else code will executes.
}

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 27
Object Oriented with java programming

Example 2: Java if else Statement


1. class IfElse
2. {
3. Public static void main(String[] args)
4. {
5. int number = 10;
6. if (number >0)
7. {
8. System.out.println("Number is positive.");
9. }
10. else
11. {
12. System.out.println("Number is not positive.");
13. }
14. System.out.println("This statement is always executed.");
15. }
16. }

When you run the program, the output will be:

Number is positive.
This statement is always executed.

When number is 10, the test expression number > 0 is evaluated to true. In this case, codes inside the

body of if are executed, and codes inside the body of else statements are skipped from execution.
Now, change the value of number to a negative number. Let's say -5. The output in this case will be:

Number is not positive.


This statement is always executed.

When number is -5, the test expression number > 0 is evaluated to false. In this case, codes inside the
body of else are executed, and codes inside the body of if statements are skipped from execution.

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 28
Object Oriented with java programming

Java if..else..if Statement (if ..else.. ladder)


In Java, it's possible to execute one block of code among many. For that, you can use if..else...if ladder.
Syntax of if..else..if

if (expression1)
{
// codes
}
else if(expression2)
{
// codes
}
else if (expression3)
{
// codes
}
.
.
else
{
// codes
}

The if statements are executed from the top towards the bottom. As soon as the test expression is true,
codes inside the body of that if statement is executed. Then, the control of program jumps outside if-
else-if ladder.
If all test expressions are false, codes inside the body of else is executed.

Example 3: Java if..else..if Statement


1. class Ladder
2. {
3. Public static void main(String[] args)
4. {
5. int number = 0;
6. if (number >0)
7. {
8. System.out.println("Number is positive.");
9. }
10. elseif (number <0)
11. {

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 29
Object Oriented with java programming

12. System.out.println("Number is negative.");


13. }
14. else
15. {
16. System.out.println("Number is 0.");
17. }
18. }
19. }

When you run the program, the output will be:

Number is 0.

When number is 0, both test expression number > 0 and number < 0 is evaluated to false. Hence, the
statement inside the body of else is executed.
The above program checks whether number is positive, negative or 0.

Java Nested if..else Statement


The nested if statement represents the if block within another if block. Here, the inner if block condition
executes only when outer if block condition is true.
It's possible to have if..else statements inside a if..else statement in Java. It's called
nested if...else statement.
Here's a program to find largest of 3 numbers:
Sysntax:
if(condition)
{
//code to be executed
if(condition)
{
//code to be executed
}
}

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 30
Object Oriented with java programming

Example 4: Nested if...else Statement


1. Class Number
2. {
3. publicstaticvoid main(String[] args)
4. {
5. Double n1 = -1.0, n2 = 4.5, n3 = -5.3, largestNumber;
6. if (n1 >= n2)
7. {
8. if (n1 >= n3)
9. {
10. largestNumber = n1;
11. }
12. else
13. {
14. largestNumber = n3;
15. }
16. }
17. Else
18. {
19. if (n2 >= n3)
20. {
21. largestNumber = n2;
22. }
23. else
24. {
25. largestNumber = n3;
26. }
27. }
28. System.out.println("Largest number is " + largestNumber);
29. }
30. }

When you run the program, the output will be:

Largest number is 4.5

Note: In above programs, we have assigned value of variables ourselves to make this easier. However,
in real world applications, these values may come from user input data, log files, form submission etc.

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 31
Object Oriented with java programming

Java Selection/Switch Statement:

The switch statement allows us to execute a block of code among many alternatives.
Syntax:
switch (expression)
{
case value1:
// code
break;

case value2:
// code
break;
...
...

default:
// default statements
}

How does the switch-case statement work?


The expression is evaluated once and compared with the values of each case.
 If expression matches with value1, the code of case value1 are executed. Similarly, the code
of case value2 is executed if expression matches with value2
 If there is no match, the code of the default case is executed

// Java Program to check the size using the switch...case statement

class Main
{
public static void main(String args[ ])
{
int number = 44;
String size;

// switch statement to check size


switch (number)
{
case 29:
size = "Small";
break;

case 42:
size = "Medium";

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 32
Object Oriented with java programming

break;

// match the value of week


case 44:
size = "Large";
break;

case 48:
size = "Extra Large";
break;

default:
size = "Unknown";
break;

}
System.out.println("Size: " + size);
}
}
Output:

Size: Large

Java Looping:

In computer programming, loops are used to repeat a block of code.

For example, if you want to show a message 100 times, then rather than typing the same
code 100 times, you can use a loop.

In Java, there are three types of loops.

1. for loop
2. while loop
3. do...while loop

1.for loop:
Java for loop is used to run a block of code for a certain number of times. The syntax of for loop is:

for (initialization; condition; Increment/Decrement)


{
// body of the loop
}

Here,

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 33
Object Oriented with java programming

1. The initialization initializes and/or declares variables and executes only once.
2. The condition is evaluated. If the condition is true, the body of the for loop is executed.
3. The Increment/Decrement updates the value of initialization.
4. The condition is evaluated again. The process continues until the condition is false.

Example 1: Display a Text Five Times


// Program to print a text 5 times
class Main OUTPUT:
{
public static void main(String[] args) Java is fun
{ Java is fun
int n = 5; Java is fun
// for loop Java is fun
for (int i = 1; i <= n; i++) Java is fun
{
System.out.println("Java is fun");
}
}
}

Example 3: Display Sum of n Natural Numbers


// Program to find the sum of natural numbers from 1 to 10.

class SumOfNaturalNumber OUTPUT:


{
public static void main(String[] args) Sum = 50
{
int sum = 0;
int n = 10;

// for loop
for (int i = 1; i <= n; i++)
{
sum = sum + i
}
System.out.println("Sum = " + sum);
}
}

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 34
Object Oriented with java programming

2. Java while loop


Java while loop is used to run a specific code until a certain condition is true.

The syntax of the while loop is:

//Intialization
while (Condition)
{
// body of loop
//Increment /Decrement
}

Here,
1. A while loop evaluates the Condition inside the parenthesis ().
2. If the Condition evaluates to true, the code inside the while loop is executed.
3. The Condition is evaluated again.
4. This process continues until the Condition is false.
5. When the Condition evaluates to false, the loop stops.

Example 1: Display Numbers from 1 to 5

class PrintNumbers OUTPUT:


{ 1
public static void main(String[] args) 2
{ 3
// declare variables 4
int i = 1, n = 5; 5

// while loop from 1 to 5


while(i <= n)
{
System.out.println(i);
i++;
}
}
}

3. Java do...while loop


The do...while loop is similar to while loop. However, the body of do...while loop is executed once
before the test expression is checked. For example,

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 35
Object Oriented with java programming

do
{
// body of loop
//Increment/Decrement
} while(Condition);

Here,
1. The body of the loop is executed at first. Then the Condition is evaluated.
2. If the Condition evaluates to true, the body of the loop inside the do statement is executed
again.
3. The Condition is evaluated once again.
4. If the Condition evaluates to true, the body of the loop inside the do statement is executed
again.
5. This process continues until the Condition evaluates to false. Then the loop stops.

Example : Display Numbers from 1 to 5


class PrintNumbers OUTPUT:
{ 1
public static void main(String[] args) 2
{ 3
int i = 1, n = 5; 4
5
do
{
System.out.println(i);
i++;
} while(i <= n);
}
}

Nested Loop in Java


If a loop exists inside the body of another loop, it's called a nested loop. Here's an example of the
nested for loop.

// outer loop
for (int i = 1; i <= 5; ++i)
{
// codes
// inner loop
for(int j = 1; j <=2; ++j)
{
// codes
}
..
}

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 36
Object Oriented with java programming

Here, we are using a for loop inside another for loop.

Here is a program to create a half pyramid pattern using nested loops.

class Main OUTPUT:


{ 1
public static void main(String[] args) 12
{ 123
int rows = 5; 1234
// outer loop 12345
for (int i = 1; i <= rows; i++)
{

// inner loop to print the numbers


for (int j = 1; j <= i; j++)
{
System.out.print(j + " ");
}
System.out.println("");
}
}
}

Java for-each Loop

The for-each loop is used to traverse array or collection in Java. It is easier to use than simple for loop
because we don't need to increment value and use subscript notation.

It works on the basis of elements and not the index. It returns element one by one in the defined
variable.

Syntax:

for(data_type variable : array_name)


{
//code to be executed
}

Here,

Array_name - an array or a collection

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 37
Object Oriented with java programming

variable - each item of array/collection is assigned to this variable

data_type - the data type of the array/collection

Example 1: Print Array Elements

class PrintArray OUTPUT:


{ 3
public static void main(String[] args) 9
{ 5
// create an array -5
int[] numbers = {3, 9, 5, -5};

// for each loop


for (int number: numbers)
{
System.out.println(number);
}
}
}

Java Jumping Satements:


Jumping statements are control statements that transfer execution control from one point to another
point in the program. There are three Jump statements that are provided in the Java programming
language:

1. Break statement.
2. Continue statement.
3. Return Statement

Break statement
1. Using Break Statement to exit a loop:

In java, the break statement is used to terminate the execution of the nearest looping statement or
switch statement. The break statement is widely used with the switch
statement, for loop, while loop, do-while loop.

Syntax:

break;

When a break statement is found inside a loop, the loop is terminated, and the control reaches the
statement that follows the loop. here is an example:

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 38
Object Oriented with java programming

// Java program to illustrate the OUTPUT:


// break keyword in Java 1
import java.io.*; 2
3
class BreakExample 4
{ 5
public static void main(String[] args)
{
int n = 10;
for (int i = 0; i < n; i++)
{
if (i == 6)
break;
System.out.println(i);
}
}
}

Java continue:
While working with loops, sometimes you might want to skip some statements or terminate the loop.
In such cases, break and continue statements are used.

The continue statement skips the current iteration of a loop (for, while, do...while, etc).

After the continue statement, the program moves to the end of the loop. And, test expression is
evaluated (update statement is evaluated in case of the for loop).

Here's the syntax of the continue statement.

continue;

Example:

// Java program to illustrate the continue keyword in Java OUTPUT:


0
import java.io.*; 1
class ContinueExample 2
{ 3
public static void main(String[] args) 4
{ 5
for (int i = 0; i < 10; i++)
{ 7
if (i == 6) 8
{ 9
System.out.println();
continue;
}

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 39
Object Oriented with java programming

System.out.println(i);
}
}
}

Return Statement
The “return” keyword can help you transfer control from one method to the method that called it.
Since the control jumps from one part of the program to another, the return is also a jump statement.

“return” is a reserved keyword means we can’t use it as an identifier.

Syntax:

return value;

class ReturnExample OUTPUT:


{ Result: 15

public static int calculateSum(int num1, int num2)


{

System.out.println("Calculating the sum of " + num1 + " and " + num2);


int sum = num1 + num2;
System.out.println("The sum is: " + sum);

return sum;
}

public static void main(String[] args)


{

int result = calculateSum(5, 10);

System.out.println("Result: " + result);


}
}

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 40
Object Oriented with java programming

Java Array:
What is an Array in Java?
An array refers to a data structure that contains homogeneous elements. This means that all the
elements in the array are of the same data type. Let's take an example:

This is an array of seven elements. All the elements are integers and homogeneous. The box below the
array is called the index, which always starts from zero and goes up to n-1 elements.

In this case, as there are seven elements, the index is from 0 to 1.

Elements stored under a single name: All the elements are stored under one name. This name is used
any time we use an array.

Advantages:

 Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.
 Random access: We can get any data located at an index position.
 Java arrays enable you to access any element randomly with the help of indexes
 It is easy to store and manipulate large data sets

Disadvantages

 Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its size at
runtime. To solve this problem, collection framework is used in Java which grows
automatically.
 Java cannot store heterogeneous data. It can only store a single type of primitives

Step-by-Step Guide to Declare an Array:

# 1. Declaration:

First, you declare an array variable, specifying the type of the elements the array will hold.

Syntax:

data_type[ ] Array_Name; OR data_type Array_Name[ ];

Here:

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 41
Object Oriented with java programming

data_type - it can be primitive data types like int, char, double, byte, etc.

Array_Name - it is an identifier or array name.

# 2. Creation:

Next, you create the array, which means specifying its size (the number of elements it can hold).

myArray = new int[5]; // Creates an array that can hold 5 integers

Combined Declaration and Creation:

You can combine the declaration and creation into a single statement.

int[ ] myArray = new int[5]; // Declares and creates an array of 5 integers

Initializing an Array:

You can also initialize the array with values at the time of declaration.

int[ ] myArray = {7, 10, 23, 17, 5};

// Declares, creates, and initializes an array with specified values

Examples with Different Data Types:

# Integer Array:

int[ ] intArray = new int[10]; // An array of 10 integers

# String Array:

String[ ] stringArray = new String[3]; // An array of 3 strings

# Double Array:

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 42
Object Oriented with java programming

double[ ] doubleArray = new double[4]; // An array of 4 doubles

# Array Initialization with Values:

char[ ] charArray = {'a', 'b', 'c', 'd'}; // An array of 4 characters initialized with values

Types of Array in java


There are two types of array.

1. Single Dimensional Array


2. Multidimensional Array

1. Single Dimensional Array - (One- Dimensional Array)


A one-dimensional array in Java is a collection of elements, all of the same type, stored in a single
row. Each element in the array can be accessed by its index, which starts from 0. Let's break down the
concept with an example.

Steps to Create and Use a One-Dimensional Array in Java:

1. Declare the Array: Specify the type of elements it will store and the name of the array.

2. Instantiate the Array: Use the `new` keyword to allocate memory for the array.

3. Initialize the Array: Assign values to the elements in the array.

Example:
Let's create an array of integers to store 5 numbers.

# Step 1: Declare the Array

Ex: int[ ] numbers;

This line declares an array named `numbers` that will hold integers.

# Step 2: Instantiate the Array

Ex: numbers = new int[5];

This line allocates memory for 5 integers. Now `numbers` can hold 5 elements.

# Step 3: Initialize the Array

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 43
Object Oriented with java programming

numbers[0] = 10;

numbers[1] = 20;

numbers[2] = 30;

numbers[3] = 40;

numbers[4] = 50;

Here, we assign values to each element in the array using their indices.

# Full Example #1:

public class ArrayExample


{ OUTPUT:
public static void main(String[] args) Element at index 0: 10
{ Element at index 1: 20
// Step 1: Declare the array Element at index 2: 30
int[ ] numbers; Element at index 3: 40
Element at index 4: 50
// Step 2: Instantiate the array
numbers = new int[5];

// Step 3: Initialize the array


numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;

// Print the elements of the array


for (int i = 0; i < numbers.length; i++)
{
System.out.println("Element at index " + i + ": " + numbers[i]);
}
}
}

Key Points:

- Arrays in Java are zero-indexed, meaning the first element is at index 0.

- The size of the array is fixed once it is instantiated.

- You can access and modify the elements of the array using their indices.

Example #2: (Displays the elements using for each loop)

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 44
Object Oriented with java programming

public class ArrayExample


{ OUTPUT:
public static void main(String[] args) Element at index 0: 10
{ Element at index 1: 20
// Step 1: Declare the array and intialize Element at index 2: 30
int[ ] numbers = {10,20,30,40,50}; Element at index 3: 40
Element at index 4: 50
// Print the elements of the array
int i=0;
for (int number:numbers)
{
System.out.println("Element at index " + i + ": " + number);
i++;
}
}
}

Example #3

import java.util.Scanner;

public class ArrayExample


{
public static void main(String[] args)
{
// Create a Scanner object for reading user input
Scanner scanner = new Scanner(System.in);

// Step 1: Declare the array


int[ ] numbers;

// Ask the user for the size of the array


System.out.print("Enter the number of elements you want to store: ");
int size = scanner.nextInt();

// Step 2: Instantiate the array


numbers = new int[size];

// Step 3: Initialize the array using user input


for (int i = 0; i < size; i++)
{
System.out.print("Enter element at index " + i + ": ");
numbers[i] = scanner.nextInt();
}

System.out.println("");
// Print the elements of the array
System.out.println("Elements of the array are:");
for (int i = 0; i < numbers.length; i++)

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 45
Object Oriented with java programming

{
System.out.println("Element at index " + i + ": " + numbers[i]);
}
}
}

OUTPUT:

Enter the number of elements you want to store: 5

Enter element at index 0: 22


Enter element at index 1: 55
Enter element at index 2: 66
Enter element at index 3: 33
Enter element at index 4: 44

Elements of the array are:


Element at index 0: 22
Element at index 1: 55
Element at index 2: 66
Element at index 3: 33
Element at index 4: 44

2. Two Dimensional Array:


Two dimensional arrays are the data is stored in row and column based index (also known as
matrix form).

Syntax to Declare Multidimensional Array in Java

1. dataType[rowsize ][columnsize ] ArrayName; (or)


2. dataType [rowsize][columnsize] ArrayName; (or)
3. dataType ArrayName [rowsize][columnsize]; (or)
4. dataType [rowsize] ArrayName[columnsize];

Example to instantiate Multidimensional Array in Java

1. int[ ][ ] arr=new int[3][3];//3 row and 3 column

Example to initialize Multidimensional Array in Java

arr[0][0]=1;
arr[0][1]=2;

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 46
Object Oriented with java programming

arr[0][2]=3;
arr[1][0]=4;
arr[1][1]=5;
arr[1][2]=6;
arr[2][0]=7;
arr[2][1]=8;
arr[2][2]=9;

Example of Multidimensional Java Array

Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional array.

//Java Program to illustrate the use of multidimensional array


class Test_Array
{ OUTPUT:
public static void main(String args[ ]) 1 2 3
{ 2 4 5
//declaring and initializing 2D array 4 4 5
int arr[ ][ ]={{1,2,3},{2,4,5},{4,4,5}};

//printing 2D array
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}
}

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 47
Object Oriented with java programming

Class and Object in Java


Class: Class is a blue print which is containing only list of variables and method .A class is a group of
objects that has common properties.
OR
Class: Class can be defined as a template / blueprint that describe the state and behavior of the objects.

A class contains:
1. Field/Data Member: Data items are called fields or data members (Instance of class)
2. Method : Functions are called methods.
3. Constructor
4. Block

In java variables are known as instances of classes, which are actual objects.

Syntax to declare a class:


access modifier class ClassName
{
// Fields
[access modifier] [static] [final] datatype fieldName1;
[access modifier] [static] [final] datatype fieldName2;

// Constructors
access modifier ClassName([parameters])
{
// Constructor body
}

// Methods
access modifier [static] datatype methodName1([parameters])
{
// Method body
}

Here's what each part means:

1. access modifier: Specifies the visibility of the class, fields, or methods. Examples include public,
private, protected, or default (no modifier).
2. class: Keyword indicating the declaration of a class.
3. ClassName: The name of the class. By convention, class names start with an uppercase letter.
4. Fields: Variables declared within the class representing its state.

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 48
Object Oriented with java programming

5. [static]: Keyword indicating that a field or method belongs to the class itself rather than to instances
of the class.
6. [final]: Keyword indicating that a field's value cannot be changed once initialized, or that a method
cannot be overridden by subclasses.
7. Constructors: Special methods used for initializing objects. They have the same name as the class.
8. Parameters: Values passed to constructors or methods.
9. Methods: Functions defined within the class representing its behavior.
10. datatype: The data type of fields, parameters, and return values, such as int, String, boolean, etc.

Java Class Naming Conventions


1. Use PascalCase: Class names should be in PascalCase, which means the first letter of each word
in the name is capitalized. For example: `MyClass`, `Car`, `EmployeeDetails`.

2. Choose descriptive names: Class names should be descriptive and indicative of the class's
purpose or responsibility

3. Avoid abbreviations: While shortening names might seem convenient, it can make your code
less readable. Try to avoid abbreviations unless they are widely understood and accepted (e.g.,
`HTMLParser`, `URL`, `IO`, etc.).

4. Start with a capital letter: Always start class names with a capital letter to distinguish them from
variables and methods, which typically start with lowercase letters.

5. Avoid underscores: Unlike variables and constants, which may use underscores to separate words
(e.g., `my_variable`), class names should not contain underscores. Instead, use PascalCase to
indicate word boundaries.

Field Declaration:
Data is encapsulated in a class by placing data fields inside the body of a class definition.
These variables are called instance variables because of they are created whenever an object of the
class they are instantiated.

Example for Field Declaration:


class Rectangle
{
int length, width;
}

Here, in above example for class field declaration Rectangle is the class name and in this class we
declared the two variable like length and width.

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 49
Object Oriented with java programming

Note: If we are created a class like above example, no storage space or memory allocation has been
created for these variables, also called as member variables.

Method Declaration:
A method is a collection of statements that perform some specific task and return the result to the caller. A method
can perform some specific task without returning anything.
Syntax
modifier data_type method_name (Parameter List)
{
// method body
}

The syntax shown above includes −


 Modifier
 Data_type
 Name of the method
 Type of the value or return
 Parameter list
 The body of the method

Example1:
class Rectangle
{
int length;
int width;

void getdata(int x, int y)


{
length=x;
width=y;
}
}

Here, void is return type it does not return any value.


Example2:
class Rectangle
{
int length, width;
void getdata(int x, int y)
{
length=x;
width=y;
}
int rectArea()
{
int area=length*width;
return(area);
}
}

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 50
Object Oriented with java programming

Java Object :
Object: Object is an instance of class, object has state and behaviors.
An Object in java has three characteristics:
1. State
2. Behavior
3. Identity

State: Represents data (value) of an object.


Behavior: Represents the behavior (functionality) of an object such as deposit, withdraw etc.
Identity: Object identity is typically implemented via a unique ID. The value of the ID is not visible to
the external user. But, it is used internally by the JVM to identify each object uniquely.

Object: Object is an entity has state and behavior is known as an object.


Ex: Chair, Bike, Pen, Table, Animal

Object Definitions:

 Object is a real world entity.


 Object is a run time entity.
 Object is an entity which has state and behavior.
 Object is an instance of class

Creation of Object:
An object in java is essentially a block of memory that contains space to store all the instance
variables. Creating an object is also referred to as instantiating an object.

 An objects in java created using new operator. The new operator dynamically allocates memory for
an object.

Example for creating an object:

A simple class example


Suppose, Student is a class and student's name, roll number, age will be its property. Let’s see this in
Java syntax
class Student
{
String name;
Int rollno;
int age;
}

Creating Object for the class Student is given below.

Student std; //Declare the object for class student


Std=new Student(); //creating the object.

 Both statements can be combined into one as shown below:

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 51
Object Oriented with java programming

Student std=new Student( );

After the above statement std is instance/object of Student class. Here the new keyword creates an
actual physical copy of the object and assign it to the std variable. It will have physical existence and
get memory in heap area. The new operator dynamically allocates memory for an object

The method Student( ) is the default constructor of the class student. We can create any number of
objects of Student.

Example:

Student std1=new Student( );


Student std2=new Student( );
Student std3=new Student( );

Here there are three objects are created for one Student class. And each object like std1,std2 and std3
contains the copy of the instance variable of the class Student.

Std1 is first object it contains Std2 is second object it contains the Std3 is third object it contains the all
the all instance variable all instance variable instance variable

Like: Name ,roll no, age Like: Name ,roll no, age Like: Name ,roll no, age

Accessing class members/Accessing instance variables and methods:


We can’t use instance variables outside the class and also methods. To do this we must concerned object
and the dot(.) operator as shown below.

Syntax:

Object_name.variable_name=value;
Object_name.method_name(parameter list);

Where,
Object_name Name of the object
variable_nameName of the variable.
Method_nameMethod
Parameter_listActual values to the parameter.

Examples:
Student std=new Student();

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 52
Object Oriented with java programming

Here std is the object, with the std object we can use the instance variables of the class out of the
class like,

 Assigning the values to the variables with reference object.


std.name=”Shridhar”;
std.roll_no=1114520;
age=24;

Example 1: java program to access the class variable by reference variable.


File Name:StudentDemo.java

class Student
{
int rollno;
String name;
int age;
}
public class StudentDemo
{
public static void main(String args[])
{
Student std=new Student(); // Creating an object

std.rollno=1114520; // accessing class members in StudentDemo


std.name="Shridhar";
std.age=24;

//Displaying the values.


System.out.println("Student Roll No is :"+std.rollno);
System.out.println("Student Name is :"+std.name);
System.out.println("Student Age is :"+std.age);
}
}

OUTPUT:
C:\Users\Admin\Desktop>java StudentDemo
Student Roll No is :1114520
Student Name is :Shridhar
Student Age is :24
---------------------------

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 53
Object Oriented with java programming

Example 2: java program to display the area of rectangle


File Name: Rectangle.java

classRectangle
{
int length;
int width;
public static void main(String args[])
{
Rectangle rect=new Rectangle();//instantiate the object
rect.length=100; //Accessing class member
rect.width=35;
int area=rect.length*rect.width;

//Displaying the are


System.out.println("The Area of the rectangle is :"+area);
}
}
OUTPUT:
C:\Users\Admin\Desktop>javac Rectangle.java
C:\Users\Admin\Desktop>java Rectangle
The Area of the rectangle is :3500
-------------------------

Instance Operator:
In Java, the instance operator is represented by the keyword `instanceof`. It is used to check whether
an object is an instance of a particular class or implements a particular interface.

Here's the basic syntax:

object instanceof ClassName;

This operator returns `true` if the object is an instance of the specified class or implements the
specified interface, otherwise it returns `false`.

For example:

class Dog
{
void bark()
{
System.out.println(“Dog is barking”);
}

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 54
Object Oriented with java programming

}
public class Main extends Dog
{
public static void main(String[] args) {
Main animal = new Main();
Animal.bark();
if (animal instanceof Dog) {
System.out.println("The animal is a Dog.");
} else {
System.out.println("The animal is not a Dog.");
}
}
}

OUTPUT:
Dog is barking
The animal is a Dog.

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 55
Object Oriented with java programming

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 56

You might also like