0% found this document useful (0 votes)
3 views55 pages

2 Lecture2

Java

Uploaded by

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

2 Lecture2

Java

Uploaded by

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

Object-Oriented Programming

Lecture2:
• Data Types in Java
• Variables in Java
• Arrays
• Operators
• Control Statements
• Input and output
• Scanner and System class
• print(),println(), and printf() methods
Data Types in Java
• Definition: Specifies different sizes and values
for storing variables.
• Importance: Ensures efficient memory use
and type checks at compile time.
• Use: Declaring variables and managing data in
a program.
Primitive Data Types
Data type Range of values

byte -128 .. 127 (8 bits)


short -32,768 .. 32,767 (16 bits)
int -2,147,483,648 .. 2,147,483,647 (32 bits)
long -9,223,372,036,854,775,808 .. ... (64 bits)
float +/-10-38 to +/-10+38 and 0, about 6 digits precision
double +/-10-308 to +/-10+308 and 0, about 15 digits precision
char Unicode characters (generally 16 bits per char)
boolean True or false

Appendix A: Introduction to Java 4


Primitive data types are predefined by the Java language and are named by a
reserved keyword. They are the simplest forms of data types and are not objects.
They include:
• Primitive Data Types in Java
1. byte
• Description: The byte data type is an 8-bit signed two's complement
integer.
• Range: -128 to 127.
• Use: Useful for saving memory in large arrays where memory savings are
critical. Also used to handle raw binary data.
• Example:
• public class ByteExample {
• public static void main(String[] args) {
• byte b = 100;
• System.out.println("Value of byte b: " + b);
• }
• }
• Output:
• Value of byte b: 100
Cont..
2. short
• Description: The short data type is a 16-bit signed two's complement
integer.
• Range: -32,768 to 32,767.
• Use: Like byte, short can be used to save memory in large arrays.
• Example:
• public class ShortExample {
• public static void main(String[] args) {
• short s = 10000;
• System.out.println("Value of short s: " + s);
• }
• }
• Output:
• Value of short s: 10000
Cont…
• 3. int
• Description: The int data type is a 32-bit signed two's complement integer.
• Range: -2^31 to 2^31 - 1.
• Use: The default choice for integer values unless there is a specific reason to
use a smaller or larger integer type.
• Example:
• public class IntExample {
• public static void main(String[] args) {
• int i = 100000;
• System.out.println("Value of int i: " + i);
• }
• }
• Output:
• Value of int i: 100000
Cont…
• 4. long
• Description: The long data type is a 64-bit signed two's
complement integer.
• Range: -2^63 to 2^63 - 1.
• Use: When a wider range than int is needed.
• Example:
• public class LongExample {
• public static void main(String[] args) {
• long l = 10000000000L; // Note the 'L' at the end to indicate a
long literal
• System.out.println("Value of long l: " + l);
• }
• }
• Output:
• Value of long l: 10000000000
Cont…
• 5. float
• Description: The float data type is a single-precision 32-bit IEEE
754 floating point.
• Range: Approximately ±3.40282347E+38F (6-7 significant decimal
digits).
• Use: Used to save memory in large arrays of floating point
numbers. Should never be used for precise values, such as currency.
• Example:
• public class FloatExample {
• public static void main(String[] args) {
• float f = 10.5f; // Note the 'f' at the end to indicate a float literal
• System.out.println("Value of float f: " + f);
• }
• }
• Output:
• Value of float f: 10.5
Cont….
• 6. double
• • Description: The double data type is a double-precision 64-bit
IEEE 754 floating point.
• • Range: Approximately ±1.79769313486231570E+308 (15
significant decimal digits).
• • Use: The default choice for decimal values. Should never be
used for precise values, such as currency.
• Example:
• public class DoubleExample {
• public static void main(String[] args) {
• double d = 10.5;
• System.out.println("Value of double d: " + d);
• }
• }
• Output:
• Value of double d: 10.5
Cont….
• 7. char
• Description: The char data type is a single 16-bit Unicode
character.
• Range: '\u0000' (or 0) to '\uffff' (or 65,535 inclusive).
• Use: Used to store any character.
• Example:
• public class CharExample {
• public static void main(String[] args) {
• char c = 'A';
• System.out.println("Value of char c: " + c);
• }
• }
• Output:
• Value of char c: A
Cont…
• 8. boolean
• Description: The boolean data type has only two possible
values: true and false.
• Use: Used for simple flags that track true/false conditions.
• Example:
• public class BooleanExample {
• public static void main(String[] args) {
• boolean flag = true;
• System.out.println("Value of boolean flag: " + flag);
• }
• }
• Output:
• Value of boolean flag: true
Example - Data Types
• public class DataTypesDemo {
• public static void main(String[] args) { Output:
• int num = 10;
Integer: 10
• double price = 19.99; Double: 19.99
• char letter = 'A'; Character: A
Boolean: true
• boolean isJavaFun = true;
• System.out.println("Integer: " + num);
• System.out.println("Double: " + price);
• System.out.println("Character: " + letter);
• System.out.println("Boolean: " + isJavaFun);
• }
• }
Variables in Java
• Definition: Containers for storing data values.
• Importance: Fundamental for storing and
manipulating data.
• Use: Store information to be referenced and
manipulated in a program.
Example - Variables
• public class VariablesDemo {
• public static void main(String[] args) {
• int number = 100;
• String message = "Hello";
• System.out.println("Number: " + number);
• System.out.println("Message: " + message);
• } Output:
• }
Number: 100
Message: Hello
Arrays in Java
• Definition: Objects that store multiple values
of the same type, accessed with an index
number.
• Importance: Efficient storage and access to a
collection of data.
• Use: Store and manipulate a fixed number of
values of a single type.
Arrays
• In Java, an array is also an object
• The elements are indexes and are referenced
using the form arrayvar[subscript]

