Object Oriented Programming: Java Fundamentals
Object Oriented Programming: Java Fundamentals
Lecture 02
Java Fundamentals
MCS
Java Program Structure
• Java inherits its syntax from C.
– Case sensitive
– Statements terminated by a semicolon
– Control statements (conditional statements & loops)
– Compound statements enclosed in braces ({})
• Java object model is adapted from C++.
• Its source file is officially called a compilation unit.
• The source file name should match the name of
main class. Furthermore, it should use the .java
filename extension.
• All code must reside inside a class.
• Like other object-oriented languages, Java has its
own class-library, known as JDK (Java Development Kit)
MCS
Sample Program
/*
Package in Java is same as namespace in C++.
It is used for logical grouping of named entities
*/
package SamplePackage;
/**
* Sample class for First Program
*/
public class SampleProgram {
/**
* Entry point for JVM
* @param args the command line arguments
*/
public static void main(String[] args) {
// An output statement
System.out.println("Long Live Pakistan");
}
}
MCS
Sample Program
/*
Package in Java is same as namespace in C++.
It is used for logical grouping of named entities
*/
package SamplePackage;
/**
* Sample class for First Program
*/
public class SampleProgram {
/**
* Entry point for JVM
* @param args the command line arguments
*/
public static void main(String[] args) {
// An output statement
System.out.println("Long Live Pakistan");
}
}
MCS
Sample Program
/*
Package in JavaComments
Comments
is same as namespace in C++.
•• The
The Java
Javais
It comments
comments
used for are statements
arelogical
statements that
that are
grouping are not
ofexecuted
not executed by
by the
named entitiesthe
compiler
compiler and
*/ and interpreter.
interpreter.
•• package
The
The comments can
can bebe used
SamplePackage;
comments used to to provide
provide information
information oror explanation
explanation
about
about the
/** the variable,
variable, method,
method, classclass or
or any
any statement.
statement.
•• ItIt*can
Sample
can also
also beclass
be used
used tofor
to hide
hideFirst
program
programProgram
code
code forfor specific
specific time.
time.
*/
•• There
There are
are three
three types
types ofof comments
comments in in Java.
Java.
public class SampleProgram {
1.
1. Single
Single Line Comment //
// Single
Single Line
/** Line Comment Line
2.
2. Multi
Multi Line
Line Comment
* Entry Comment
point for JVM /*
/* Multi
Multi Line
Line */ */
3.
3. Documentation
Documentation
* @param args Comment
Comment
the command line /**
/** Documentation
arguments
Documentation */
*/
*/
Implementation
Implementation comments
commentsare aremeant
meantforforcommenting
commentingout outcode
codeororfor
for
comments
commentspublic
about static
aboutthe void
theparticular
particular main(String[]
implementation.
implementation. Doc args) {are
Doccomments
comments aremeant
meanttoto
describe
describethe // An output
thespecification
specification of thestatement
ofthe code,
code,from
froman animplementation-free
implementation-free
perspective.
perspective.to be
beread
readbybydevelopers
developerswho
System.out.println("Long
to whomight not
notnecessarily
mightLive have
havethe
Pakistan");
necessarily the
source
sourcecode
} at
code athand.
hand.
}
MCS
Sample Program
/*
Package in Java is same as namespace in C++.
It is used for logical grouping of named entities
*/
package SamplePackage;
/**
* Sample class for First Program
*/
public class SampleProgram {
/**
* Entry point for JVM
* @param args the command line arguments
*/
public static void main(String[] args) {
// An output statement
System.out.println("Long Live Pakistan");
}
}
MCS
Sample Program
/*
Package
Package
Package in Java is same as namespace in C++.
•• It is used for logical grouping of named entities
Packages
Packages (optional)
(optional) areare used
used in in Java
Java in in order
order to to
*/
prevent
prevent naming
naming conflicts,
conflicts, to to control
control access,
access, to to make
make
package SamplePackage;
searching/locating and usage of classes, interfaces
/** searching/locating and usage of classes, interfaces
and
and enumerations
* Sample enumerations
class for First easier, etc.
easier,Program
etc.
*/•• A Package can
A Package can be be defined
defined as as aa grouping
grouping of of related
related
public types
types providing
providing
class access
access protection
SampleProgram protection
{ and
and namespace
namespace
management.
management.
/**
* Entry point for
•• Programmers JVM
Programmers can can define
define their
their own
own packages
packages to to bundle
bundle
*
group @param args the command line arguments
group of of related
related classes/interfaces,
classes/interfaces, etc. etc.
*/
•• The
The package
package statement
statement should
should be be the
the first
first line
line{inin the
the
public static void main(String[] args)
source
source // file. There
There can
file.output
An can be
be only
statementonly one
one package
package statement
statement
in
in each
each source
source file,
file, and
and itit applies
System.out.println("Long applies toto all
Liveall types
types in
in the
Pakistan"); the file.
file.
•• }IfIf aa package
package statement
statement is is not
not used,
used, then
then thethe types
types will
will
} be
be placed
placed in in the
the current
current default
default package.
package.
MCS
Import Statement
• If we want to use any class of a particular package, we
need to import that class
• The import statement represents the class stored in the
other package.
• It is written before the class declaration and after the
package statement.
• We use the import statement in two ways, either import a
specific class or import all classes of a particular
package. In a Java program, we can use multiple import
statements.
MCS
Sample Program
/*
Package in Java is same as namespace in C++.
It is used for logical grouping of named entities
*/
package SamplePackage;
/**
* Sample class for First Program
*/
public class SampleProgram {
/**
* Entry point for JVM
* @param args the command line arguments
*/
public static void main(String[] args) {
// An output statement
System.out.println("Long Live Pakistan");
}
}
MCS
Sample Program
/*
Class
Class
Package in Java is same as namespace in C++.
•• It
In is used class
In Java,
Java, the
for logical
the class is is basic
grouping
basic unit
unit of
of named entities
of encapsulation.
encapsulation.
*/
•• Every
Every Java
Java application
application mustmust have
have at at least
least one
one class
class
package SamplePackage;
/** definition
definition that
that consists
consists of class keyword
of class keyword followedfollowed by by
class
class name.
* Sample name.
class for First Program
*/•• The public keyword
The public keyword is is an
an access
access modifier.
modifier.
public •• Access
Access modifiers
class modifiers (or
SampleProgram(or access
access{ specifiers)
specifiers) areare keywords
keywords in in
/**object-oriented
object-oriented languages
languages that that set
set the
the accessibility
accessibility of
of
* classes, methods,
classes,point
Entry methods,forand
and
JVMother
other members.
members.
••* Access
Access modifiers
@param args the
modifiers facilitate
command
facilitate the
the encapsulation
line arguments
encapsulation of
of
*/components.
components.
•• public
The
The classstatic
class voidis
definition
definition ismain(String[]
enclosed
enclosed within args)
within curly {
curly braces
braces ({}).
({}).
The//
The An output
elements
elements between
between statement
the
the two
two braces
braces are are members
members of of
the System.out.println("Long Live Pakistan");
the class.
class.
•• }In
In Java
Java all
all program
program activity
activity occurs
occurs within
within aa class.
class.
}
MCS
Sample Program
/*
Package in Java is same as namespace in C++.
It is used for logical grouping of named entities
*/
package SamplePackage;
/**
* Sample class for First Program
*/
public class SampleProgram {
/**
* Entry point for JVM
* @param args the command line arguments
*/
public static void main(String[] args) {
// An output statement
System.out.println("Long Live Pakistan");
}
}
MCS
Sample Program
/*
Entry
Entry Point
Point –– main()
main() method
method
Package in Java is same as namespace in C++.
It is applications
•• All used for logical groupingcalling of named entities
All Java
Java applications begin begin execution
execution by main() method.
by calling main() method.
*/
•• When
When a a class
class member
member is is made public, then
made public, then itit can
can be be accessed
accessed
package SamplePackage;
by code outside the class. The main() must be declared as
/** by code outside the class. The main() must be declared as
public, so
public,
* Sample so that
that ititfor
class
can
can be be called
called
First
by
by code
Program code outside
outside of of its
its class.
class.
••*/The
The keyword static allows
keyword static main() to
allows main() to be
be called
called before
before anan
object
object
public of
of the
class the class
class has has been
SampleProgram been created.
created.
{ This
This is
is necessary
necessary becausebecause
/** isis called
main()
main() called by by the
the JVM
JVM before
before any any objects
objects areare made.
made.
•• The
The* keyword
keyword
Entry point void simply
void simply
for JVM tells
tells the
the compiler
compiler that main() does
that main() does
not
not*return
return
@param any value.
anyargs
value.the command line arguments
•• The
The*/String[]
String[] args args declares
declares aa parameter
parameter args, args, whichwhich isis an
an
array
array
publicof
of objects
objects
static of type
type String.
of void ItIt receives
main(String[]
String. receives the
the command-line
args) command-line
{
arguments,
// Anthat
arguments, that
outputare
are passed
passed
statementas
as strings
strings whenwhen the the program
program is is
executed.
executed.
System.out.println("Long Live Pakistan");
}
}
MCS
Sample Program
/*
Package in Java is same as namespace in C++.
It is used for logical grouping of named entities
*/
package SamplePackage;
/**
* Sample class for First Program
*/
public class SampleProgram {
/**
* Entry point for JVM
* @param args the command line arguments
*/
public static void main(String[] args) {
// An output statement
System.out.println("Long Live Pakistan");
}
}
MCS
Sample Program
/*
Console
Console Output
Output –– println()
println()
Package in Java is same as namespace in C++.
It is used
•• For for logical applications,
grouping of named entities
For simple
simple stand-alone
stand-alone Java
Java applications, aa typical
typical way
way to
to
*/
write
write aaSamplePackage;
line
line of
of output
output data
data is:
is:
package
/**System.out.println(data);
System.out.println(data);
••* System
Sample is
System aa built-in
isclass forclass
built-in class
First that
that provides
provides access
Program access to to the
the system.
system.
••*/The
The outout isis static/class
static/class field
field of System class.
of System class. ItIt is
is an
an object/
object/
public
instance class typeSampleProgram { which corresponds to
instance of of type PrintStream,
PrintStream, which corresponds to
/**
standard
standard outputoutput stream.
stream.
* Entry point for JVM
•• The
The println() is is aathe
member
member method
method of PrintStream
PrintStream class.
* println()
@param args command lineofarguments class.
ItIt prints
*/ the
prints the contents
contents of of the
the argument
argument (passed
(passed during
during thethe
call),
call), and
and terminates
public terminates
static the
void line.
themain(String[]
line. args) {
•• The
The println()
println()
// An output method
method is
is overloaded
statementoverloaded for for various
various built-in
built-in
types.
types. In In our
our example
example we we passed
System.out.println("Long passed StringLive (literal)
String (literal) "Long
Pakistan"); "Long
Live
Live} Pakistan" as
Pakistan" as argument
argument to to this
this method.
method.
}
MCS
Java Identifiers
• An identifier is a sequence of characters used
to name variables, methods, classes, interfaces,
enumerations and packages.
• Only alphabets, numeric digits, underscore (_)
and dollar-sign ($) characters are legal in an
identifier, where first character can only be
alphabet.
• Blank spaces cannot be used in variable names
• Java identifiers are case sensitive. For
example, fileName is different from FileName.
• Identifiers cannot be exactly the same spelling
and case as keywords.
MCS
Java Keywords
• Keywords are predefined reserved identifiers that
have special meanings.
• They cannot be used as identifiers in your program.
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
MCS
Java Variables
• Following are the types of variables in Java:
– Local Variables
– Class Variables (Static Variables)
– Instance Variables (Non-static Variables)
MCS
Primitive Data Types
• There are eight primitive data types supported by Java.
Primitive data types are predefined by the language and
named by a keyword.
Numerical Range
Keyword Bytes
Minimum Maximum
= Assignment
+= Addition assignment
-= Subtraction assignment
1 *= Right to left
Multiplication assignment
/= Division assignment
%= Modulus assignment
MCS
Scanner Input
• Scanner input = new Scanner(System.in);
– boolean hasValue =
input.nextBoolean();
– short age =
input.nextShort();
– float price =
input.nextFloat();
MCS
Quadratic Equation
import java.util.Scanner;
public class QuadraticEquation {
public static void main(String[] args) {
double a, b, c, root, x1, x2;
Scanner input = new Scanner(System.in);
System.out.print("Enter a: ");
a = input.nextDouble();
System.out.print("Enter b: ");
b = input.nextDouble();
System.out.print("Enter c: ");
c = input.nextDouble();
root = Math.sqrt(Math.abs(Math.pow(b, 2)
- 4 * a * c));
x1 = (-b + root) / (2 * a);
x2 = (-b - root) / (2 * a);
System.out.printf("X1 = %.2f\n", x1);
System.out.printf("X2 = %.2f\n", x2);
}
}
MCS
Quadratic Equation
import java.util.Scanner;
public class QuadraticEquation {
public static void main(String[] args) {
double a, b, c, root, x1, x2;
Scanner input = new Scanner(System.in);
System.out.print("Enter a: ");
a = input.nextDouble();
System.out.print("Enter b: ");
b = input.nextDouble();
System.out.print("Enter c: ");
c = input.nextDouble();
root = Math.sqrt(Math.abs(Math.pow(b, 2)
- 4 * a * c));
x1 = (-b + root) / (2 * a);
x2 = (-b - root) / (2 * a);
System.out.printf("X1 = %.2f\n", x1);
System.out.printf("X2 = %.2f\n", x2);
}
}