Chapter 2
Chapter 2
CHAPTER - 2
Can contain letters, digits, underscores (_) and dollar signs ($)
Should begin with a letter, an underscore (_) or a dollar sign ($).
Should not contain special characters (!,@,#,
%,^,&,*,>,?,/).
Should not contain space.
Are case sensitive, meaning that myVar and myvar are different
identifiers.
Java –Identifier naming rules
Java keywords or reserved words are words that have a special meaning or function in the Java
programming language. They cannot be used as identifiers for variables, methods, classes or any other
elements.
Java –Identifier example
Variables are names given to memory locations that store data values
during program execution.
Variables have a data type that specifies the type and size of the value
they can hold.
Variables can be declared using the syntax:
dataType variableName = value;
3. Local variables
Declared within a method or block of code.
They are only accessible within the method or block in which they
are declared.
Variables
4. Parameters
Used to pass information between methods or classes.
Can be declared in the method signature.
Can also be declared in a constructor.
Java – Data types
Fields that are declared but not initialized will be set to a reasonable
default by the compiler.
Local variables are slightly different; the compiler never assigns a
default value to an uninitialized local variable.
If you cannot initialize your local variable where it is declared, make
sure to assign it a value before you attempt to use it.
Accessing an uninitialized local variable will result in a compile-
time
error.
Java – Reference data types
Integer literal :
int decVal = 26; // The number 26, in decimal
Floating-Point Literals:
double d1 = 123.4;
double d2 = 1.234e2;
float f1 = 123.4f;
Java – Literal
\b (backspace),
\t (tab),
\n (line feed),
\f (form feed),
\r (carriage return),
\" (double quote),
\' (single quote), and
\\ (backslash).
Java – Escape Sequence characters
output
Java – Comments
2. Multi-line comments:
They start with /* and end with */ and comment multiple lines of code.
They can be used to explain complex code snippets or comment out
multiple lines of code at a time.
Java – Comments
3. Documentation comments:
Java documentation comments are special comments that are used to
generate HTML documentation for Java source code using the Javadoc
tool.
They are also known as doc comments or Javadoc comments. They start
with /** and end with */, and can have multiple lines.
They help to create documentation API using the javadoc tool.
They can use various tags and HTML elements to depict parameters,
headings, author names, etc.
Java – Comments
Java – Operators
Operators Precedence
postfix expr++ expr--
unary ++expr --expr +expr -expr ~ !
multiplicative */%
additive +-
shift << >> >>>
relational < > <= >= instanceof
equality == !=
bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
logical AND &&
logical OR ||
ternary ?:
assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=
Java – Operators
output
Java – Operators
Unary Operators
+ Unary plus operator; indicates positive value
- Unary minus operator; negates an expression
++ Increment operator; increments a value by 1
-- Decrement operator; decrements a value by 1
! Logical complement operator; inverts the value of a
boolean
Java – Operators
output
Java – Operators
output
Java – Operators
Logical Operators
&& Conditional-AND
|| Conditional-OR
! Negation -NOT
Conditional operator
?: Ternary (shorthand for if-then-else
statement)
Type Comparison Operator
Java – Operators
output
Java – Operators
output
Java – Operators
output
Java – Operators
output
Basic Java program structure
Documentation section
It is an optional section that contains basic information about the
program, such as author name, date, version, description, etc.
It uses comments to write the information.
Package declaration
It is an optional section that declares the package name in which
the
class is placed.
It helps to organize the classes into different modules and
directories.
It uses the keyword package to declare the package name..
Basic Java program structure
Import statements
They are used to import the classes or interfaces from other packages
that are needed in the program.
They use the keyword import to import the classes or interfaces.
Interface section
It is an optional section that declares one or more interfaces that are
implemented by the class.
An interface is a collection of abstract methods and constants that
define
a common behavior for a class.
Basic Java program structure
Class definition
It is a mandatory section that defines the class name, variables, methods
and constructors of the program.
A class is a blueprint for creating objects that have state and behavior. It
uses the keyword class to define a class.
Main method
It is a mandatory method that is the entry point of any Java program.
It contains the instructions for executing the program.
It uses the keyword public static void main(String[] args) to declare
the main method.
Basic Java program structure
Expressions, Statements, and Blocks
Expressions
An expression is a construct made up of variables, operators, and
method invocations, that evaluates to a single value.
The data type of the value returned by an expression depends on
the
elements used in the expression.
Example: of expression highlighted below
Expressions, Statements, and Blocks
Expressions
Expressions, Statements, and Blocks
Statements
Statements are roughly equivalent to sentences in natural languages.
A statement forms a complete unit of execution.
The following types of expressions can be made into a statement by
terminating the expression with a semicolon (;).
Assignment expressions
Any use of ++ or --
Method invocations
Object creation expressions
Expressions, Statements, and Blocks
Statements
Such statements are called expression statements. Here are some
examples of expression statements.
Expressions, Statements, and Blocks
Statements
In addition to expression statements, there are two other kinds of
statements: declaration statements and control flow statements.
A declaration statement declares a variable.
// declaration statement
double aValue = 8933.234;
Control flow statements regulate the order in which statements get
executed.
Expressions, Statements, and Blocks
Block
A block is a group of zero or more statements between balanced braces
and can be used anywhere a single statement is allowed.
Control flow structures
Loops are used to repeatedly execute a block of code. There are three types
of loops in Java:
for loops: For loops allow you to iterate over a range of numbers or a
collection of objects.
while loops: While loops allow you to execute a block of code as long
as a condition is true.
do-while loops: Do-while loops are similar to while loops, but the
block
of code is executed at least once, even if the condition is false.
Control flow structures
Branching Statements are used to alter the flow of control in loops. There
are three types of branching statements in Java:
break statements: Break statements are used to exit a loop.
continue statements: Continue statements are used to skip the current
iteration of a loop and continue with the next iteration.
return : used to exit from a method, with or without value.
Control flow structures
output
Control flow structures
output
Control flow structures
Unlabeled Labeled
Control flow structures
Control flow structures
Unlabeled Labeled
Control flow structures
Control flow structures
Arrays Class
The Arrays class in the java.util package provides various methods for
manipulating arrays (such as sorting and searching).
Some of the methods in the Arrays class are:
Arrays.sort(array): Sorts the specified array into ascending order.
Arrays.binarySearch(array, key): Searches the specified array for the
specified value using the binary search algorithm.
Array
Arrays Class
Arrays.equals(array1, array2): Returns true if the two specified arrays
are equal to one another.
Arrays.fill(array, value): Assigns the specified value to each element
of
the specified array.
Arrays.asList(array): Returns a fixed-size list backed by the specified
array.
Classes and objects
For example, in real life, a car is an object that has attributes like
color, weight, model, etc. and methods like drive, brake, etc.
A class named Car can define these attributes and methods for all
car
objects.
Classes and objects
Declaring Classes
⁻ A class is defined using the keyword `class`, followed by the name of the
class and a pair of curly braces `{ }` that enclose the body of the class.
⁻ The name of the class should start with a capital letter and follow the
camel case convention (e.g. `MyClass`, `Student`, `BankAccount`).
⁻ The body of the class can contain fields (variables that store data) and
methods (functions that perform actions).
Classes and objects
Declaring Classes
The class body (the area between the braces) contains all the code that
provides for the life cycle of the objects created from the class:
constructors for initializing new objects,
declarations for the fields that provide the state of the class and its
objects, and
methods to implement the behavior of the class and its objects.
Classes and objects
Declaring Classes
Classes and objects
Example : for the car class created above the object can be created and the
fields and methods can be accessed as follows.
Classes and objects
Example
Classes and objects
Example (cont…)
Access modifiers
Access modifiers in Java are keywords that specify the visibility and
accessibility of classes, methods, and variables.
They are an important feature of object-oriented programming that
allows
you to control how your code is accessed by other classes and
methods.
There are four types of access modifiers in Java:
1. public: The public access modifier makes the class, method, or variable
accessible from anywhere in the program. It has the widest scope of
accessibility.
Access modifiers
Outside Package
Modifier Within Class Within Package Outside Package
by Subclass
private Yes No No No
A method can have parameters that are values passed to it, and a return
type that is the value it produces.
A method must be declared within a class, and it is called by its name
followed by parentheses ().
A method can be public, private, static, or other modifiers that affect its
access and behavior.
Methods
Example
output
Methods
Example
output
Method overloading
The compiler determines which method to invoke based on the number and type
of
arguments passed.
output
this keyword
To create an object of a class using a constructor, we use the new keyword followed by the class
name and parentheses. If the constructor has parameters, we pass the arguments inside the
parentheses. For example:
Constructor vs method
Example :
Classes and objects
model
data color mode - Camry
member color - White
brand brand - Toyota
Static members in Java are those members of a class that belong to the
class itself and not to any instance of the class.
Static members are declared with the static keyword before their names.
Static members can be fields, methods, blocks, or nested classes.
Static members
1. Static fields are variables that have only one copy shared among all
instances of the class.
They are also known as class variables.
Static fields are initialized when the class is loaded and can be accessed
directly using the class name without creating an object.
Static members
3. Static blocks are blocks of code that are executed only once when the
class is loaded.
They are used to initialize static fields or perform any other one-time
operations.
Static blocks are declared with the static keyword before the curly
braces { }.
Static members
4. Static nested classes are classes that are defined inside another class
with the static keyword.
They are also known as static inner classes.
Static nested classes can access only static members of the outer class
and do not have a reference to an instance of the outer class.
To create an object of a static nested class, we can use the outer class
name followed by a dot (.) and the nested class name.
Static members