Java Introduction
Java Introduction
Programming Language
• It is different category of written symbols that instruct computer
hardware to perform specified operations required by the designer.
• Skills required to be a programmer:
• Programming Language Skill: knowing one or more programming
language to talk to the computer and instruct the machine to
perform a task.
• Problem Solving Skill: skills on how to solve real world problem
and represent the solution in understandable format.
• Algorithm Development: skill of coming up with sequence of
simple and human understandable set of instructions showing the
step of solving the problem. Those set of steps should not be
dependent on any programming language or machine.
1
Java language
• Java is related to C++, which is a direct descendant of C.
• Much of the character of Java is inherited from C and C+
+.
• From C, Java derives its syntax. Many of Java’s object-
oriented features were influenced by C++.
• In fact, several of Java’s defining characteristics come
from—or are responses to—its predecessors.
• the creation of Java was deeply rooted in the process of
refinement and adaptation that has been occurring in
computer programming languages for the past several
decades
2
Features of Java
• Simple: Learning and practicing java is easy because of resemblance
with c and C++.
4
Features of Java…
• Robust (Strong/ Powerful): Java programs will not crash because of
its exception handling and its memory management features.
• They are:
abstraction
encapsulation,
inheritance, and
polymorphism. 6
Abstraction
7
Encapsulation
8
Inheritance
• Without the use of hierarchies, each object would need to define all of its
characteristics explicitly.
• However, by use of inheritance, an object need only define those qualities that
make it unique within its class. It can inherit its general attributes from its
parent.
9
Polymorphism
• Polymorphism meaning many forms is a feature that allows one
interface to be used for a general class of actions.
12
Executing a Java Program…
13
Java editors
14
Naming Conventions
• These keywords, combined with the syntax of the operators and separators, form
the foundation of the Java language.
• The keywords const and goto are reserved but not used.
• In addition to the keywords, Java reserves the following: true, false, and null.
These are values defined by Java. You are not allowed to use these words for the
names of variables, classes, and so on.
17
The Java Keywords…
18
Data types
Java defines eight primitive types of data: byte, short, int, long, char,
float, double, and boolean. The primitive types are also commonly
referred to as simple types.
These can be put in four groups:
• Integers: This group includes byte, short, int, and long, which are for whole-
valued signed numbers.
• Floating-point numbers: This group includes float and double, which represent
numbers with fractional precision.
• Characters: This group includes char, which represents symbols in a character
set, like letters and numbers.
• Boolean:This group includes boolean, which is a special type for representing
true/false values.
20
Integer Data type
• Java defines four integer types: byte, short, int, and long. All of these
are signed, positive and negative values.
21
Variables
23
Arithmetic Operators
24
Increment and Decrement
25
Increment and Decrement…
• These operators are unique in that they can appear both in postfix
form, where they follow the operand, and prefix form, where they
precede the operand.
28
Assignment Operator
29
Dynamic Initialization
• Not only constants are used as initializers, but also Java allows variables to be initialized
dynamically, using any expression valid at the time the variable is declared.
package len;
import java.util.Scanner;
public class DaynInit {
public static void main(String args[])
{ Scanner input=new Scanner (System.in);
double a, b,c;
// c is dynamically initialized
System.out.print("Enter base of triangle\n");
a=input.nextInt();
System.out.print("Enter height of triangle\n"); b=input.nextInt();
c = Math.sqrt((a * a) + (b * b));
System.out.println("Hypotenuse is " + c);
}
}
30
The Scope and Lifetime of Variables
31
The Scope and Lifetime of Variables(cont’d…)
• In Java, the two major scopes are those defined by a class
and those defined by a method.
• The scope defined by a method begins with its opening curly
brace. As a general rule, variables declared inside a scope
are not visible to code that is defined outside that scope.
• when you declare a variable within a scope, you are
localizing that variable and protecting it from unauthorized
access and/or modification.
• the scope rules provide the foundation for encapsulation.
32
The Scope and Lifetime of Variables(cont’d…)
• Scopes can be nested.
• For example, each time you create a block of code,
you are creating a new, nested scope.
• the outer scope encloses the inner scope.
• This means that objects declared in the outer scope
will be visible to code within the inner scope.
• Objects declared within the inner scope will not be
visible outside it.
33
Example: effect of nested scopes
34
Control Statements
• Control statements are the statements which alter the flow of execution
and provide better control to the programmer on the flow of execution.
35
Decision statement
• Decision making structures have
one or more conditions to be
evaluated.
• Statement or statements that are
executed if the condition is
determined to be true, and
• optionally, other statements to be
executed if the condition is
determined to be false.
36
If statement
• An if statement consists of a Boolean expression followed by one or
more statements.
• Following is the syntax of an if statement −
38
Switch statements…
⁻ The value for a case must be the same data type as the variable in the switch
and it must be a constant.
39
Switch statements…
⁻ The default case can be used for performing a task when none
of the cases is true. No break is needed in the default case.
40
Switch Statement(cont’d…)
41
Loop statements
• There may be a situation when you need to execute a block of code
several number of times. In general, statements are executed
sequentially:
44
do...while loop
45
do...while loop
46
For loop
• A for loop is a repetition control structure that allows you to
efficiently write a loop that needs to be executed a specific number of
times.
• A for loop is useful when you know how many times a task is to be
repeated.
47
For loop…
• Here is the flow of control in a for loop −
• The initialization step is executed first, and only once. This step allows you to declare and
initialize any loop control variables and this step ends with a semi colon (;).
• Next, the Boolean expression is evaluated. If it is true, the body of the loop is executed. If it
is false, the body of the loop will not be executed and control jumps to the next statement
past the for loop.
• After the body of the for loop gets executed, the control jumps back up to the update
statement. This statement allows you to update any loop control variables. This statement
can be left blank with a semicolon at the end.
• The Boolean expression is now evaluated again. If it is true, the loop executes and the
process repeats (body of loop, then update step, then Boolean expression). After the Boolean
expression is false, the for loop terminates.
48
For loop…
49
Break and continue statement
• The break statement in Java programming language has the following
two usages −
⁻ When the break statement is encountered inside a loop, the loop is
immediately terminated and the program control resumes at the next
statement following the loop.
⁻ It can be used to terminate a case in the switch statement (covered in
the next chapter).
• The continue keyword can be used in any of the loop control structures.
It causes the loop to immediately jump to the next iteration of the loop.
⁻ In a for loop, the continue keyword causes control to immediately
jump to the update statement.
⁻ In a while loop or do/while loop, control immediately jumps to the
Boolean expression.
50
Defining Classes and Objects
• The most important thing to understand about a class is that it defines
a new data type.
• Once defined, this new type can be used to create objects of that type
• Because an object is an instance of a class, you will often see the two
words object and instance used interchangeably.
51
Class Definition(cont’d…)
• When you define a class, you declare its exact form and nature.
• You do this by specifying the data that it contains and the code that
operates on that data.
54
Declaring Objects
• when you create a class, you are creating a new data type.
• you can use this type to declare objects of that type.
• First, you must declare a variable of the class type. This variable
does not define an object. Instead, it is simply a variable that can
refer to an object.
55
Declaring Objects…
• Second, you must acquire an actual, physical copy of the object
and assign it to that variable.
57
Declaring Object(cont’d…)
• An object has a unique identity, state, and behavior.
• The state of an object (also known as its properties or attributes) is
represented by data fields with their current values.
• For example, A circle object has a data field radius, which is the
property that characterizes a circle.
• The behavior of an object (also known as its actions) is defined by
methods.
• To invoke a method on an object is to ask the object to perform an
action.
• For example, you may define a method named getArea() for circle
objects. A circle object may invoke getArea() to return its area.
58
Access modifier
• Private members can be accessed only from the inside of the class.
60
Method Declaration
• The method header specifies the modifiers, return value type, method
name, and parameters of the method.
• The return Type is the data type of the value the method returns.
• The parameter list refers to the type, order, and number of the
parameters of a method.
62
Method Declaration…
• The method name and the parameter list together constitute the method
signature.
• Calling method means using that method to perform the defined tasks
for that method.
63
Method Declaration…
64
Types of method
predefined methods are the method that is already defined in the Java class
libraries.
• 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(), 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.
User-defined Method
• The method written by the user or programmer is known as a user-
65
defined method. These methods are modified according to the requirement.
Passing Parameters
• The power of a method is its ability to work with parameters.
• When calling a method, you need to provide arguments, which must
be given in the same order as their respective parameters in the method
signature. This is known as parameter order association.
• For example, the following method prints a message n times:
66
Constructors
Inheritance Basics
• Acquiring the properties from one class to another class
• Producing new class from already existing class.
• Reusability of code is main advantage of inheritance
• To inherit a class, you simply incorporate the definition of one class
into another by using the extends keyword.
• The general form of a class declaration that inherits a superclass is
shown here:
68
Inheritance Basics(cont’d…)
• You can only specify one superclass for any subclass that you create.
• Java does not support the inheritance of multiple super classes into a
single subclass.
• You can create a hierarchy of inheritance in which a subclass
becomes a superclass of another subclass. However, no class can be a
superclass of itself.
• Although a subclass includes all of the members of its superclass,
it cannot access those members of the superclass that have been
declared as private.
• A class member that has been declared as private will remain private
to its class.
• It is not accessible by any code outside its class, including subclasses.
69
Using the super Keyword
• The second is used to access a member of the superclass that has been
hidden by a member of a subclass
71
Polymorphism
Overloading Methods
74
Method Overriding(cont’d…)
• Method overriding occurs only when the names and the type
signatures of the two methods are identical. If they are not,
then the two methods are simply overloaded.
76
Abstract class
78
Interfaces
• using interface, you can specify what a class must do, but not how it
does it.
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
//…
return-type method-nameN(parameter-list);
80
Defining an Interface(cont’d…)
• When it is declared as public, the interface can be used by any other code.
• In this case, the interface must be the only public interface declared in the
file, and the file must have the same name as the interface. name is the name
of the interface, and can be any valid identifier.
• The methods that are declared in interface have no bodies. They end with a
semicolon after the parameter list.
}
82
Implementing Interfaces
• Once an interface has been defined, one or more classes can implement
that interface.
• The general form of a class that includes the implements clause looks
like this:
class classname [implements interface [,interface…]] {
// class-body
83
Casting
• It is about converting one data type into another data type
• Type cast operator is used to convert one data type into
another data type.
• Data type represents the type of the data stored into a variable.
• There are two kinds of data types:
Primitive Data type: Primitive data type represents singular
values.
• e.g.: byte, short, int, long, float, double, char, boolean.
84
Constructors…
• The following are rules used to define the constructor.
• Constructor name must be the same as its class name
• A Constructor must have no explicit return type
• A Java constructor cannot be abstract, static, final, and
synchronized
86
Static Method
87
Final keyword
• The final keyword in java is used to restrict the user. The java
final keyword can be used in many context. Final can be:
Java final variable
• If you make any variable as final, you cannot change the value of
final variable(It will be constant).
Java final method
• If you make any method as final, you cannot override it.
Java final class
• If you make any class as final, you cannot extend it.
88
this Keyword
• As you know, it is illegal in Java
to declare two local variables
with the same name inside the
same or enclosing scopes.
• Interestingly, you can have local
variables, including formal
parameters to methods, which
overlap with the names of the
class’ instance variables.
• However, when a local variable
has the same name as an instance
variable, the local variable hides
the instance variable
89