Appendix A: Introduction to Java 17


Example - Arrays
• public class ArraysDemo {
• public static void main(String[] args) { Explanation:
Declares and
• int[] numbers = {1, 2, 3, 4, 5};
initializes an array
• System.out.println("Array elements:"); of integers, iterates
• for (int i = 0; i < numbers.length; i++) { over the elements
• System.out.println(numbers[i]); and prints them.
• } Output:
Array elements:
• }
1
• } 2
3
4
5
Operators in Java
• Definition: Special symbols that perform
operations on operands and return a result.
• Importance: Essential for performing
arithmetic, logical, and comparison
operations.
• Use: Perform operations on variables and
values in expressions.
Operators
• Operators in Java are special symbols that perform operations on variables
and values. Java has a rich set of operators to manipulate variables. They can
be categorized into several types:
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
Cont…
• 1. Arithmetic Operators
• These operators are used to perform basic arithmetic operations.
• Addition (+)
• int a = 10;
• int b = 5;
• int sum = a + b;
• System.out.println("Sum: " + sum);
• // Output: Sum: 15
• Subtraction (-)
• int a = 10;
• int b = 5;
• int difference = a - b;
• System.out.println("Difference: " + difference);
• // Output: Difference: 5
Cont..
• Multiplication (*)
• int a = 10;
• int b = 5;
• int product = a * b;
• System.out.println("Product: " + product);
• // Output: Product: 50
• Division (/)
• int a = 10;
• int b = 5;
• int quotient = a / b;
• System.out.println("Quotient: " + quotient);
• // Output: Quotient: 2
• Modulus (remainder) (%)
• int a = 10;
• int b = 3;
• int remainder = a % b;
• System.out.println("Remainder: " + remainder);
• // Output: Remainder: 1
2. Relational Operators
• These operators are used to compare two values.
• Equal to (==)
• int a = 10;
• int b = 5;
• boolean result = (a == b);
• System.out.println("a == b: " + result);
• // Output: a == b: false
• Not equal to (!=)
• int a = 10;
• int b = 5;
• boolean result = (a != b);
• System.out.println("a != b: " + result);
• // Output: a != b: true
Cont…
• Greater than (>)
• int a = 10;
• int b = 5;
• boolean result = (a > b);
• System.out.println("a > b: " + result);
• // Output: a > b: true
• Less than (<)
• int a = 10;
• int b = 5;
• boolean result = (a < b);
• System.out.println("a < b: " + result);
• // Output: a < b: false
cont
• Greater than or equal to (>=)
• int a = 10;
• int b = 5;
• boolean result = (a >= b);
• System.out.println("a >= b: " + result);
• // Output: a >= b: true

