0% found this document useful (0 votes)
13 views41 pages

Lec 1 Fundamentals Feb 23

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 41

MCS

CS212-Object Oriented
Programming
Lecture 1
Java Language Fundamentals
(Feb 2023)
Instructor: Lt Col Muhammad Imran Javaid
Email: imranjavaid@mcs.edu.pk

Military College of Signals , NUST


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, underscore (_) or dollar-sign ($).
• Java identifiers are case sensitive. For example, fileName is different from
FileName.
• Identifiers cannot be exactly the same spelling and case as keywords.

2
Data Types
• Adata type describes the nature of data that a variable or expression can
contain/represent
• Our computers use memory which is
• limited in size and
• ultimately consists of bits (binary values 0 and 1 )
• Therefore, all data that we can represent must be
• limited in size and
• ultimately be broken down to bits
• In Java, we can distinguish different sorts of data types:
• Boolean Types: represent a Boolean decision of true and false
boolean myBool = true;
• Integer Types: represent whole numbers, i.e., subsets of 6, int myNum = 5;
• Floating Point Types: represent fractional numbers float myFloatNum = 5.99f;
• Char Types: represent a character “a” char myLetter = 'D';
String myText = "Hello";
3 • String Types: represent a text e.g “hello”
Data Types
• In Java, we can process data of several basic primitive data types

4
Variables
• A variable is a container which has a specific data type and can store
exactly one value of that type
• Variables are declared with statements of the form [type] [variableName];
which creates a variable with name variableName and of type type .
• We can store a value in a variable by using statements of the form
[variableName] = [expression] , where variableName is the name of the
variable and expression must be an expression of the right type
• When a program is executed, variables exist in the RAM assigned to the
process. After the process has terminated, they disappear.

5
Numbers
• Numbers are always represented relative to a given base
• The least significant/important digit is always the right-most one whereas
the one with the highest value is on the left side
• We usually use numbers relative to base 10:
– 1234 means
• Binary numbers are relative to base 2 and written in the form of
0b... in Java
– 0b1234 is invalid, since only digits 0 and 1 can occur
– 0b10100 means,
• Hexadecimal numbers are relative to base 16 (using digits 0 . . . 9, a. . .f)
and written in form 0x... in Java
– 0x1234 means
– 0x10100 means

6
Assignment Operators
Operator Example Same As
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
&= x &= 3 x=x&3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3
7
Comparison Operators

Operator Name Example


== Equal to x == y

!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y

8
Logical Operators

Operator Name Description Example


&& Logical and Returns true if both statements x < 5 && x < 10
are true
|| Logical or Returns true if one of the x < 5 || x < 4
statements is true
! Logical not Reverse the result, returns false if !(x < 5 && x <
the result is true 10)

9
Ternary Operator

10
Expressions

• Integer arithmetic is exact, i.e. ((a − b) − a) + b = 0, but since we have only 8, 16, 32, or 64 bits, the range
of numbers we can represent is limited. Thus, if, e.g., a + b is outside of the range of numbers we can
11 represent, it will be “wrapped back in”, i.e., we get the wrong result
Strings
• A String variable contains a collection of characters surrounded by
double quotes e.g String txt = "Hello World";

String txt = "Hello World";

System.out.println(txt); // Outputs Hello World


System.out.println(txt.toUpperCase()); // Outputs HELLO WORLD
System.out.println(txt.toLowerCase()); // Outputs hello world

String txt = "Please locate where 'locate' occurs!"; // Find Character in String
System.out.println(txt.indexOf("locate")); // Outputs 7

String firstName = “Ahmad"; // Concatenation


String lastName = “Aariz";
System.out.println(firstName + " " + lastName); // Outputs Ahmad Aariz

12
Escape Sequences
• The backslash (\) escape character turns special characters into string
characters:
String txt = “We from “Pakistan” “; // ERROR
String txt = “We from \“Pakistan\” “; // Outputs We are from “Pakistan”

• Other Escape sequences


Code Result
\n New Line
\r Carriage Return
\t Tab
\b Backspace
\f Form Feed
13
Adding Number & Strings
• If you add two numbers, the result will be a number:
int x = 10;
int y = 20;
int z = x + y; // z will be 30 (an integer/number)

• If you add two strings, the result will be a string concatenation


String x = "10";
String y = "20";
String z = x + y; // z will be 1020 (a String)

• If you add a number and a string, the result will be a string


concatenation:
String x = "10";
int y = 20;
String z = x + y; // z will be 1020 (a String)
14
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.
15
Sample Program
/*
Comments Package in Java is same as namespace in C++.
It is used for logical grouping of named entities
*/

