0% found this document useful (0 votes)
40 views26 pages

Cse205 1

Uploaded by

r.rayhan241974
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views26 pages

Cse205 1

Uploaded by

r.rayhan241974
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

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 W3Schools.com, 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:

Main.java

public class Main {

public static void main(String[] args) {

System.out.println("Hello World");

}
Java Syntax
Main.java

public class Main {

public static void main(String[] args) {

System.out.println("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., Main.java) 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.

System.out.println("Hello World");

 System.out.println: 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:
System.out.println("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
System.out.println("Hello World!");

You can add as many println() methods as you want. Note that it will add a
new line for each method:

Example
System.out.println("Hello World!");

System.out.println("I am learning Java.");

System.out.println("It is awesome!");

Double Quotes
Text must be wrapped inside double quotations marks "".

If you forget the double quotes, an error occurs:

Example
System.out.println("This sentence will work!");

System.out.println(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
System.out.print("Hello World! ");

System.out.print("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
System.out.println(3);

System.out.println(358);

System.out.println(50000);

You can also perform mathematical calculations inside the println() method:

Example
System.out.println(3 + 3);

Example
System.out.println(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

System.out.println("Hello World");

This example uses a single-line comment at the end of a line of code:

Example
System.out.println("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 */

System.out.println("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";

System.out.println(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;

System.out.println(myNum);

You can also declare a variable without assigning the value, and assign the
value later:

Example
int myNum;

myNum = 15;

System.out.println(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

System.out.println(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";

System.out.println("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;

System.out.println(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;

System.out.println(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;

System.out.println(x + y + z);

You can simply write:

int x = 5, y = 6, z = 50;

System.out.println(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;

System.out.println(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

System.out.println("Student name: " + studentName);

System.out.println("Student id: " + studentID);

System.out.println("Student age: " + studentAge);

System.out.println("Student fee: " + studentFee);

System.out.println("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

System.out.println("Length is: " + length);

System.out.println("Width is: " + width);

System.out.println("Area of the rectangle is: " + area);

You will learn more about data types in the next class.

You might also like