java - mobile, internet,
pop oop
Introduction to Java
function object
Introduction to Java c c++, java, python
[Java is a high-level programming language and is very popular amongst software developers.
Java is an Objective Oriented Programming (OOP) language.] One reason for Java’s popularity
is that it is platform independent. This means that the same Java program can be run on
=====================
many different types of computers as long as they all have the Java Runtime Environment
(JRE) installed and running. To create Java programs, you ========================
need to have an Integrated
====== ============
Development Environment (IDE). Some of the well-known ones are Java Netbeans, BlueJ,
============================ ==================
Eclipse, and IntelliJ. We will be working with BlueJ because it is the best IDE for beginners.
================ ====================================
Object Oriented Programming
Object Oriented Programming (OOP) is a different and modern approach to programming. C++,
Python and Java are some examples of Object Oriented Programming languages.[ OOP is based
on the fundamental concept of objects. Associated with objects are other OOP concepts such
======
as classes, data hiding, inheritance, polymorphism, encapsulation, and abstraction.]
==================================================================
Object: [An object is the basic element of OOP. An object is anything that has well-defined
characteristics and behaviour. An object has a set of properties that defines it uniquely. ]
========
Class: [A class can be understood as a collection of similar objects. In OOP, a class is a data
==========================
type and objects are its variables. The entire set of data and methods of an object contained in
a class.] A class can have many objects in a program. Each object is called an instance of its
class.
===============================
====
Data Hiding
In Java, [a variable can be declared as private or public. A private variable is accessible only
within the class in which it is declared.][ A public variable is accessible to all the classes in the
program. When a variable is declared as private, it remains hidden from all other classes.] Thus,
it can be accessed only by the methods of the class it belongs to.
[ A method can also be public and private. When a method is public, it can be invoked within
the same class in which it is declared, or in any other class. Private methods can only be
invoked within the class in which they are declared.] They are not visible to other classes. This
is what is called data hiding.
=========
Inheritance:[ When one class acquires the properties and behaviours of a parent class, it is
known as inheritance. This means that an object of one class acquires the properties of
objects of another class. ]
Polymorphism: [Poly means many and morphism means forms. When the same methods can
===========================
be invoked for different purposes, it is known as polymorphism]
Encapsulation: In programming, binding (or wrapping) code and data together into a single
unit is known as==================================================
encapsulation. A Java class is an example of encapsulation.
Data Abstraction: Hiding internal details and revealing only the essential functionality is
known as abstraction.=====================================================
Starting BLUEJ
We will learn programming in Java by using BlueJ. Let us start the BlueJ environment.
Select Start → All Programs → BlueJ
OR
Double click the BlueJ icon on the desktop.
After a few seconds, the BlueJ window will open.
Start screen of BlueJ
BlueJ window
Writing a Java Program
1. Click Project → New Project
2. The New Project dialog box will appear. Enter the project name in the Folder name text
box and click Create
3. In Java, a folder is created on your hard disk with the project name which will store the
files for this project.
4. Now, click on New Class button on the BlueJ
5. Create New Class dialog box appear. Enter the class name in the text box and click
OK.
6. The class is created and its icon appears on the BlueJ.
------
7. Double click the program icon. A program template is displayed. This is just to assist
you on writing a Java Program.
8. Delete the default program template and type your program.
Compiling a Java Program
[ Compilation means to convert the source code to object code.] If the program has errors, all are
=====================
reported after compilation completes. You have to correct the program and again compile it. A
program executes only when it is error free.
To compile a Java Program follow the steps:
1. Click the Compile button. If no error is found in the program, a message will appear on
the bottom pane ― Class compiled – no syntax errors.
===========================
2. Now, your program is ready for execution. Close the window by clicking the close button.
The BlueJ window will appear.
Running a Java Program
1. Right click the class icon and click void main() to execute it.
2. The output will appear on the screen. Click the close button to close the output screen
Modifying a Program
If you want to do some editing in a program, double click the class icon. The program screen
will appear. Make the required changes and again compile the program to convert source code
to object code. If no syntax error is displayed on the screen, it means the changes are correct.
Close the window by clicking the Close button and then execute the program.
KEYWORDS: Keywords are reserved words that have a predefined meaning in the
======================================================
programming language. These cannot be used as an identifier, i.e. a variable name, class
==================== ----------------------------------------------
name, or method name. The keywords in Java are given below
case switch else classbreak
if static
do const throws float char
try int double void goto
for while new import boolean
long if byte package private
catch short public class default
DATA TYPES: Each variable in a program must be given a data type, i.e., the type of data it
---------------------------------------------------------------------------
can store. Data type also helps decide how many bytes the variable will take for storage.
============================================================
The following table lists the data types in Java.
Data Type Description Storage
byte byte length integer age------2/ 3 digit 1 byte
short short integer 5 digit 2 bytes
int integer 7-8 digit 4 bytes
long long integer mobile 8 bytes
Single precision floating point
float (single precision floating points display the number 4 bytes
with------------------
7 digits after the decimal point)
Double precision floating point
double (double precision floating points display the number 8 bytes
with 15 digits after the decimal point) ---------
===========
char Single character 'm' 2 bytes
boolean boolean value (true or false) 1 bit
====
8 bits= 1 byte
Literals: Constants or literals refer to fixed values that do not change during the execution of a
program. Constants can be classified as:
• Integer constant int a=5; ( 5 is literal)
• Floating point constant a=6
• Character constant
• String constant
Integer Constant: It is whole number with positive or negative values, e.g. 125, -36, 69, -2 etc.
===============
Floating point Constant: It is a number with a decimal point, having positive or negative values,
e.g. 3.14, -26.5, 7.0, -19.0 etc. ======================================
===================
Character Constant: A character constant represents letters in uppercase or lowercase, digits,
=======================================================
and special characters. It is a single character enclosed in single quotes( ‘ ’ )
===================
e.g. ‘A’, ‘a’, ‘7’, ‘+’, ‘?’ etc. =====================================
===
String Constant: A string constant consists of one or more than one character enclosed in double
=========================================
quotes( “ ” )
char gender ='m'
e.g. “Hello”, “A”, “How are you?” etc.
========= String name= " samridh", address=" p-121, v.i.p"
Variables: A variable is a portion of memory used to store a value. A good variable name is one
=================================================================
that specifies what it represents. For example, total_marks, grade are some variable names.
===============================
There are certain rules of naming a variable in Java.
=======================
1. A valid variable name is a sequence of one or more letters(a to z or A to Z), digits(0 to 9), or
underscore(_) characters. Space, punctuation marks, or symbols cannot be a part of a
int a b; x ===========================================
variable. int a_b;
int a+b;
2. xVariables should begin with a letter, underscore(_), or dollar($) character, but in some
cases these may be reserved as compiler specific keywords. In no case can variables
begin with a digit. a _ int a123;
3. The rest part of the identifiers (except the first character) can use letters, underscore, or
digits.
4. Uppercase and lowercase letters are distinct. int A;
5. Identifiers/variables cannot be a keyword. a=5; xxxxxxx
int if=5;
Java is a case sensitive language. It means that an identifier written in capital letters is not
========================================================================
equivalent to another one with the same name written in lowercase letters. Thus, RESULT,
============================================================
result, Result are three different variables
Following table shows the list of some valid and invalid variables or identifiers in Java.
Valid Identifiers Invalid Identifiers
Name 2list (it cannot start with digit)
===
Add5 Father name (it cannot have space)
_mark =========
float (it cannot be a reserved word)
==== =============
First_name tot+mark (it cannot have a + sign)
Declaration of Variables
The type of a variable decides the value it will store
• The numeric variables use data types- byte, int, long, float, and double
• The non-numeric variables use data types –char and String
• The boolean variable uses the data types boolean
Initializing a variable
The method of assigning a value and defining the data type at the same time is called
==================================================================
initialization. The variable must be initialized before using it in the program.
==========
e.g.
char ch= ‘A’; long n=0; int num=0;
==========
String s= “Java”; boolean b=false; double d=0.0;
• You can initialize all identifiers in a single statement while defining them with commas.
========== =====================================================
e.g. int a=0, b=0, c=0;
=========== or
you can initialize them individually in three statements.
int a=0;
=======
int b=0;
int c=0;
• You can initialize the variable with some other value also, but it should match with the
data type of the variable.
e.g.
int rollno=25; long salary=100000;
double pft=3400.5 boolean pass=true;
Classes and Methods in Java
A class is a collection of objects which contains a set of data members and member methods.
========================================================================
The member methods operate on the data members.
Defining a class
a class may be defined as:
public class <class name>
abc
{
type variable1;
type variable2;
.
.
.
type variable;
type methodname1
Body of the method
}
}
sum()--------->function
[Link]("hello");------> function
Defining a method
main()--------------->
Functions are created so that the set of code can be used at different points in the program.
========================================================================
Functions are essentially methods in java.
In Java, a method may be defined as :
<access-specifier> <return-type> <method-name>(<formal parameter list>)
public, private void main
{
Body of the method
<access-specifier> : This can be public or private.
<return-type> : This is the data type of the value returned by the method.
<method-name> : This is the name of the method.
<formal parameter list> :This is the comma separated list of variables that receives the
values when a method is called.
OPERATORS
Operators are used for performing operation on constants and variables. The variables and
==============
========================================================
constants are called operands. Operators and operands together form an expression.
======================
The operators that require only one operand are called unary operators while the ones that require
two operands are called binary operators. a+b
The operators in Java can be classified into the following types:
• Arithmetic operators
• Relational operators
• Logical operators
• Increment and Decrement operators
Arithmetic Operators: Arithmetic operators are those that are used for arithmetic calculations.
======================================================
The five arithmetic operators used in Java are given below:
Operators Meaning Example Output
Addition 5+3 8
Or 5.2+3 8.2
+
Unary plus +6
Subtraction 5-3 2
-
5.2-3 2.2
Or
Unary minus -4
5*3 15
* Multiplication
5.2*3 15.6
21/6 3
/ Division
21.0/6 3.5
% Modulus 10%3 1
====================================================
Some points to note about Arithmetic Operators:
• If any of the operands is a real number, the result will also be real.
• The modulus operation gives the remainder as result. Therefore, it requires an integer value,
===========================================
otherwise you will get an error.
• Unary plus and minus work on a single operand, and multiply it with +1 or -1 respectively.
a++----->
The table given below shows how algebraic expressions are written in Java
Algebraic expressions Java expressions
a=b×c a=b*c; int a=5;
======= =
a=a+1; a++;
S=a2+b2+c2 S=a*a+b*b+c*c;
========== a^2 xxxxxx
=======
R= 𝑑
𝑎𝑏 R=(a*b)/d;
====== ++ increment
==
-- decrement
R= 𝑎𝑏
𝑎+𝑏 R=(a+b)/(a*b);
====
Precedence of Arithmetic Operators
The precedence of arithmetic operators in Java is:
1. Parentheses ( ) (5+6)*4
bedmas
2. Unary operators (+ , -) 5+24=29
3. Exponent (^)
4. Multiplication (*), Division (/), Modulus (%) 3/2*5
5. Addition(+), Subtraction (-) 7-3+2= 4+2 1*5
The expression is evaluated from left to right, in case of equal priority ( The operator that appears
first will be evaluated first)
Consider the expression given below to understand the precedence.
int a, b=2, c=4;
---------------------
a=b*3/4+c/4+5/8
========
=2*3/4+4/4+5/8
=6/4+4/4+5/8
=1+4/4+5/8
=1+1+5/8
=1+1+0
=2+0
=2
Relational Operators: Relational operators are used to compare two expressions. The result of a
relational operation is a =============================================
boolean value that can be either true or false. The relational =============
operators used
=======================================================
in Java are given below:
a==b
Relational Operator Meaning Example Output
== Equal to 8==5 False
!= Not equal to 8!=5 True
> Greater than 8>5 True
< Less than 5<5 False
>= Greater than or equal to 8>=8 True
<= Less than or equal to 8<=5 false
Note: The operator ‘=’ (one equal sign) is different from the operator ‘==’ (two equal sign). The first
one (=) is an assignment operator, i.e., it assigns the value on its right to the variable on its left, and
=============================================================================
the other one (==) is an equality operator that compares if the two expressions on its either side are
=============================================================================
equal to each other and results in either true or false.
=========================================
Logical Operator: Java supports three logical operators. They are used with one or more relational
================================
expressions and result in either true or false. The logical operators are given below:
========================================
Logical Operator Meaning Example Output
t f
&& (AND) True if both the conditions (5==5) && (3>6) False
===== ====
are true, and false otherwise ================
(10>=5) && (3!=5) True
|| (OR) True if either of its two (5==5) || (3>6) True
conditions are true, and false ===============
if both the conditions are
false (5>=10) || (3==5) False
! (NOT) False if the condition is true !(5==5) False
====== =====
======= and true if the condition is
false
!(6<4) True
=====
!((5==5) && (3>6)) True
!((5==5) || (3>6)) False
Assignment Operator
The assignment operator is used to assign a value to a variable. For example,
=======================================================
A=10; it assigns the value 10 to the variable A
B=5; it assigns the value 5 to the variable B
A=B; it assigns the value of variable B to variable A
Compound Assignment Operator
Compound assignment operators are used to perform an operation with the value currently
=======================================================================
stored in a variable, and stores the new value in the same variable.
====================================================
The list of compound assignment operators are given below:
Expression Is equivalent to
Value +=c; Value=Value + c;
============== a=a+b;
A – =5; a=a – 5; a+=b;
=======
a/=b; a=a/b;
P*=u+100; P=P*(u+100);
A%=10; A=A%10;
Increment and Decrement Operators
The increment and decrement operators are unary operators as they require only one operand.
The increment operator (++) increases the value stored in a variable by one.
The decrement operator (--) decreases the value stored in a variable by one.
The increment and decrement operators can be used as prefix (before the operand) or suffix
(after the operand)
a++;
++a; int a=5;
These are equivalent to
a=a+1; a++; ------->a=6
Similarly, a=a+1; -------> a=6
a--;
--a;
These are equivalent to
a=a-1;
++a prefix a++---> postfix
Both prefix and postfix versions of the operators appear to be the same, but they make a
difference if the value of the variable is used in an assignment operation.
A pre-increment or pre-decrement operator first carries out the increment/decrement
operation and then assigns the new value
A post-increment or post-decrement operator first assigns the value and then carries out the
increment/decrement operation.
Let us understand the concept through the example given below:
Example 1
int A=5, B;
B=A++;
[Link](“A = ”+A+ “ and B = ”+B);
The initial value of variable A is 5. It first assigns its value to variable B and then increments
itself to 6. The output here is
A = 6 and B=5
Example 2
int A=5, B;
B=++A;
[Link](“A = ”+A+ “ and B = ”+B);
The initial value of variable A is 5. It first increments its value to 6 and then assigns it to
variable B. The output here is
A = 6 and B=6
Exercises
Objective Type Questions
A. Fill in the blanks with the correct words.
1. The int data type takes ___________ bytes for storage.
2. ‘A’ is a ___________ constant.
3. float a=45.34; is a/an ___________ statement.
4. The output of 20%6 in Java will be ___________.
B. Write T for the true statement and F for the false one.
1. In Java, a class is a capsule of data members and member functions.
2. To run a Java program, double click the compiled class.
3. A variable name can start with a digit.
C. Choose the correct option
1. Which data type is used to store a whole number?
a. float b. int
c. double d. long double
2. Which of these is an invalid String constant?
a. “g” b. “Hello”
c. ‘9’ d. “*****”
3. Which of these is not a valid initialization?
a. int a=12; b. float b=34.6;
c. char a=‘A’; d. String S=‘Hello!’;
Descriptive Type Questions
D. Answer the following
1. What do you understand by object-oriented programming?
2. What is a class in Java? What is it composed of?
3. What do you understand by data type? List the data types in Java.
E. Write Java Program for the following:
1. Write a Java program to accept the price of one book. Calculate and display the price
of one dozen book.
2. Write a Java program to accept the length and breadth of a rectangle. Calculate and
display the perimeter and area of the rectangle.
3. Write a Java program to accept the cost price(cp) and selling price(sp) of an item.
Considering the shop keeper has made a profit, calculate and display the profit and
profit percentage.
4. Write a Java program to accept the principal amount(p), rate(r) and time(t). Calculate
and display the simple interest(SI) and final amount(A).
5. Write a Java program to accept the height and base of one triangle. Calculate and
display the area of the triangle.
6. Write a Java program to accept the radius of a circle. Calculate and display the area of
the circle.
*******************************