Package package SamplePackage;


/**
* Sample class for First Program
*/
Class public class SampleProgram {
/**
* Entry point for JVM
* @param args the command line arguments
*/
Entry Point public static void main(String[] args) {
// An output statement
Console Output System.out.println("Long Live Pakistan");
}
16
}
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");
}
17 }
Sample Program
/*
Package in Java is same as namespace in C++.
Comments
It is used for logical grouping of named entities
*/ • The Java comments are statements that are not
packageexecuted
SamplePackage;
by the compiler and interpreter.
/**
• The comments can be used to provide information
* Sample class for First Program
*/ or explanation about the variable, method, class
public or any statement.
class SampleProgram {
/**
• It can also be used to hide program code for
* specific
Entry point
time. for JVM
* @param args the command line arguments
• */There are three types of comments in Java.
public static
1. Single Linevoid
Comment // Single
main(String[] args) Line
{
2.//Multi
An output statement /* Multi Line */
Line Comment
3.System.out.println("Long
Documentation Comment /** LiveDocumentation
Pakistan"); */
}
18 }
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");
}
19 }
Sample Program
/*
Package in Java is same as namespace in C++.
Package
It is used for logical grouping of named entities
*/• Packages are used in Java in order to prevent naming
package SamplePackage;
conflicts, to control access, to make searching/locating and
/** usage of classes, interfaces and enumerations easier, etc.
*• Sample
A Package classcanfor First Program
be defined as a grouping of related types
*/ providing access protection and namespace management.
public class SampleProgram {
• Programmers can define their own packages to bundle
/**
group of related classes/interfaces, etc.
* Entry point for JVM
• The* @param
packageargs the command
statement should beline arguments
the first line in the
*/ file. There can be only one package statement in
source
public
each static
source and itmain(String[]
file,void args)
applies to all types { file.
in the
// An output
• If a package statementstatement
is not used, then the types will be
placed System.out.println("Long
in the current default package. Live Pakistan");
}
20 }
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");
}
21 }
Sample Program
/*
Class
Package in Java is same as namespace in C++.
• InIt is the
Java, used for islogical
class basic unitgrouping of named entities
of encapsulation.
*/
•package
Every Java application must have at least one class
SamplePackage;
/**definition that consists of class keyword followed by class
* name.
Sample class for First Program
• */The public keyword is an access modifier.
public class
• Access SampleProgram
modifiers {
(or access specifiers) are keywords in
/**
object-oriented languages that set the accessibility of
* Entrymethods,
classes, point for JVM members.
and other
* @param
• Access args facilitate
modifiers the command line arguments
the encapsulation of components.
• The*/class definition is enclosed within curly braces {}.
public static void main(String[] args) {
• The elements between the two braces are members of the
// An output statement
class.
System.out.println("Long Live Pakistan");
• In}Java all program activity occurs within a class.
22 }
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");
}
23 }
Sample Program
/*
Entry Point – main() method
Package in Java is same as namespace in C++.
• AllItJava
is applications
used for logical grouping
begin execution of named
by calling main()entities
method.
*/
• When a class member is made public, then it can be accessed
package SamplePackage;
by code outside the class. The main() must be declared as
/**
public, so that it can be called by code outside of its class.
* Sample class for First Program
•*/The keyword static allows main() to be called before an
objectclass
public of the class has been created.
SampleProgram { This is necessary because
main() is called by the JVM before any objects are made.
/**
• The * keyword void simply
Entry point tells the compiler that main() does
for JVM
not*return
@param
any args
value. the command line arguments
• The */String[] args declares a parameter args, which is an
public
array of objects type String.
staticof void main(String[]
It receivesargs) {
the command-line
// Anthat
arguments, output statement
are passed as strings when the program is
System.out.println("Long Live Pakistan");
executed.
}
24 }
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");
}
25 }
Sample Program
/*
Console Output – println()
Package in Java is same as namespace in C++.
• For Itsimple
is used for logical
stand-alone grouping of anamed
Java applications, typicalentities
way to
*/
write a line of output data is:
package SamplePackage;
/**System.out.println(data);
• * System
Sample isclass forclass
a built-in First Program
that provides access to the system.
• */The out an object/ instance of type PrintStream, which is
public class
a public static member of{the classoutput stream.
and SampleProgram
/**
• The println() is a member method of PrintStream class.
* Entry point for JVM
It prints the contents of the argument (passed during the
* @param args the command line arguments
call),
*/and terminates the line.
• The println()
public void main(String[]
staticmethod is overloaded forargs) { built-in
various
types. // An example
In our we passed String (literal) "Long
output statement
Live System.out.println("Long
Pakistan" as argument to this Live Pakistan");
method.
}
26 }
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
27
Java Variables
• Following are the types of variables in Java:
– Local Variables
– Class Variables (Static Variables)
– Instance Variables (Non-static Variables)