• Less than or equal to (<=)


• int a = 10;
• int b = 5;
• boolean result = (a <= b);
• System.out.println("a <= b: " + result);
• // Output: a <= b: false
3. Logical Operators
• These operators are used to perform logical operations.
• Logical AND (&&)
• boolean a = true;
• boolean b = false;
• boolean result = (a && b);
• System.out.println("a && b: " + result);
• // Output: a && b: false
• Logical OR (||)
• boolean a = true;
• boolean b = false;
• boolean result = (a || b);
• System.out.println("a || b: " + result);
• // Output: a || b: true
Cont…
• Logical NOT (!)
• boolean a = true;
• boolean result = !a;
• System.out.println("!a: " + result);
• // Output: !a: false
4. Bitwise Operators
• 1. Bitwise Operators
• Bitwise operators in Java perform operations on individual bits of integer
types.
• AND (&): Performs a bitwise AND operation.
• OR (|): Performs a bitwise OR operation.
• XOR (^): Performs a bitwise exclusive OR operation.
• NOT (~): Performs a bitwise complement (inversion of bits).
Example:

public class BitwiseOperatorsExample {


public static void main(String[] args) {
int a = 5; // 0101 in binary
int b = 3; // 0011 in binary

// Bitwise AND
int andResult = a & b; // 0101 & 0011 = 0001
System.out.println("a & b = " + andResult); // Output: 1

// Bitwise OR
int orResult = a | b; // 0101 | 0011 = 0111
System.out.println("a | b = " + orResult); // Output: 7

// Bitwise XOR
int xorResult = a ^ b; // 0101 ^ 0011 = 0110
System.out.println("a ^ b = " + xorResult); // Output: 6

// Bitwise NOT
int notResult = ~a; // ~0101 = 1010 (in 2's complement, -6)
System.out.println("~a = " + notResult); // Output: -6
5. Assignment Operators
• Assignment operators are used to assign values to variables. The most
common assignment operator is =. There are also compound assignment
operators that combine a binary operation with assignment.
• Simple Assignment (=): Assigns the right-hand side value to the left-hand
side variable.
• Addition Assignment (+=): Adds the right-hand side value to the left-hand
side variable and assigns the result.
• Subtraction Assignment (-=): Subtracts the right-hand side value from
the left-hand side variable and assigns the result.
• Multiplication Assignment (*=): Multiplies the left-hand side variable by
the right-hand side value and assigns the result.
• Division Assignment (/=): Divides the left-hand side variable by the right-
hand side value and assigns the result.
• Modulus Assignment (%=): Computes the modulus of the left-hand side
variable by the right-hand side value and assigns the result.
• Example:
• public class AssignmentOperatorsExample {
• public static void main(String[] args) {
• int a = 10;

• // Simple Assignment
• int b = a;
• System.out.println("b = " + b); // Output: 10

• // Addition Assignment
• a += 5; // a = a + 5
• System.out.println("a += 5 -> a = " + a); // Output: 15

• // Subtraction Assignment
• a -= 3; // a = a - 3
• System.out.println("a -= 3 -> a = " + a); // Output: 12

• // Multiplication Assignment
• a *= 2; // a = a * 2
• System.out.println("a *= 2 -> a = " + a); // Output: 24

• // Division Assignment
• a /= 4; // a = a / 4
• System.out.println("a /= 4 -> a = " + a); // Output: 6

• // Modulus Assignment
• a %= 5; // a = a % 5
• System.out.println("a %= 5 -> a = " + a); // Output: 1
• }
• }
Control Statements in Java
• Definition: Control the flow of execution
based on conditions.
• Importance: Allow conditional execution and
repetitive tasks, making programs dynamic
and responsive.
• Use: Implement logic involving decision
making and repetitive tasks.
Cont…
• These statements can be classified into three categories:
1. Selection Statements (Conditional Statements)
2. Iteration Statements (Looping Statements)
3. Jump Statements
Cont…
1. Selection Statements
Selection statements allow the program to choose different paths of execution based on the
outcome of an expression or condition.
if Statement
The if statement evaluates a boolean expression and executes a block of code if the
expression is true.
int num = 10;
if (num > 5) {
System.out.println("Number is greater than 5");
}
if-else Statement
The if-else statement provides a secondary path of execution when an if clause
evaluates to false.
int num = 3;
if (num > 5) {
System.out.println("Number is greater than 5");
} else {
System.out.println("Number is not greater than 5");
}
One-way if Statements
if (radius >= 0) {
area = radius * radius * PI;
if (boolean-expression) { System.out.println("The area"
statement(s);
} + " for the circle of radius "
+ radius + " is " + area);
}

36
The Two-way if Statement
if (boolean-expression) {
statement(s)-for-the-true-case;
}
else {
statement(s)-for-the-false-case;
}

37
Cont..
• if-else-if Ladder
• This allows multiple conditions to be checked in sequence.
• int num = 10;
• if (num == 1) {
• System.out.println("Number is one");
• } else if (num == 10) {
• System.out.println("Number is ten");
• } else {
• System.out.println("Number is neither one nor ten");
• }
Multi-Way if-else Statements

39
Multiple Alternative if Statements

if (score >= 90.0) if (score >= 90.0)


System.out.print("A"); System.out.print("A");
else else if (score >= 80.0)
if (score >= 80.0) Equivalent System.out.print("B");
System.out.print("B"); else if (score >= 70.0)
else System.out.print("C");
if (score >= 70.0) else if (score >= 60.0)
System.out.print("C"); System.out.print("D");
else else
if (score >= 60.0) System.out.print("F");
System.out.print("D"); This is better
else
System.out.print("F");

(a) (b)

40
Cont…
• switch Statement
• The switch statement allows a variable to be tested for equality against a list of values.
• int day = 3;
• switch (day) {
• case 1:
• System.out.println("Monday");
• break;
• case 2:
• System.out.println("Tuesday");
• break;
• case 3:
• System.out.println("Wednesday");
• break;
• default:
• System.out.println("Other day");
• break;
• }
2. Iteration Statements
• Iteration statements allow blocks of code to be executed repeatedly based on a
condition.
• for Loop
• The for loop is used when the number of iterations is known.
• for (int i = 0; i < 5; i++) {
• System.out.println("Value of i: " + i);
• }
• while Loop
• The while loop is used when the number of iterations is not known and the loop
needs to run until a condition is false.
• int i = 0;
• while (i < 5) {
• System.out.println("Value of i: " + i);
• i++;
• }
Cont..
• do-while Loop
• The do-while loop is similar to the while loop but it guarantees the block of
code will be executed at least once.
• int i = 0;
• do {
• System.out.println("Value of i: " + i);
• i++;
• } while (i < 5);
3. Jump Statements

• Jump statements are used to transfer control to another part of the program.
• break Statement
• The break statement is used to exit from a loop or switch statement.
• for (int i = 0; i < 10; i++) {
• if (i == 5) {
• break; // exits the loop when i is 5
• }
• System.out.println("Value of i: " + i);
• }
Cont…
• continue Statement
• The continue statement is used to skip the current iteration of a loop and continue with
the next iteration.
• for (int i = 0; i < 10; i++) {
• if (i == 5) {
• continue; // skips the rest of the loop when i is 5
• }
• System.out.println("Value of i: " + i);
• }
• Output
• Value of i: 0
• Value of i: 1
• Value of i: 2
• Value of i: 3
• Value of i: 4
• Value of i: 6
• Value of i: 7
• Value of i: 8
• Value of i: 9
Input and Output in Java
• Definition: Reading data from an input source
and writing data to an output destination.
• **Input:** Receiving data from the user.
• - **Output:** Displaying data to the user.
• - **Streams:** Java uses streams to perform input
and output operations.
• Importance: Important for interacting with users
and handling data input/output operations.
• Use: Handle data input from users, files, and
other sources; output data to the console, files,
or other destinations.
Example - Input and Output
import java.util.Scanner;
public class InputOutputDemo {
public static void main(String[] args) {
Scanner input1 = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = input1.nextLine();
System.out.println("Hello " + name + "!");
input1.close(); Explanation: Uses the Scanner
} class to read input from the
user and prints a greeting
} message.
Output:

Enter your name: John


Hello John!
Scanner and System Class
• Definition:
• Scanner Class: Used to get input from various input
sources.
• System Class: Provides access to system resources
including standard input and output.
• Importance: Simplifies input handling and provides
essential system-level operations.
• Use:
• Scanner: Reading input from the console, files, etc.
• System: Managing system input, output, and error
streams.
Example - Scanner and System Class
• import java.util.Scanner;
• public class ScannerSystemDemo {
• public static void main(String[] args) {
• Scanner input1 = new Scanner(System.in);
• System.out.print("Enter a number: ");
• int number = input1.nextInt();
• System.out.println("You entered: " + number);
• input1.close(); Explanation: Uses the
Scanner class to read an
• } integer input from the user
and the System class to print
• } the input value.
Output:
yaml
Enter a number: 25
You entered: 25
• import java.util.Scanner;
• - **Output:**

• Enter your name:
• public class Main {
• John Doe
• public static void main(String[] args) {
• Enter your age:
• Scanner myObj = new Scanner(System.in);
• 20
• System.out.println("Enter your name:");
• Enter your GPA:
• String userName = myObj.nextLine();
• 3.5
• System.out.println("Enter your age:");
• Name: John Doe
• int userAge = myObj.nextInt();
• Age: 20
• System.out.println("Enter your GPA:");
• GPA: 3.5
• double userGPA = myObj.nextDouble();
• System.out.println("Name: " + userName);
• System.out.println("Age: " + userAge);
• System.out.println("GPA: " + userGPA);
• }
• }
print(), println(), and printf() Methods
• Definition:
• print(): Prints text without a newline.
• println(): Prints text with a newline.
• printf(): Prints formatted text using format
specifiers.
• Importance: Provide flexibility in outputting
data to the Control unit.
• Use: Display text and formatted output.
Example - print(), println(), and printf()
• public class PrintDemo {
• public static void main(String[] args) {
• System.out.print("Hello ");
• System.out.print("World");

• System.out.println(); // Newline

• System.out.println("Hello World");

• int age = 25;
• String name = "John";
• System.out.printf("My name is %s and I am %d years old.",
name, age);
• }
• }
Explanation: shwos the use of print(), println(), and
printf() methods.

Output:
Hello World
Hello World
My name is John and I am 25 years old.
Cont…
• Common Format Specifiers for printf()
• %d: Decimal integer
• %f: Floating-point number
• %s: String
• %c: Character
• %x: Hexadecimal integer
• %o: Octal integer
• %b: Boolean
Example of how printf() is used:
public class Main {
public static void main(String[] args) {
int age = 25;
String name = "Alice";
double score = 95.5;

System.out.printf("Name: %s, Age: %d,


Score: %.2f", name, age, score);
}
}
The output of this program will be:
Name: Alice, Age: 25, Score: 95.50

You might also like