0% found this document useful (0 votes)
27 views42 pages

Lecture Notes 3 4

Uploaded by

nauman khan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views42 pages

Lecture Notes 3 4

Uploaded by

nauman khan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 42

Object Oriented Programming

(CSC241 )

FUNDAMENTAL
DATA TYPES

COMSATS University Islamabad, Abbottabad


Campus
AGENDA

 Basic Structure of Program


 Primitive Data Types
 Variable declaration
 Arithmetical Operations
 Expressions
 Assignment statement
 Increment and Decrement operators
 Short hand operators
 The Math Class
 Math Functions Example
 Casting
BASIC STRUCTURE OF JAVA
PROGRAM
public class MyFirstJavaClass
{
public static void main(String[] arg)
{
System.out.println(“Hello World!!!!");
}
}
 The name of class and file must be same.
PARAMETERS USED IN FIRST JAVA
PROGRAM
 class keyword is used to declare a class in Java.
 public keyword is an access modifier that represents visibility. It
means it is visible to all.
 static is a keyword. If we declare any method as static, it is known
as the static method. The core advantage of the static method is
that there is no need to create an object to invoke the static
method. The main() method is executed by the JVM, so it doesn't
require creating an object to invoke the main() method. So, it
saves memory.
 void is the return type of the method. It means it doesn't return
any value.
CONTINUED…

 main represents the starting point of the program.


 String[] args or String args[] is used for
command line argument. We will discuss it in coming section.
 System.out.println() is used to print statement. Here, System is
a class, out is an object of the PrintStream class, println() is a
method of the PrintStream class. We will discuss the internal
working of System.out.println() statement in the coming section.
PRIMITIVE DATA TYPES
Java has eight primitive data types as described
below.
Type Size/Format Range
byte 8-bit -128 to 127
short 16-bit -32,768 to 32,767
int 32-bit about –2 billion to 2billion
long 64-bit about –10E18 to +10E18
float 32-bit -3.4E38 to +3.4E38
double 64-bit 1.7E308 to 1.7E308
char 16-bit A single character
boolean true or false true or false
FORMAT SPECIFIERS

 d: decimal integer [byte, short, int, long]


 f : floating-point number [float, double]
 c : characterCapital C will uppercase the letter
 s : StringCapital S will uppercase all the letters in the string
 b: To format boolean values, we use the %b format.
VARIABLE DECLARATION

You can declare a variable to hold a data value of any of the primitive types.
int counter;
int numStudents = 583;
long longValue;
long numberOfAtoms = 1237890L;
float gpa;
float batchAverage = 0.406F;
double e;
double pi = 0.314;
char gender;
char grade = ‘B’;
boolean safe;
boolean isEmpty = true;
VARIABLE DECLARATION (CONT.)

public class Example1


{
public static void main ( String[] args )
{
int payAmount = 123;
System.out.println("The variable contains: " +
payAmount );
}
}
OUTPUT FUNCTIONS

 System.out.println()
 System.out.print()
 System.out.printf()

 import java.lang;
 Java compiler imports java.lang package internally by default.
FOLLOWING ARE THE IMPORTANT
CLASSES IN JAVA.LANG PACKAGE
1.Boolean: The Boolean class wraps a value of the primitive type boolean in an
object.
2.Byte: The Byte class wraps a value of primitive type byte in an object.
3.Character – Set 1, Set 2: The Character class wraps a value of the primitive
type char in an object.
4.Double: The Double class wraps a value of the primitive type double in an
object.
5.Enum: This is the common base class of all Java language enumeration types.
6.Float: The Float class wraps a value of primitive type float in an object.
7.Integer :The Integer class wraps a value of the primitive type int in an object.
8.Long: The Long class wraps a value of the primitive type long in an object.
CONTINUED…

9. Math : The class Math contains methods for performing basic numeric
operations such as the elementary exponential, logarithm, square root, and
trigonometric functions.
10. Object: Class Object is the root of the class hierarchy.
11. Short: The Short class wraps a value of primitive type short in an object.
12. String- Set1, Set2: The String class represents character strings.
13. StringBuffer: A thread-safe, mutable sequence of characters.
14. StringBuilder: A mutable sequence of characters.
15. System: The System class contains several useful class fields and
methods.
16. Thread: A thread is a thread of execution in a program.
SYSTEM.IN

 import java.util.Scanner;
 Create Object of Scanner
 Call the function nextInt
IMPORT DECLARATION

 import declaration
 Helps the compiler locate a class that is used in this
program.
 Rich set of predefined classes that you can reuse rather
than “reinventing the wheel.”
 Classes are grouped into packages—named groups of
related classes—and are collectively referred to as the Java
class library, or the Java Application Programming Interface
(Java API).
 You use import declarations to identify the predefined
classes used in a Java program.

© Copyright 1992-2012 by Pearson Education, Inc. All


Rights Reserved.
SCANNER

