CSE205
OOP- Java
12/01/2025
Java OOP(Object Oriented Programming)
What is?
Object-Oriented Programming or Java OOPs concept refers to
programming languages that use objects in programming. They use
objects as a primary source to implement what is to happen in the
code. Objects are seen by the viewer or user, performing tasks you
assign.
Object means a real-world entity such as a pen, chair, table, computer,
watch, etc. Object-Oriented Programming is a methodology or
paradigm to design a program using classes and objects. It simplifies
software development and maintenance by providing some concepts:
o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation
Object-oriented programming aims to implement real-world
entities like inheritance, abstraction, polymorphism, etc. in
programming. The main aim of OOPs is to bind together the data
and the functions that operate on them so that no other part of the
code can access this data except that function.
Object
Any entity that has state and behavior is known as an object. For
example, a chair, pen, table, keyboard, bike, etc. It can be physical or
logical.
Class
Collection of objects is called class. It is a logical entity.
Inheritance
When one object acquires all the properties and behaviors of a parent
object, it is known as inheritance. It provides code reusability.
Polymorphism
If one task is performed in different ways, it is known as polymorphism.
For example: to convince the customer differently, to draw something,
for example, shape, triangle, rectangle, etc.
What is Java?
Java is a popular programming language, created in 1995.
It is owned by Oracle, and more than 3 billion devices run Java.
It is used for:
Mobile applications (specially Android apps)
Desktop applications
Web applications
Web servers and application servers
Games
Database connection
And much, much more!
Why Use Java?
Java works on different platforms (Windows, Mac, Linux,
Raspberry Pi, etc.)
It is one of the most popular programming languages in the
world
It has a large demand in the current job market
It is easy to learn and simple to use
It is open-source and free
It is secure, fast and powerful
It has huge community support (tens of millions of developers)
Java is an object oriented language which gives a clear structure
to programs and allows code to be reused, lowering
development costs
As Java is close to C++ and C#, it makes it easy for
programmers to switch to Java or vice versa
W3Schools' Java Editor
When learning Java at [Link], you can use our "Try it Yourself" tool,
which shows both the code and the result. It is used to write, run, and test
code right in your browser:
[Link]
public class Main {
public static void main(String[] args) {
[Link]("Hello World");
}
Java Syntax
[Link]
public class Main {
public static void main(String[] args) {
[Link]("Hello World");
}
Explanation: Code Breakdown
public class Main {
public: This is an access modifier, meaning the Main class is accessible
from anywhere.
class Main: Declares a class named Main. In Java, all code resides within
a class, and the file name (e.g., [Link]) should match the class name.
public static void main(String[] args) {
public: Makes the main method accessible from anywhere. This is
required for the program to start execution.
static: Indicates that the main method belongs to the class itself, not to an
instance of the class. This is important because the Java runtime calls the
main method without creating an object of the class.
void: Specifies that the main method does not return any value.
main: The name of the method. Java programs begin execution from the
main method.
String[] args: This parameter is used to accept command-line arguments
passed when running the program. It's an array of String objects.
[Link]("Hello World");
[Link]: This prints the text "Hello World" to the console,
followed by a new line.
o System: A built-in class that provides access to system-level
resources.
o out: A static member of System class, representing the standard
output stream (the console).
o println: A method of out that prints the text and moves the cursor
to the next line.
Closes the main method.
Closes the Main class.
What Happens When You Run the Program?
1. The Java runtime looks for the main method in the Main class.
2. The main method executes the statement inside it:
[Link]("Hello World");.
3. The text "Hello World" is printed to the console.
Output
Hello World
This program is often referred to as the "Hello World" program, a traditional
way to introduce someone to a new programming language!
Java Output / Print
Example
[Link]("Hello World!");
You can add as many println() methods as you want. Note that it will add a
new line for each method:
Example
[Link]("Hello World!");
[Link]("I am learning Java.");
[Link]("It is awesome!");
Double Quotes
Text must be wrapped inside double quotations marks "".
If you forget the double quotes, an error occurs:
Example
[Link]("This sentence will work!");
[Link](This sentence will produce an error);
The Print() Method
There is also a print() method, which is similar to println().
The only difference is that it does not insert a new line at the end of the
output:
Example
[Link]("Hello World! ");
[Link]("I will print on the same line.");
Java Output Numbers
Print Numbers
You can also use the println() method to print numbers.
However, unlike text, we don't put numbers inside double quotes:
Example
[Link](3);
[Link](358);
[Link](50000);
You can also perform mathematical calculations inside the println() method:
Example
[Link](3 + 3);
Example
[Link](2 * 5);
Java Comments
Comments can be used to explain Java code, and to make it more readable.
It can also be used to prevent execution when testing alternative code.
Single-line Comments
Single-line comments start with two forward slashes (//).
Any text between // and the end of the line is ignored by Java (will not be
executed).
This example uses a single-line comment before a line of code:
Example
// This is a comment
[Link]("Hello World");
This example uses a single-line comment at the end of a line of code:
Example
[Link]("Hello World"); // This is a comment
Java Multi-line Comments
Multi-line comments start with /* and ends with */.
Any text between /* and */ will be ignored by Java.
This example uses a multi-line comment (a comment block) to explain the
code:
Example
/* The code below will print the words Hello World
to the screen, and it is amazing */
[Link]("Hello World");
Note: Single or multi-line comments?
It's up to you which one you use. Normally, we use // for short comments,
and /* */ for longer.
Java Variables
Java Variables
Variables are containers for storing data values.
In Java, there are different types of variables, for example:
String - stores text, such as "Hello". String values are surrounded by
double quotes
int - stores integers (whole numbers), without decimals, such as 123
or -123
float - stores floating point numbers, with decimals, such as 19.99 or
-19.99
char - stores single characters, such as 'a' or 'B'. Char values are
surrounded by single quotes
boolean - stores values with two states: true or false
Declaring (Creating) Variables
To create a variable, you must specify the type and assign it a value:
Syntax
type variableName = value;
Where type is one of Java's types (such as int or String),
and variableName is the name of the variable (such as x or name).
The equal sign is used to assign values to the variable.
To create a variable that should store text, look at the following
example:
Example
Create a variable called name of type String and assign it the value "John".
Then we use println() to print the name variable:
String name = "John";
[Link](name);
To create a variable that should store a number, look at the following
example:
Example
Create a variable called myNum of type int and assign it the value 15:
int myNum = 15;
[Link](myNum);
You can also declare a variable without assigning the value, and assign the
value later:
Example
int myNum;
myNum = 15;
[Link](myNum);
Note that if you assign a new value to an existing variable, it will overwrite
the previous value:
Example
Change the value of myNum from 15 to 20:
int myNum = 15;
myNum = 20; // myNum is now 20
[Link](myNum);
Final Variables
If you don't want others (or yourself) to overwrite existing values, use
the final keyword (this will declare the variable as "final" or "constant",
which means unchangeable and read-only):
Example
final int myNum = 15;
myNum = 20; // will generate an error: cannot assign a value to a
final variable
Other Types of Variables
A demonstration of how to declare variables of other types:
Example
int myNum = 5;
float myFloatNum = 5.99f;
char myLetter = 'D';
boolean myBool = true;
String myText = "Hello";
Java Print Variables
Display Variables
The println() method is often used to display variables.
To combine both text and a variable, use the + character:
Example
String name = "John";
[Link]("Hello " + name);
You can also use the + character to add a variable to another variable:
Example
String firstName = "John ";
String lastName = "Doe";
String fullName = firstName + lastName;
[Link](fullName);
For numeric values, the + character works as a mathematical operator (notice
that we use int (integer) variables here):
Example
int x = 5;
int y = 6;
[Link](x + y); // Print the value of x + y
Java Declare Multiple Variables
To declare more than one variable of the same type, you can use a comma-
separated list:
Example
Instead of writing:
int x = 5;
int y = 6;
int z = 50;
[Link](x + y + z);
You can simply write:
int x = 5, y = 6, z = 50;
[Link](x + y + z);
One Value to Multiple Variables
You can also assign the same value to multiple variables in one line:
Example
int x, y, z;
x = y = z = 50;
[Link](x + y + z);
Java Identifiers
All Java variables must be identified with unique names.
These unique names are called identifiers.
Identifiers can be short names (like x and y) or more descriptive names
(age, sum, totalVolume).
Note: It is recommended to use descriptive names in order to create
understandable and maintainable code:
Example
// Good
int minutesPerHour = 60;
// OK, but not so easy to understand what m actually is
int m = 60;
The general rules for naming variables are:
Names can contain letters, digits, underscores, and dollar signs
Names must begin with a letter
Names should start with a lowercase letter, and cannot contain
whitespace
Names can also begin with $ and _
Names are case-sensitive ("myVar" and "myvar" are different
variables)
Reserved words (like Java keywords, such as int or boolean) cannot
be used as names
Java Variables - Examples
Real-Life Examples
Often in our examples, we simplify variable names to match their data type
(myInt or myNum for int types, myChar for char types, and so on). This is
done to avoid confusion.
However, for a practical example of using variables, we have created a
program that stores different data about a college student:
Example
// Student data
String studentName = "John Doe";
int studentID = 15;
int studentAge = 23;
float studentFee = 75.25f;
char studentGrade = 'B';
// Print variables
[Link]("Student name: " + studentName);
[Link]("Student id: " + studentID);
[Link]("Student age: " + studentAge);
[Link]("Student fee: " + studentFee);
[Link]("Student grade: " + studentGrade);
Calculate the Area of a Rectangle
In this real-life example, we create a program to calculate the area of a
rectangle (by multiplying the length and width):
Example
// Create integer variables
int length = 4;
int width = 6;
int area;
// Calculate the area of a rectangle
area = length * width;
// Print variables
[Link]("Length is: " + length);
[Link]("Width is: " + width);
[Link]("Area of the rectangle is: " + area);
You will learn more about data types in the next class.