28
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

boolean false true 1

byte –128 127 1

char '\u0000' '\uffff' 2

short –32,768 32,767 2

int –2,147,483,648 2,147,483,647 4

long -9,223,372,036,854,775,808 9,223,372,036,854,775,807 8

float 3.4 x 10–38 3.4 x 1038 4

double 1.7 x 10–308 1.7 x 10308 8


29
Java Operator Precedence Table
Precedence Operator Type Associativity
() Parentheses
15 [] Array subscript Left to Right
· Member selection
++ Unary post-increment
14 Right to left
-- Unary post-decrement
++ Unary pre-increment
-- Unary pre-decrement
+ Unary plus
13 - Unary minus Right to left
! Unary logical negation
~ Unary bitwise complement
( type ) Unary type cast
* Multiplication
12 / Division Left to right
% Modulus
+ Addition
11 Left to right
- Subtraction
<< Bitwise left shift
10 >> Bitwise right shift with sign extension Left to right
30 >>> Bitwise right shift with zero extension
Java Operator Precedence Table
Precedence Operator Type Associativity
< Relational less than
<= Relational less than or equal
9 > Relational greater than Left to right
>= Relational greater than or equal
instanceof Type comparison (objects only)
== Relational is equal to
8 Left to right
!= Relational is not equal to
7 & Bitwise AND Left to right
6 ^ Bitwise exclusive OR Left to right
5 | Bitwise inclusive OR Left to right
4 && Logical AND Left to right
3 || Logical OR Left to right
2 ? : Ternary conditional Right to left
= Assignment
+= Addition assignment
-= Subtraction assignment
1 Right to left
*= Multiplication assignment
/= Division assignment
31 %= Modulus assignment
Java Console Input/Output
Output to Console
• We already know that we can create output using System.out.println(...)
• System.out is a PrintStream which allows us to write data to the console
• It has the methods System.out.print and System.out.println for all basic Java
types we had so far:
– System.out.print(a) prints the value of expression a
– System.out.println(a) prints the value of expression a and then starts a new line
– System.out.println() without argument just starts a new line

32
Java Console Input/Output
Output to File
• If a program writes output to the console, then this output can be written to a
file instead. // Java program to demonstrate redirection in System.out.println()
import java.io.*;

public class Filewriting


{
public static void main(String arr[]) throws FileNotFoundException
{ // out is instance of PrintStream
// Store current System.out before assigning a new value
PrintStream c = System.out;

// Creating a File object that represents the disk file.


PrintStream f = new PrintStream(new File(“MCS.txt"));

// Use stored value for output stream


System.setOut(c);
System.out.println(“MCS will be written on the console!");

// Assign o to output stream


System.setOut(f);
System.out.println(“NUST will be written to the text file");

}
33
}
Java Console Input/Output
Input
• System.in is an InputStream which allows us to write read single
characters from the console
• We can get this by wrapping System.in into a Scanner object scanner by
doing Scanner input = new Scanner(System.in);
• Well, we did not yet learn what an object is and what new does, so let us
ignore this aspect for now and focus just on reading data
– input.nextLine() reads a full line of text as a String
– input.nextInt() reads an int number (from text)
– input.nextDouble() reads a double number (from text)
– input.hasNext() check if there is something else to read
34 • But before using scanner , import it first import java.util.Scanner; // Import the Scanner class
Scanner Input
• Scanner input = new Scanner(System.in);
– boolean hasValue = input.nextBoolean();

– byte bin = input.nextByte();

– short age = input.nextShort();

– int count = input.nextInt();

– long factorial = input.nextLong();

– float price = input.nextFloat();

– double speed = input.nextDouble();


35
Variables
• Listing: A program allocating, initializing, and printing boolean variables

36
Comparison Operators

37
Expressions

38
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);
}
39 }
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);
}
40 }
Copyright Notice

The material in this presentation has been taken from textbooks,


reference books, research literature and various sources on
Internet; and compiled/edited for classroom teaching at MCS-NUST
without any infringement into the copyrights of the author(s). The
original authors retain their respective copyrights as per their
stated claims. Commercial use of the material contained herein in
full or in part through copying, publication and reproducing in any
form is strictly prohibited

41

You might also like