 Variable declaration statement


Scanner input = new Scanner( System.in );

 This LHS declares a reference variable named input of


type Scanner.
 The RHS creates the object of scanner class.
 Assignment Operator(=) assign the reference of object
to input variable.
 The Scanner object is associated with standard input
device (System.in).
 System.in is the static variable of InputStream class.
JVM MEMORY
Purpose: Stores all Java objects or class
instances.
Shared Area: Accessible by all threads in
the application.
Garbage Collection:
HEAP MEMORY Automatically manages memory.
Reclaims space from unreferenced objects.
Prevents memory leaks and optimizes
usage.
Thread-Specific: Each thread has its own
stack for storing:
Method call information
Local variables
Intermediate results
STACK LIFO Structure: Operates on a Last In,
MEMORY First Out principle; the most recent method
called is the first to exit.
The default value for the stack size
depends on the JVM and the operating
system but is typically somewhere between
256 KB to 1 MB per thread.
• Bytecode: The compiled version of
your Java classes, which the JVM
executes.
• Class Metadata: Information about
METHOD the class, such as its name,
superclass, interfaces, method names,
AREA and field names.
• Static Variables: Variables that
belong to the class rather than any
instance, maintaining their state
across all instances.
PROGRAM Each thread has its own PC register.
Tracks the address of the currently
COUNTER (PC) executing instruction.
Enables correct resumption of execution
 Native Stack:
• Used for Java applications calling native
methods (e.g., C/C++).
• A native method is a method in a Java
program that is implemented in a
programming language other than Java,
NATIVE typically in C, C++, or another language.
METHOD • Contains stack frames for native calls.
STACK  JNI (Java Native Interface):
• Facilitates interaction between Java code
and native applications/libraries.
• Enables execution of non-Java code within
Java applications.
ARITHMETIC OPERATORS

Operator Use Description


+ op1 + op2 Adds op1 and op2
- op1 - op2 Subtracts op2 from op1
* op1 * op2 Multiplies op1 by op2
/ op1 / op2 Divides op1 by op2
% op1 % op2 Computes the remainder of dividing
op1 by op2
CONTINUED…

public class Example2


{
public static void main ( String[] args )
{
int hoursWorked = 40;
double payRate = 10.0;
System.out.println("Hours Worked: " + hoursWorked );
System.out.println("pay Amount : "+ (hoursWorked*payRate));
}
}
ARITHMETIC OPERATION

Modes of operation :
If operand1 and operand2 are of same data type, then the
resultant value of the operation will be of that same data type.

If operand1 and operand2 are of different data type like real and
integer, then the resultant value of the operation will be of real
data type.
Operand1 Operand2 Result
e.g. 1/2 gives 0 Real Real Real
1.0/2 gives 0.5 Whole Whole Whole
1.0/2.0 gives 0.5 Whole Real Real
Real Whole Real
ARITHMETIC EXPRESSIONS

Definition: An expression is a sequence of variables, constants, operators, and method


calls (constructed according to the syntax of the language) that evaluates to a single
value.
In Java, Arithmetic expressions are evaluated very similar to the way they are evaluated
in algebra.
Operator Meaning Precedence
- unary minus highest
+ unary plus highest
* multiplication middle
/ division middle
% remainder middle
+ addition low
- subtraction low
ASSOCIATIVITY OF OPERATORS

 In Java, all binary operators except for the assignment operators


are evaluated in left to right order.

2 * 7 * 3 4 - 2 + 5
----- -----
14 * 3 2 + 5
------- -------
42 7
ASSIGNMENT STATEMENT

variable = expression;
 The value of constants / variables / expression in the right side of the =
operator, is assigned to the variable in the left side of the = operator.
 Examples:
a = 5;
b = a;
c = a + b;
The left hand side of the = operator must be a variable.
 It cannot be a constant or an expression.
 Example of an invalid assignment statement :
a + b = c ;
ASSIGNMENT STATEMENT (CONT.)
 Java allows multiple assignment.
int width = 100, height = 45;
 By default, Java takes whole numbers to be of type int and real
numbers to be of type double. However, we can append a letter at
the end of a number to indicate its type.
 Upper and lower case letters can be used for ‘float’ (F or f), ‘double’ (D or
d), and ‘long’ (l or L, but we should prefer L):
float maxGrade = 100f; // now holds ‘100.0’
double temp = 583d; // holds double precision
float temp = 5.5; // ERROR!
// Java treats 5.5 as a double
long x = 583l; // holds 583, but looks like 5,381
long y = 583L; // This looks much better!
INCREMENT OR DECREMENT
OPERATORS
Increment/decrement operations (count = count +1) are very common in
programming. Java provides operators that make these operations shorter.
Operator Use Description
++ op++ Increments op by 1;
++ ++op Increments op by 1;
-- op-- Decrements op by 1;
-- --op Decrements op by 1;
Examples :
1. What is the value of j and i after executing the following code?
i = 1;
j = 5;
j = ++i;
INCREMENT OR DECREMENT
OPERATORS (CONT.)
2. What is the value of j and i after executing the following code?
i = 10;
j = 50;
j = i--;

3. What is the value of j and i after executing the following code?


i = 5;
j = 10;
i++;
++j;
SHORTHAND OPERATORS

Java also provides a number of operators that can be used as a


short-cut for performing arithmetic operations on a variable and
assigning the result to the same variable.
Operator Short-Form Equivalent to
+= op1 += op2 op1 = op1 + op2
-= op1 -= op2 op1 = op1 - op2
*= op1 *= op2 op1 = op1 * op2
/= op1 /= op2 op1 = op1 / op2
%= op1 %= op2 op1 = op1 % op2
Example :
Instead of writing a = a + 5; We can write a += 5;
COMMENTS IN JAVA

