Java Unit - 1 Notes
Java Unit - 1 Notes
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.
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.
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.
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
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.
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.
5. Abstraction
Data Abstraction may also be defined as the process of identifying only the required
characteristics of an object ignoring the irrelevant details.
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.
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.
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.
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.
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.
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
Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 9
Object Oriented with java programming
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
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
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
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
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
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.
Types of Variables
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.
Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 13
Object Oriented with java programming
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.
Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 14
Object Oriented with java programming
Example:
//constructor
Student(int r, String n)
{
rollno = r;
name = n;
}
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
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
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
// 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
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.
= 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;
// create variables
int a = 4;
int var;
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.
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
}
}
// && 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.
Operator Meaning
+ Unary plus: not necessary to use since numbers are positive without using it
// 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
// 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);
// 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.
Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 23
Object Oriented with java programming
~ 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
^ Bitwise exclusive OR
These operators are not generally used in Java. To learn more, visit Java Bitwise and Bit Shift
Operators.
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;
Output
even
Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 25
Object Oriented with java programming
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
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
}
Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 26
Object Oriented with java programming
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.
Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 27
Object Oriented with java programming
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:
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
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.
Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 29
Object Oriented with java programming
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.
Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 30
Object Oriented with java programming
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
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
}
class Main
{
public static void main(String args[ ])
{
int number = 44;
String size;
case 42:
size = "Medium";
Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 32
Object Oriented with java programming
break;
case 48:
size = "Extra Large";
break;
default:
size = "Unknown";
break;
}
System.out.println("Size: " + size);
}
}
Output:
Size: Large
Java Looping:
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.
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:
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.
// 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
//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.
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.
// 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
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:
Here,
Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 37
Object Oriented with java programming
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 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).
continue;
Example:
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.
Syntax:
return value;
return sum;
}
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.
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
# 1. Declaration:
First, you declare an array variable, specifying the type of the elements the array will hold.
Syntax:
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.
# 2. Creation:
Next, you create the array, which means specifying its size (the number of elements it can hold).
You can combine the declaration and creation into a single statement.
Initializing an Array:
You can also initialize the array with values at the time of declaration.
# Integer Array:
# String Array:
# Double Array:
Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 42
Object Oriented with java programming
char[ ] charArray = {'a', 'b', 'c', 'd'}; // An array of 4 characters initialized with values
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.
Example:
Let's create an array of integers to store 5 numbers.
This line declares an array named `numbers` that will hold integers.
This line allocates memory for 5 integers. Now `numbers` can hold 5 elements.
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.
Key Points:
- You can access and modify the elements of the array using their indices.
Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 44
Object Oriented with java programming
Example #3
import java.util.Scanner;
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:
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;
Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional array.
//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
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.
// Constructors
access modifier ClassName([parameters])
{
// Constructor body
}
// Methods
access modifier [static] datatype methodName1([parameters])
{
// Method body
}
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.
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.
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
}
Example1:
class Rectangle
{
int length;
int width;
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
Object Definitions:
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.
Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 51
Object Oriented with java programming
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:
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
Syntax:
Object_name.variable_name=value;
Object_name.method_name(parameter list);
Where,
Object_name Name of the object
variable_nameName of the variable.
Method_nameMethod
Parameter_listActual 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,
class Student
{
int rollno;
String name;
int age;
}
public class StudentDemo
{
public static void main(String args[])
{
Student std=new Student(); // Creating an object
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
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;
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.
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