CHAPTER TWO
BASICS OF JAVA PROGRAMMING
OOP CH-2 07:52 AM
INTRUDUCTION
ꭥIn this Chapter you learned how to create, compile, and run a Java program. Now you will learn how to solve
practical problems programmatically.
ꭥThrough these problems, you will learn elementary programming using primitive data types, variables,
constants, operators, expressions, and input and output.
OOP CH-2 07:52 AM
Writing Simple Programs
Writing a program involves designing algorithms and translating algorithms into code.
Problem:
It an environmental situation that needs to be solved.
Algorithm:
It describes how a problem is solved in terms of the actions to be executed and the order of their execution.
It can help the programmer plan a program before writing it in a programming language. It can be described in natural languages or in
pseudocode (i.e., natural language mixed with programming code).
OOP CH-2 07:52 AM
Writing Simple Programs
Example-1-:
Write a simple java code for computing the area of a circle. The algorithm for this program can be described as follows:
1. Read in the radius.
2. Compute the area using the following formula: area = radius * radius * p
3. Display the area.
When you code, you translate an algorithm into a program. Syntax:
OOP CH-2 07:52 AM
Writing Simple Programs
OOP CH-2 07:52 AM
Writing Simple Programs
Java Keywords
Keywords are words that are reserved for particular purposes. They have special meanings and cannot be changed
or used for other purposes. The following list shows the reserved words in Java. These reserved words may not be
used as constant or variable or any other identifier names.
OOP CH-2 07:52 AM
Writing Simple Programs
abstract assert boolean break
byte case catch char
class const continue default
do double else enum
extends final finally Float
for goto if implements
import instanceof int interface
long native new package
private protected public return
short static strictfp super
switch synchronized this Throw
throws transient try void
volatile while
OOP CH-2 07:52 AM
Basic syntax
Case Sensitivity − Java is case sensitive, which means identifier Hello and hello would have different
meaning in Java.
Class Names − For all class names the first letter should be in Upper Case. If several words are used to form
a name of the class, each inner word's first letter should be in Upper Case.
Example: class MyFirstJavaClass
Method Names − All method names should start with a Lower Case letter. If several words are used to form
the name of the method, then each inner word's first letter should be in Upper Case.
Example: public void myMethodName()
OOP CH-2 07:52 AM
Basic syntax
Program File Name − Name of the program file should exactly match the class name.
When saving the file, you should save it using the class name (Remember Java is case sensitive) and append
'.java' to the end of the name (if the file name and the class name do not match, your program will not compile).
But please make a note that in case you do not have a public class present in the file then file name can be
different than class name. It is also not mandatory to have a public class in the file.
Example: Assume 'MyFirstJavaProgram' is the class name. Then the file should be saved
as 'MyFirstJavaProgram.java'
public static void main(String args[]) − Java program processing starts from the main() method which is a
mandatory part of every Java program.
OOP CH-2 07:52 AM
Java Identifiers
All Java components require names. Names used for classes, variables, and methods are called identifiers.
In Java, there are several points to remember about identifiers. They are as follows −
All identifiers should begin with a letter (A to Z or a to z), currency character ($) or an underscore (_).
After the first character, identifiers can have any combination of characters.
A key word cannot be used as an identifier.
Most importantly, identifiers are case sensitive.
Examples of legal identifiers: age, $salary, _value, __1_value.
Examples of illegal identifiers: 123abc, -salary.
OOP CH-2 07:52 AM
Java Variables
Variable in Java is a data container that saves the data values during Java program execution. Every
variable is assigned a data type that designates the type and quantity of value it can hold. Variable is a
memory location name of the data.
A variable is a name given to a memory location. It is the basic unit of storage in a program.
The value stored in a variable can be changed during program execution.
A variable is only a name given to a memory location, all the operations done on the variable effects that
memory location.
In Java, all the variables must be declared before use.
OOP CH-2 07:52 AM
Java Variables
How to declare variables?
Variable
Data type
name
int count;
OOP CH-2 07:52 AM
Java Variables
If variables are of the same type, they can be declared together, as follows:
Datatype Variable_1, Variable_2, Variable_3, …
The variables are separated by commas.
OOP CH-2 07:52 AM
Java Variables
Initializing Variables
Variables often have initial values. You can declare a variable and initialize it in one step.
Consider, for instance, the following code:
int count = 1;
This is equivalent to the next two statements:
int count;
count = 1;
You can also use a shorthand form to declare and initialize variables of the same type together.
Example:
int i = 1, j = 2;
OOP CH-2 07:52 AM
Java Variables
A name can only be given to a memory location. It can be assigned values in two ways:
Variable Initialization
Assigning value by taking input
How to initialize variables?
It can be perceived with the help of 3 components that are as follows:
datatype: Type of data that can be stored in this variable.
variable_name: Name given to the variable.
value: It is the initial value stored in the variable.
OOP CH-2 07:52 AM
Reading Input from the Console
Scanner class is used to obtain input from console. Java uses System.out to refer to the standard
output device and System.in to the standard input device. By default, the output device is the
display monitor, and the input device is the keyboard. To perform console output, you simply use
the println method to display a primitive value or a string to the console.
Console input is not directly supported in Java, but you can use the Scanner class to create an object to read
input from System.in, as follows:
OOP CH-2 07:52 AM
Reading Input from the Console
OOP CH-2 07:52 AM
Reading Input from the Console
OOP CH-2 07:52 AM
Reading Input from the Console
OOP CH-2 07:52 AM
Variable Types and Identifiers
A variable designates a location in memory for storing data and computational results in the program. A
variable has a name that can be used to access the memory location.
A programming language is called a strong data typing language if the language needs the instructions in the
programs to clearly state the types of all data unless the data type can be unambiguously implied. Java as
well as languages in the C-family (E.g. C, C++, and C #) are strong data typing languages, while some
examples of popular programming languages that are not strong data typing are Visual Basic and PHP.
There are 2 main types of data in Java.
Primitive data types
Classes
OOP CH-2 07:52 AM
Variable Types and Identifiers
OOP CH-2 07:52 AM
Number Types, Characters, Strings, and Constants
Number Types
Every data type has a range of values. The compiler allocates memory space for each variable or constant
according to its data type. Java provides eight primitive data types for numeric values,
characters, and Boolean values.
OOP CH-2 07:52 AM
Number Types, Characters, Strings, and Constants
Number Types
OOP CH-2 07:52 AM
Number Types, Characters, Strings, and Constants
Number Types
Java uses four types for integers: byte, short, int, and long. Choose the type that is most appropriate for
your variable.
Java uses two types for floating-point numbers: float and double. The double type is twice as big as float. So,
the double is known as double precision, float as single precision. Normally you should use the double type,
because it is more accurate than the float type.
OOP CH-2 07:52 AM
Characters
The character data type, char, is used to represent a single character. A character literal is enclosed in single
quotation marks. Consider the following code:
The first statement assigns character A to the char variable letter. The second statement assigns digit
character 4 to the char variable numChar.
OOP CH-2 07:52 AM
The String Type
The char type represents only one character. To represent a string of characters, use the data type called
String.
Example:
String is actually a predefined class in the Java library just like the classes System, JOptionPane, and
Scanner. The String type is not a primitive type. It is known as a reference type. Any Java class can be used
as a reference type for a variable. The plus (+) sign is used for concatenation.
07:52 AM
The String Type
Concatenating Strings
It combines two strings if two operands are strings.
Example:
07:52 AM
The String Type
Concatenating Strings and Numbers
If one of the operands is a non-string (e.g., a number), the non-string value is converted into a string and
concatenated with the other string.
Example:
07:52 AM
The String Type
Concatenating Strings and Numbers
Breaking a Long String
Example:
07:52 AM
The String Type
Getting Characters and Substrings by Index
You can get the character at a particular index within a string by invoking the charAt() accessor method. The
index of the first character is 0, while the index of the last character is length()-1.
Example:
The following code gets the character at index 9 in a string: String today = "Niagara. O roar again!";
System.out.println(today.charAt(9));
Indices begin at 0, so the character at index 9 is "O". The following figures shows the use of charAt method to
get a character at a particular index.
07:52 AM
The String Type
Getting Characters and Substrings by Index
07:52 AM
The String Type
Getting Characters and Substrings by Index
If you want to get more than one consecutive character from a string, you can use the substring()method.
The substring method has two versions.
Here is the syntax and description
String substring (int beginIndex, int endIndex)
Example
System.out.println (today.substring(11, 15));
07:52 AM
Constants
The value of a variable may change during the execution of a program, but a named constant or simply
constant represents permanent data that never changes.
Syntax of writing constant values in java.
OOP CH-2 07:52 AM
Constants
A constant must be declared and initialized in the same statement. The word final is a Java keyword for
declaring a constant.
Example:
OOP CH-2 07:52 AM
Boolean
A variable that holds a Boolean value is known as a Boolean variable. The boolean data type is used to
declare Boolean variables. A boolean variable can hold one of the two values: true and false.
Example:
The following statement assigns true to the variable lightsOn:
OOP CH-2 07:52 AM
Java Methods
• A method is a way to perform some task. Similarly, the method in Java is a collection of instructions that
performs a specific task.
• It provides the reusability of code. We can also easily modify code using methods. In this section, we will
learn what is a method in Java, types of methods, method declaration, and how to call a method in Java.
Java
Methods 07:52 AM
What is a method in Java?
• A method is a block of code or collection of statements or a set of code grouped together to perform a
certain task or operation. It is used to achieve the reusability of code.
• We write a method once and use it many times. We do not require to write code again and again. It also
provides the easy modification and readability of code, just by adding or removing a chunk of code.
• The method is executed only when we call or invoke it.
Java
Methods 07:52 AM
Method Declaration
The method declaration provides information about method attributes, such as
visibility, return-type, name, and arguments.
It has six components that are known as method header, as we have shown in the
following figure.
Java
Methods 07:52 AM
Method Declaration
Java
Methods 07:52 AM
Method Declaration
• Method Signature: Every method has a method signature. It is a part of the method declaration. It includes
the method name and parameter list.
• Access Specifier: Access specifier or modifier is the access type of the method. It specifies the visibility of
the method. Java provides four types of access specifier:
Public: The method is accessible by all classes when we use public specifier in our application.
Private: the method is accessible only in the classes in which it is defined.
Protected: the method is accessible within the same package or subclasses in a different package.
Default: When we do not use any access specifier in the method declaration, Java uses default access
specifier by default. It is visible only from the same package only.
Java
Methods 07:52 AM
Method Declaration
• Return Type: Return type is a data type that the method returns. It may have a primitive data type, object,
collection, void, etc. If the method does not return anything, we use void keyword.
• Method Name: It is a unique name that is used to define the name of a method. It must be corresponding to
the functionality of the method. Suppose, if we are creating a method for subtraction of two numbers, the
method name must be subtraction(). A method is invoked by its name.
• Parameter List: It is the list of parameters separated by a comma and enclosed in the pair of parentheses. It
contains the data type and variable name. If the method has no parameter, left the parentheses blank.
• Method Body: It is a part of the method declaration. It contains all the actions to be performed. It is enclosed
within the pair of curly braces.
Java
Methods 07:52 AM
Naming a Method
• While defining a method, remember that the method name must be a verb and start
with a lowercase letter. If the method name has more than two words, the first name
must be a verb followed by adjective or noun. In the multi-word method name, the first
letter of each word must be in uppercase except the first word.
• For example:
Single-word method name: sum(), area()
Multi-word method name: areaOfCircle(), stringComparision()
• It is also possible that a method has the same name as another method name in the
same class, it is known as method overloading.
Java
Methods 07:52 AM
Types of Method
• There are two types of methods in Java:
Predefined Method
User-defined Method
Java
Methods 07:52 AM
Predefined Method
• In Java, predefined methods are the method that is already defined in the Java class
libraries is known as predefined methods. It is also known as the standard library
method or built-in method. We can directly use these methods just by calling them
in the program at any point. Some pre-defined methods are length(), equals(),
compareTo(), sqrt(), etc. When we call any of the predefined methods in our
program, a series of codes related to the corresponding method runs in the background
that is already stored in the library.
• Each and every predefined method is defined inside a class. Such as print() method is
defined in the java.io.PrintStream class. It prints the statement that we write inside
the method. For example, print("Java"), it prints Java on the console.
Java
Methods 07:52 AM
Predefined Method
• Example:
Java
Methods 07:52 AM
Predefined Method
• In the above example, we have used three predefined methods main(),
print(), and max(). We have used these methods directly without declaration because
they are predefined. The print() method is a method of PrintStream class that prints
the result on the console. The max() method is a method of the Math class that returns
the greater of two numbers.
Java
Methods 07:52 AM
User-defined Method
• The method written by the user or programmer is known as a user-defined method.
These methods are modified according to the requirement.
• Example:
Java
Methods 07:52 AM
User-defined Method
• We have defined the above method named findevenodd(). It has a parameter num of
type int. The method does not return any value that's why we have used void. The
method body contains the steps to check the number is even or odd. If the number is
even, it prints the number is even, else prints the number is odd.
Java
Methods 07:52 AM
User-defined Method
How to Call or Invoke a User-defined Method
Once we have defined a method, it should be called. When we call or invoke a user-
defined method, the program control transfer to the called method.
Java
Methods 07:52 AM
User-defined Method
How to Call or Invoke a User-defined Method
Java
Methods 07:52 AM
User-defined Method
How to Call or Invoke a User-defined Method
In the above code snippet, as soon as the compiler reaches at
line findEvenOdd(num), the control transfer to the method and gives the output
accordingly.
Let's combine both snippets of codes in a single program and execute it.
• Addition.java
Java
Methods 07:52 AM
Static Method
• A method that has static keyword is known as static method. In other words, a
method that belongs to a class rather than an instance of a class is known as a
static method.
• We can also create a static method by using the keyword static before the method
name.
• The main advantage of a static method is that we can call it without creating an object.
It can access static data members and also change the value of it. It is used to create
an instance method. It is invoked by using the class name. The best example of a static
method is the main() method.
Java
Methods 07:52 AM
Static Method
• Example of static method
Java
Methods 07:52 AM
Instance Method
• The method of the class is known as an instance method. It is a non-static method
defined in the class. Before calling or invoking the instance method, it is necessary to
create an object of its class. Let's see an example of an instance method.
• InstanceMethodExample.java
Java
Methods 07:52 AM