OOP_Chapter 02 Basic Programming in Java
OOP_Chapter 02 Basic Programming in Java
OOP IN JAVA 1
Basic Programming in Java
Learning Objectives: at the end of the class,
you should be able to:
Describe Structure of Programming in Java
OOP IN JAVA 2
Basics in Java Programming
Structure of Java Program
[Comments] [Namespaces] [Classes]
[Objects]
[Variables] [Methods]
Comment: is a piece of descriptive text which
explains some aspect of a program.
Namespace:- are named program regions used to
memory.
OOP IN JAVA 3
…Con
A method is a separate piece of code that can be
called by a main program or any other method to
perform some specific function.
Documentation Section Suggested
Optional
Package Statement
Optional
Import Statements
Optional
Interface Statements
OOP IN JAVA 5
…Con
Main Method Class
Since every Java stand-alone program requires a main
OOP IN JAVA 6
Simple Java Program
The simplest way to learn a new language is to write a
few simple example programs and execute them.
OOP IN JAVA 7
…Con
Class Declaration: the first line class. Hello declares a
class, which is an object constructor.
Class is keyword and declares a new class definition and Hello is
a java identifier that specifies the name of the class to be
defined.
Opening Brace “{”: every class definition in java begins
with an opening brace and ends with a closing brace “}”.
The main line: the third line public static void
main(String args[]) defines a method named as main.
Is the starting point for the interpreter to begin the
execution of the program.
A java program can have any number of classes but only
one of them must include the main method to initiate the
execution.
Java applets will not use the main method at all.
OOP IN JAVA 8
…Con
The "public static void" key words in the main function has
the following meanings
public – specifies that the method is accessible to all other
classes and to the interpreter
static – this keyword specifies that the method is one that
is associated with the entire class,
It is not associated with objects belonging to the class
void – specifies that the method does not return any value.
All parameters to a method are declared inside a pair of
parenthesis. Here, String args[ ] declares a parameter
named args, which contains array of objects of the class
type String.
The Output Line: The only executable statement in the
program is System.out.println(“ Hello World);
This is similar to cout<< “constructor of C++.”;
The println method is a member of the out object, which
is a static data member of System class.
OOP IN JAVA 9
Basic Elements of Java
The basic elements of Java are:
Keywords (Reserved Words) Identifiers
Literals Comments
Separator
Keywords
Keywords are predefined identifiers reserved by Java for
a specific purpose.
There are 60 reserved keywords currently defined in the
Java language.
These keywords cannot be used as names for a
used.
OOP IN JAVA 10
Keywords …. Con
Keywords or Reserved word must be lower case letter
but not Upper Case Letter
OOP IN JAVA 11
Keywords …. Con
Keywor Keys
d
boolean declares a boolean variable or return type [True/False
- 0/1]
byte declares a byte variable or return type
char declares a character variable or return type [Single
character]
double declares a double variable or return type
float declares a floating point variable or return type
short declares a short integer variable or return type
void declare that a method does not return a value
“$”.
Consist only of letters, the digits 0-9, or the underscore
symbol “_”
Cannot use Java keywords/reserved words like class,
OOP IN JAVA 16
Java Identifier…Con
Examples of legal identifiers: age, $salary, _value,
__1_value, AvgTemp ,a7 etc…
Examples of illegal identifiers: 123abc, -salary
,not/ok ,Yes! etc…
Which is Valid Identifiers and which is Invalid
Identifiers?
A. First Name B. int C.my*Name D. Total##
E. LastName F. Double G. salary H. my_best
OOP IN JAVA 17
Literals
Literals are tokens that do not change or are
constant.
The different types of literals in Java are:
Integer Literals: decimal(base 10),
hexadecimal(base 16), and octal(base 8).
Example: int x=5; //decimal
int x=0127; //octal
int x=0x3A; //hexadecimal or int x=OX5A;
Floating-Point Literals: represent decimals with
fractional parts. Example: float x=3.1415;
Boolean Literals: have only two values, true or
false (0/1). Example: boolean test=true;
OOP IN JAVA 18
Literals …Con
Character Literals: represent single Unicode
characters enclosed by single quotes.
A Unicode character is a 16-bit character set that
replaces the 8-bit ASCII character set.
Example: char ch=‘A’;
String Literals: represent multiple/sequence of
characters enclosed by double quotes.
Example: String str=“Hello World”;
OOP IN JAVA 19
Java Comments
Comments are notes written to a code for
documentation purposes.
Those text are not part of the program and
compiler ignores executing them.
They add clarity and code understandability.
Java supports three types of comments:
OOP IN JAVA 20
Java Comments…Con
C-Style: Multiline comments – Starts with /* and
ends with */ .Everything between /* and */ is ignored by
the compiler.
E.g. /*This is an example of
a C-style or multiline comments */
Documentation Comments: is used to produce an
HTML file that documents your program. The
documentation comment begins with a /** and ends
with a */.
E.g. /** This is documentation comment */.
OOP IN JAVA 21
Java Separator
Are symbols used to indicate where groups of code are
divided and arranged.
In Java, there are a few characters that are used as
separators.
Symbo Name Purpose
l
() Parent Used to contain lists of parameters in method
hesis definition and invocation.
Also used for defining precedence in
expressions, containing expressions in control
statements, and surrounding cast types.
{} Braces Used to contain the values of automatically
initialized arrays. Also used
to define a block of code, for classes, methods,
and local scopes.
[] Bracke Used to declare array types. Also used when
ts dereferencing array values.
OOP IN JAVA 22
;
Data Types, Variables, and Constants
Variables
A variable is a container which holds the value while
the java program is executed.
A variable is an identifier that denotes a storage
location used to store a data value.
A variable has a data type and a name.
The data type indicates the type of value that the variable
can hold. The variable name must follow rules for
identifiers.
Declaring Variables: To declare a variable is as
follows,
datatype name;
Ex: int x;
OOP IN JAVA 23
Data Types, Variables, and Constants…Con
Initializing Variables [At moment of variable
declaration]
int x = 5; // declaring AND assigning
char ch = ‘A’; //initializing character
Assigning values to Variables [After variable
declaration]
int x; // declaring a variable
x = 5; // assigning a value to a variable
Types of Variable
There are three types of variables in java:
local variable
instance variable
OOP IN JAVA 24
Types of Variable…Con
local variable: Variables defined inside methods,
constructors or blocks are called local variables.
The variable will be declared and initialized within the
method and the variable will be destroyed when the
method has completed.
Instance variables: Instance variables are variables
within a class but outside any method.
These variables are instantiated when the class is
loaded. Instance variables can be accessed from
inside any method, constructor or blocks of that
particular class.
Class variables: Class variables are variables
declared within a class, outside any method, with the
static keyword.
OOP IN JAVA 25
Types of Variable…Con
class variable{
int data=40;//instance variable
static int x=100;//static variable
void method(){
int y=90;//local variable
}
}//end of class
OOP IN JAVA 26
Basic Data Type
OOP IN JAVA 27
Basic Data Type…Con
OOP IN JAVA 28
Basic Data Type…Con
There are eight built-in (primitive) data types in the
Java language.
4 integer types (byte, short, int, long)
2 floating point types (float, double)
1 Boolean (boolean)
1 Character (char)
OOP IN JAVA 29
Basic Data Type…Con
Data Type Size Range
boolean 1 byte Take the values true and false
Summary of Javaonly
Data(0/1).
Types
byte 1 byte -2 to 2 -1
7 7
OOP IN JAVA 30
Constants
In Java, a variable declaration can begin with the final keyword. This
means that once an initial value is specified for the variable, that
value is never allowed to change.
Example:
final float pi=3.14;
final int max=100; //or
final int max;
max=100;
public class Area_Circle {
public static void main(String args[]) {
final float pi=3.14;
float area=0; //initialize area to 0
float rad=5;
area=pi*rad*rad; //computer area
System.out.println(“The Area of the Circle: ”+area);
}
}
OOP IN JAVA 31
Java Operators and operator precedence
Operator in java is a symbol that is used to perform
operations.
Are symbols that take one or more arguments (operands)
and operates on them to a produce a result.
Are used to in programs to manipulate data and
variables.
They usually form a part of mathematical or logical
expressions.
Expressions can be combinations of variables, primitives
and operators that result in a value.
There are 8 different groups of operators in Java:
Arithmetic operators, Relational operators, Logical
operators, Assignment operator, Increment/Decrement
operators, Conditional operators, Bitwise operators, and
Special operators
OOP IN JAVA 32
Assignment Operator (=)
The assignment operator is used for storing a value at
some memory location (typically denoted by a variable).
Var = 5 assigning a value to a variable using =.
OOP IN JAVA 33
Arithmetic Operators
Arithmetic operators are used in mathematical
expressions in the same way that they are used in
algebra.
Operator Name Use Description
+ Addition op1 + op2 Adds op1 and op2
- Subtraction op1 - op2 Subtracts op2 from op1
* Multiplication op1 * op2 Multiplies op1 by op2
/ Division op1 / op2 Divides op1 by op2
% Remainder op1 % op2 Computes the remainder of
dividing op1 by op2
OOP IN JAVA 34
Relational Operators
Relational operators compare two values
Produces a Boolean value (true or false) depending on
the relationship.
Java supports six relational operators:
Operator Name Description
x<y Less than True if x is less than y, otherwise false.
x>y Greater than True if x is greater than y, otherwise false.
Less than or True if x is less than or equal to y,
x <= y
equal to otherwise false.
Greater than or True if x is greater than or equal to y,
x >= y
equal to otherwise false.
x == y Equal True if x equals y, otherwise false.
x != y Not Equal True if x is not equal to y, otherwise false.
OOP IN JAVA 35
Logical Operators
Java provides three logical/conditional operators for
combining logical expressions.
Logical operators evaluate to True or False.
OOP IN JAVA 36
Conditional Operators
The character pair ?: is a ternary operator available in java
It is used to construct conditional expression of the form:
exp1 ? exp2: exp3;
where exp1, exp2 and exp3 are expressions.
The operator ?: works as follows:
exp1 is evaluated first. If it is no zero (true), then the
OOP IN JAVA 37
Increment & Decrement Operators
Operato Use Description
r
++ x++ Increments x by 1; evaluates to the
value of x before it was incremented
++ ++x Increments x by 1; evaluates to the
value of x after it was incremented
-- x-- Decrements x by 1; evaluates to the
value of x before it was decremented
-- --x Decrements x by 1; evaluates to the
value of x after it was decremented
OOP IN JAVA 38
Increment & Decrement Operators…Con
Example : let x =5
Operato Name Example
r
++ Auto Increment ++x + 10 // gives 16
(prefix)
++ Auto Increment x++ + 10 // gives 15
(postfix)
-- Auto Decrement --x + 10 // gives 14
(prefix)
-- Auto Decrement x-- + 10 // gives 15
(postfix)
OOP IN JAVA 39
Bitwise operators
One of the unique features of java compared to other
high-level languages is that it allows direct
manipulation of individual bits within a word
Bitwise operators are used to manipulate data at values
of bit level.
They are used for testing the bits, or shifting them to
the right or left.
They may not be applied to float or double data types.
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
~ One’s complement
<< Shift left
>> Shift right
>>> Shift right with zero fill
OOP IN JAVA 40
Special operators
Java supports some special operators of interest such
as instanceof operator and member selection
operator(.).
instanceof Operator: is an object reference operator
OOP IN JAVA 43
…Con
Escape Sequence Description
\t Inserts a tab in the text at this point.
\b Inserts a backspace in the text at this point.
\n Inserts a newline in the text at this point.
\r Inserts a carriage return in the text at this point.
\f Inserts a form feed in the text at this point.
\' Inserts a single quote character in the text at this
point.
\“ Inserts a double quote character in the text at this
point.
\\ Inserts a backslash character in the text at this point.
OOP IN JAVA 44
Characters Methods
isLetter(): Determines whether the specified char
value is a letter.
isDigit(): Determines whether the specified char value
is a digit.
isWhitespace(): Determines whether the specified
char value is white space.
isUpperCase(): Determines whether the specified char
value is uppercase.
isLowerCase(): Determines whether the specified char
value is lowercase.
toUpperCase(): Returns the uppercase form of the
specified char value.
OOP IN JAVA 45
…Con
toLowerCase(): Returns the lowercase form of the
specified char value.
toString(): Returns a String object representing the
specified character value that is, a one-character string.
Example :
Public class Test{
Public static void main(String [] args){
System.out.println(Character.isLetter(‘a’);
System.out.println(Character.isDigit(7);
System.out.println(Character.isLowerCase(‘a’);
System.out.println(Character.isUpperCase(‘a’);
}
}
OOP IN JAVA 46
Java String
Strings which are widely used in Java programming are
a sequence of characters.
In the Java programming language, strings are objects.
From a day-to-day programming standpoint, one of the
most important of Java’s data types is String.
String defines and supports character strings.
The String class has eleven constructors and more than
forty methods for examining individual characters in a
sequence, comparing strings, searching substrings,
obtaining substrings, and creating a copy of a string
with all the characters translated to uppercase or
lowercase.
OOP IN JAVA 47
…Strings Methods
Here is the list of methods supported by String class:
int length(): Returns the length of this string.
character array.
String toLowerCase(): Converts all of the characters in
this String to lower case using the rules of the default locale.
String toLowerCase(Locale locale): Converts all of the
itself returned.
OOP IN JAVA 48
…Strings Methods
String toUpperCase(): Converts all of the characters in
this String to upper case using the rules of the default
locale.
String toUpperCase(Locale locale): Converts all of the
characters in this String to upper case using the rules of
the given Locale.
The trim(); method removes white spaces at the
beginning and end of a string.
Syntax: public String trim( );
Ex: System.out.println(“ wel-come ”.trim()); //prints wel-
come
The replace(); method replaces all appearances of a given
character with another character.
Syntax: public String replace( ‘ch1’, ’ch2’);
Ex: String str1=“Hello”;
System.out.println(str1.replace(‘l’, ‘m’)); // prints Hemmo
OOP IN JAVA 49
…Con
comparetTo(); Compares two strings lexicographically.
The result is a negative integer if the first String is less
OOP IN JAVA 50
…Con
The substring(); method creates a substring starting
from the specified index (nth character) until the end of
the string or until the specified end index.
Syntax : public String substring(int beginIndex);
public String substring(int beginIndex, int endIndex);
Ex: "smiles".substring(2); //returns "iles“
"smiles".substring(1, 5); //returns "miles”
The startsWith(); Tests if this string starts with the
specified prefix.
Syntax: public boolean startsWith(String prefix);
Ex: “Figure”.startsWith(“Fig”); // returns true
OOP IN JAVA 51
…Con
The indexOf(); method returns the position of the first
occurrence of a character in a string either starting
from the beginning of the string or starting from a
specific position.
public int indexOf(String str); - Returns the index of the
first occurrence of the specified substring within this
string.
public int indexOf(char ch, int n); - Returns the index of
the first occurrence of the character within this string
starting from the nth position.
OOP IN JAVA 52
…Con
Ex: String str = “How was your day today?”;
str.indexOf(‘t’); // prints 17
str.indexOf(‘y’, 17); // prints 21
str.indexOf(“was”); // Prints 4
str.indexOf("day",10)); //Prints 13
valueOf(); creates a string object if the parameter or
converts the parameter value to string representation
if the parameter is a variable.
Syntax: public String valueOf(variable);
public String valueOf(variable);
Ex: char x[]={'H','e', 'l', 'l','o'};
System.out.println(String.valueOf(x));//prints Hello
System.out.println(String.valueOf(48.958));//prints
48.958
OOP IN JAVA 53
Java Statements & Blocks
A statement is one or more line of code terminated by
semicolon (;)
Example: int x=5;
System.out.println(“Hello World”);
A block is one or more statements bounded by an opening &
closing curly braces that groups the statements as one unit.
Example:
public class Block{
public static void main(String args[]) {
int x=5;
int y=10;
char ch=‘Z’;
System.out.println(“Hello ”);
System.out.println(“World”); //Java Block of Code
System.out.println(“x=”+x);
System.out.println(“y=”+y);
System.out.println(“ch=”+ch);
}
}
OOP IN JAVA 54
Simple Type Conversion/Casting
Type casting enables you to convert the value of one
data from one type to another type
E.g. (int) 3.14; // converts 3.14 to an int to give 3
(long) 3.14; // converts 3.14 to a long to give 3
(double) 2; // converts 2 to a double to give 2.0
(char) 122; // converts 122 to a char whose code is 122 (z)
(short) 3.14; // gives 3 as a short
public class TypeCasting {
public static void main(String[] args) {
float x=3.14;
int ascii = 65;
System.out.println(“Demonstration of Simple Type
Casting");
System.out.println((int) x); //3
System.out.println((long) x); //3
System.out.println((double) x); //3.0
System.out.println((short) x); //3
System.out.println((char) ascii); //A
}} OOP IN JAVA 55
I/O Statements of Java [Scanner & BufferReader]
OOP IN JAVA 57
Illustration of Java I/O Statements
import java.util.Scanner;
public class JavaIO {
public static void main( String args[] ) { // main method begins
program execution
String studID;
double gpa;
Scanner input = new Scanner( System.in ); /*Create Scanner to
obtain input from command window */
System.out.println( "Enter Student ID: "); // prompt user to enter
ID
studID=input.nextLine(); // obtain user input from keyboard
System.out.println( "Enter GPA: "); // prompt
gpa=input.nextDouble(); // obtain user input
System.out.println("Student ID: "+studID); // Displaying Student ID
to Console System.out.println("Student GPA: "+gpa);
// Displaying GPA to Console Screen
}
}
OOP IN JAVA 58
Illustration of System.out.println() & System.out.print()
OOP IN JAVA 59
Demonstration of The 4 Arithmetic Operations in Java
import java.util.Scanner; System.out.println(“The Sum
Public classIO { x+y= ”+sum);
Public static void main(String[] System.out.println(“The
args) { Difference x-y= ”+dif);
int x, y, sum, dif, pro, quo; System.out.println(“The Product
Scanner input=new Scanner x*y= ”+pro);
(System.in); //create scanner System.out.println(“The
object input to get input from Quotient x/y= ”+quo);
user } //end of main
System.out.println(“Enter any 2 } //end of class IO
integers: ”);
x=input.nextInt();
y=input.nextInt();
sum=x+y;
dif=x-y;
pro=x*y;
Quo=(double) x/y;
OOP IN JAVA 60
End of Chapter Two!!!
THANK YOU!!!
See You in Next Class
!
OOP IN JAVA 61