 Comments
// Fig. 2.1: Welcome1.java
 // indicates that the line is a comment.
 Used to document programs and improve their readability.
 Compiler ignores comments.
 A comment that begins with // is an end-of-line comment—it
terminates at the end of the line on which it appears.
 Traditional comment, can be spread over several lines as in
/* This is a traditional comment. It
can be split over multiple lines */
 This type of comment begins with /* and ends with */.
 All text between the delimiters is ignored by the compiler.
CONTINUED…

 Javadoc comments
 Delimited by /** and */.
 All text between the Javadoc comment delimiters is ignored by the
compiler.
 Enable you to embed program documentation directly in your
programs.
 The javadoc utility program (Appendix M) reads Javadoc comments
and uses them to prepare your program’s documentation in HTML
format.

© Copyright 1992-2012 by Pearson Education, Inc. All


Rights Reserved.
© Copyright 1992-2012 by Pearson Education, Inc. All
Rights Reserved.
ESCAPE SEQUENCE

Escape sequence is two or more characters that often begin with


an escape character that tell the computer to perform some
action.
THE MATH CLASS

PI The best approximate value of PI


abs(a) Returns the absolute value of a, a can be double, float, int or
long.
cos(a) Returns the trigonometric cosine/sine/tangent of an angle given in
sin(a) radians
tan(a)
exp(a) Returns the exponential number e raised to the power of a
log(a) Returns the natural logarithm (base e) of a
max(a, b) Returns the greater/smaller of two values, a and b can double,
min(a, b) float, int or long
pow(a, b) Returns the first argument raised to the power of the second
random() Returns a random value in the range 0.0 and 1.0
MATH FUNCTIONS EXAMPLE

Public class Expressions


{
public static void main(String[]args)
{
double area, circumference;
int radius=3;
area = Math.PI * Math.pow(radius, 2);
circumference = 2 * Math.PI * radius;
System.out.println("Area = " + area);
System.out.println("Circum. =" + circumference);
}
}
 java.lang package is by default included in the project.
EXAMPLE

 The following example computes the roots of a quadratic equation, assuming


that the equation has real roots.
 It uses the formula:

public class QuadraticEquation


{
public static void main(String[] args)
{
double a = 1, b = -5, c=6;
double root1 = (-b + Math.sqrt(b*b - 4*a*c))/(2*a);
double root2 = (-b - Math.sqrt(b*b - 4*a*c))/(2*a);
System.out.println("The roots are: "+root1 + " ,"+root2);
}
}
CASTING

• We learnt earlier that the following division


5 / 2
results in 2

Because the / operator is operating between 2 integer type constants, the result
will be an integer.

To get 2.5 , we need to convert either one or both the operands to double . Then
the division will look like
5.0 / 2.0

But what if we have integer variables to divide each other, like a / b ?

For this, cast operator is used .

(double) a / (double) b
CASTING (CONT.)

• Conversion of primitives is accomplished by (1) assignment and/or


(2) explicit casting:

int total = 100;


float temp = total; //temp now holds 100.0

• When changing type that will result in a loss of precision, an explicit


‘cast’ is needed. This is done by placing the new type in
parenthesis:

float total = 100F;


int temp = total; // ERROR!
int start = (int) total;
DECISION MAKING: EQUALITY AND RELATIONAL
OPERATORS

 Condition
 An expression that can be true or false.

 if selection statement
 Allows a program to make a decision based on a condition’s value.

 Equality operators (== and !=)


 Relational operators (>, <, >= and <=)
 Both equality operators have the same level of precedence, which
is lower than that of the relational operators.
 The equality operators associate from left to right.
 The relational operators all have the same level of precedence and
also associate from left to right.
© Copyright 1992-2012 by Pearson Education, Inc. All
Rights Reserved.

You might also like