0% found this document useful (0 votes)
1 views

java mug2

The document provides an overview of CRUD operations in Java, detailing how to create, read, update, and delete files using the java.io package. It also outlines essential tools for Java programming, including the JDK, IDEs, Scene Builder, and version control with Git, as well as the Java Virtual Machine's class loading process. Additionally, it explains the memory management in the JVM, including the Method Area and Heap Area, and includes examples of Java code for various functionalities.

Uploaded by

Martin Nashaat
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

java mug2

The document provides an overview of CRUD operations in Java, detailing how to create, read, update, and delete files using the java.io package. It also outlines essential tools for Java programming, including the JDK, IDEs, Scene Builder, and version control with Git, as well as the Java Virtual Machine's class loading process. Additionally, it explains the memory management in the JVM, including the Method Area and Heap Area, and includes examples of Java code for various functionalities.

Uploaded by

Martin Nashaat
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 163

Advanced Programming

Lab 8

By Eng. Ziad & Eng. Lujaeen


What is CRUD?

CRUD stands for:


•Create → Make a new file
•Read → Look inside a file and get its data
•Update → Change or add new data to an existing file
•Delete → Remove the file when you don't need it anymore
What is CRUD?

Java has a package called java.io that helps you work with files.
There are a few important classes:
•File → used to create , delete , and get information about files.
•FileWriter → To write into a file.
•FileReader or Scanner → To read from a file.
Create a File and Write Data

import java.io.FileWriter;
import java.io.IOException;

public class CreateFile {


public static void main(String[] args) {
try {
FileWriter writer = new FileWriter("example.txt");
writer.write("Hello, this is the first line.\n");
writer.write("This is the second line.");
writer.close();
System.out.println("File created and data written successfully.");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace(); }}}
Read from a File
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadFile {
public static void main(String[] args) {
try {
File file = new File("example.txt");
Scanner reader = new Scanner(file);
while (reader.hasNextLine()) {
String data = reader.nextLine();
System.out.println(data);
}
reader.close();
} catch (FileNotFoundException e) {
System.out.println("File not found.");
e.printStackTrace(); }}}
Update a File (Append)

import java.io.FileWriter;
import java.io.IOException;

public class UpdateFile {


public static void main(String[] args) {
try {
FileWriter writer = new FileWriter("example.txt", true); // 'true' enables appending
writer.write("\nThis line was added later.");
writer.close();
System.out.println("File updated successfully.");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}}}
Delete a File

import java.io.File;

public class DeleteFile {


public static void main(String[] args) {
File file = new File("example.txt");
if (file.delete()) {
System.out.println("File deleted: " + file.getName());
} else {
System.out.println("Failed to delete the file.");
}
}
}
Complete Guide: All Tools Required to Use Java
(For Beginners)

1. JDK (Java Development Kit) - The Core of Java


- What is it?

The JDK is the most important tool. It contains everything needed to write, compile, and run Java
programs.

- Why do you need it?

 Without JDK, Java won't work.

 It includes javac (Java Compiler) to convert code into machine-readable format.

 It also includes the JVM (Java Virtual Machine) to run Java programs on any computer.

:::Zulu JDK (Recommended for JavaFX & GUI Apps)

2. IDE (Integrated Development Environment)

- What is it?

An IDE (Integrated Development Environment) is a special software that helps you write, test, and run
Java programs easily.

- Why do you need it?

 Makes coding faster with auto-suggestions & debugging tools.

 Helps organize projects better than a basic text editor.

 IntelliJ IDEA is faster and smarter, while NetBeans is beginner-friendly.

:::IntelliJ IDEA or NetBeans - Writing & Running Java Code (IDE)


3. Scene Builder - Designing GUI Apps (For JavaFX)
- What is it?

If you want to create Java applications with buttons, windows, and graphics (GUI), you need Scene
Builder.

Why do you need it?

 Allows drag-and-drop UI design for JavaFX applications.

 Works with IntelliJ IDEA and NetBeans for easy UI creation.

4. JavaFX Libraries (For GUI Development)


- What is it?

JavaFX is a set of tools that helps you create modern graphical applications with Java.

Why do you need it?

 If you are building a Java GUI application (like a calculator, chat app, or dashboard), JavaFX is
required.

 Comes pre-installed with Zulu JDK-FX (No need to download separately if using Zulu JDK).

5. Git (For Version Control & Collaboration)


- What is it?

Git is a tool used to track changes in your code and work on projects with a team.

- Why do you need it?

 Saves different versions of your code, so you don’t lose progress.

 Works with GitHub to store your projects online.

- Where to get it?

 Download Git: Git Download

 Create a Free GitHub Account to Store Code: GitHub


6. Maven or Gradle (For Managing Java Projects)
- What is it?

Maven and Gradle help manage dependencies (extra tools & libraries) that Java projects need.

- Why do you need it?

 If you build large projects, you will need Maven or Gradle to manage external libraries.

 Not needed for small beginner projects.

- Where to get it?

Maven Download: Apache Maven

Gradle Download: Gradle

7. Database (For Storing Data - Optional)


If you are working on applications that store data, you need a database like MySQL, PostgreSQL, or
SQLite.

Recommended:

MySQL (Best for Beginners & Web Apps): MySQL Download

PostgreSQL (Advanced Databases & Large Apps): PostgreSQL Download

SQLite (For Lightweight Apps): SQLite Download

Summary:
1️⃣ Install JDK (Zulu JDK-FX) → The most important tool.

2️⃣ Install IntelliJ IDEA (or NetBeans) → To write & run Java programs easily.

3️⃣ Install Scene Builder (If using JavaFX) → For GUI applications.

4️⃣ Install Git (Optional) → If you want to save your code online.

5️⃣ Install MySQL (Optional) → If your Java app needs database storage.
Step 1: Writing Java file

Java File Example: Java Source Code (HelloWorld.java)

This is a simple Java program written in a .java file.

public class HelloWorld {


public static void main(String[] args) {
System.out.println("Hello, Java!");
}
}

 Human Readable and extension .java.

Step 2: Compile the Java File

Bytecode (HelloWorld.class)

Once compiled, Java code is converted into bytecode, which is a low-level, platform-
independent representation understood by the Java Virtual Machine (JVM). Bytecode is not
human-readable, but here’s how it looks when viewed.

Compiled from "HelloWorld.java"

public class HelloWorld {


public HelloWorld();

0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: return

public static void main(java.lang.String[]);


Code:
0: getstatic #2 // Field java/lang/System.out:Ljava/io/PrintStream;
3: ldc #3 // String Hello, Java!
5: invokevirtual #4 // Method
java/io/PrintStream.println:(Ljava/lang/String;)V
8: return
}

 This is a JVM-readable bytecode stored in the HelloWorld.class file.

 It is platform-independent and can run on any OS with a JVM.


Step3: Machine Code (Executed at Runtime)

 The JVM converts bytecode into machine-specific instructions.


 This machine code is different for Windows, Linux, and macOS, as it depends on the system's
CPU architecture.
 Example of x86-64 assembly instructions (simplified representation of machine code):

mov rax, 1
mov rdi, 1
lea rsi, [Hello_Java]
mov rdx, 13
syscall

 Not portable like Java bytecode.


JVM in Java

1. Class Loader - Loading

1.1 Bootstrap Class Loader (Simple Explanation)


It is built into the JVM (Java Virtual Machine) and is responsible for loading the
core Java classes that are needed for every Java program to run.
 It loads fundamental Java classes like String, Math, System, ArrayList, etc.

 These classes are stored in a special file called rt.jar


 It is the parent of all other class loaders in Java.

What is rt.jar?
 rt.jar stands for Runtime JAR(java Archive).
 It is a special file that contains all the core Java libraries.
 It includes packages like:
o java.lang → (String, Math, Object)
o java.util → (ArrayList, HashMap)
o java.io → (File, InputStream, OutputStream)
o java.net → (Socket, URL)

Hint: Java 9+ uses module-based architecture instead of a single rt.jar.


$JAVA_HOME/lib/modules

 String: Used to store text and manipulate string data.


 Math: Provides mathematical operations like sqrt(), pow(), random(), etc.
 System: Contains utility methods like currentTimeMillis() and out.println().
 ArrayList: A resizable array implementation of the List interface.
Summary:

Bootstrap Class Loader loads essential Java classes from rt.jar.


✔ rt.jar contains fundamental Java libraries like java.lang, java.util, java.io.
✔ It is stored in $JAVA_HOME/jre/lib/rt.jar (Java 8 and earlier).
✔ In Java 9+, rt.jar was removed and replaced with the modules system.
✔ It is part of the JVM and is written in C/C++, not Java.

1.2 - Extension Class Loader (Now Called Platform ClassLoader)


The Extension Class Loader was responsible for loading Java extension classes from a special folder
called ext inside the Java installation.

 This was useful for external APIs, security libraries, and cryptography extensions.

Where is it Now?

 It is now called the Platform Class Loader.


 The ext folder does not exist anymore.
 Instead, external libraries are now loaded using the module system
($JAVA_HOME/lib/modules).

1.3. Application Class Loader


The Application Class Loader, also called the System Class Loader, is responsible for loading
Java classes from the application’s classpath.

What Does It Do?

 It loads classes from the directories and JAR files specified in the CLASSPATH.

Where Does It Load Classes From?

By default, it loads classes from:

 Project directory (where your .class files are stored)


 JAR files in the classpath

Example of Path : C:\Users\Admin\IdeaProjects\FirstProject\src


Try: java -cp C:\Users\Admin\IdeaProjects\FirstProject\out\production\FirstProject

Loading Steps

1. Bootstrap Class Loader (Loads core Java classes like java.lang.String)



2. Platform (Extension) Class Loader (Loads classes from JAVA_HOME/lib and modules)

3. Application Class Loader (Loads user-defined classes from CLASSPATH)

2. Linking – 2.1 Preparation


public class Main {
public static void main(String[] args) {
int intValue; // Default: 0
double doubleValue; // Default: 0.0
boolean boolValue; // Default: false
String strValue; // Default: null
System.out.println("intValue: " + intValue); // Output: 0
System.out.println("doubleValue: " + doubleValue); // Output: 0.0
System.out.println("boolValue: " + boolValue); // Output: false
System.out.println("strValue: " + strValue); // Output: null
}
}

 In Java's class loading process, the preparation phase only assigns default values to static
variables.

 No Java code (such as System.out.println() or method calls) is executed in this phase.


If you try to run code in the preparation phase, it will not execute because:

 Only memory allocation happens—no actual execution.


 Static variables are assigned default values—but the JVM has not yet executed any method or
static block.
 Code execution only happens in the Initialization Phase, after static variables are assigned their
proper values.

2.2 Step-by-Step Breakdown of Resolution

1. Before Resolution (Bytecode Stage)

 The compiled .class file does not store memory addresses.


 Instead, it has symbolic references like:

 Parent.display()
 Child.show()

2. During Resolution

 It finds their actual memory addresses and replaces the


symbolic references.
3. After Resolution

Now, instead of searching for Parent.display() by name every time, the JVM directly accesses its memory
address.
2. Run time data area

When a Java program runs, the JVM (Java Virtual Machine) divides memory into
different areas, including Method Area and Heap, each serving a specific purpose.

Method Area Vs Heap Area


1. Method Area (Part of the JVM Memory): The Method Area is a part of the JVM Runtime
Memory (or JVM Heap) where class-related data is stored

✔ Stores class-related data.


✔ Includes static variables, method bytecode, and metadata.

class Example {
static int count = 10; // Stored in Method Area
}

void display() {
System.out.println("Hello");
}

What is Stored in the Method Area?

Stored Data Example

 Class Metadata Class name, superclass, modifiers


 Method Bytecode public void run() {}
 Static Variables static int counter = 0;
 Constant Pool Entries String literals ("Hello" in "Hello"to UpperCase();)
Numeric constants (final static int PI = 3;)
2. Heap Area (Part of JVM Memory)

✔ Stores objects and instance variables.


✔ Each object created at runtime is stored here.
✔ Managed by Garbage Collector (GC).

What is Stored in the Heap Area?

Stored Data Example


Object Instances new Example();
Instance Variables int age; String name;
Arrays int[] numbers = {1, 2, 3};
Execution Engine
1. Intermediate Code Generator :
Generates an intermediate representation (IR) of the Java bytecode. This step makes it easier to
apply optimizations before converting to machine code.

 The JIT Compiler analyzes the bytecode and converts it into intermediate code (IR).
 This IR is not yet native machine code but is easier for the compiler to work with.

int sum (int a, int b) {


return a + b; }

2. Code Optimizer
 Enhances the intermediate code (IR) to improve execution speed and reduce memory usage.

 Optimized code runs faster, reducing CPU cycles and improving efficiency.

 Example Before Optimization:

int square(int x) {
return x * x;
}
int result = square(5); // Function call

 Optimized Code (Inlining Applied):

int result = 5 * 5; // Direct calculation (avoids function call overhead)


 Target Code Generator

Converts the optimized intermediate representation (IR) into native machine code for the
CPU.

int sum(int a, int b) {

return a + b;

MOV EAX, [EBP+8] ; Load 'a' into EAX register

ADD EAX, [EBP+12] ; Add 'b' to EAX

MOV [EBP-4], EAX ; Store result in memory

 Profiler

 Monitors the program to identify hotspots (frequently executed methods or loops).

 Instead of compiling all methods, JIT compiles only the most used parts to save
resources.
Lecture 3 Examples

Example 1:
String x = "Helwan";
System.out.println("Hello my university"+ " " + x);

Example 2: Static Method without instance of calss


public class Main {
public static void main(String[] args) {
// Calling the static method without creating an object
MyClass.sayHello(); // Output: Hello from the static method!
}
}

public class MyClass {


// Static method
public static void sayHello() {
System.out.println("Hello from the static method!");
}
}

Example 3: Creating instance without static keyword


public class Main {
public static void main(String[] args) {
MyClass obj = new MyClass();
obj.sayHello(); // Output: Hello from the static method!
}
}

public class MyClass {


// Static method
public void sayHello() {
System.out.println("Hello from the static method!");
}
}

Example 4: Scanner class


import java.util.Scanner;

public class Main {


public static void main(String[] args) {
// 2. Create a Scanner object
Scanner input = new Scanner(System.in);

// Example of reading a String


System.out.print("Enter your name: ");
String name = input.nextLine(); // Reads the full line of
input
System.out.println("Hello, " + name);

// Example of reading a byte


System.out.print("Enter a byte value: ");
byte byteValue = input.nextByte();
System.out.println("You entered byte value: " + byteValue);

// Example of reading a short


System.out.print("Enter a short value: ");
short shortValue = input.nextShort();
System.out.println("You entered short value: " + shortValue);

// Example of reading an int


System.out.print("Enter an integer value: ");
int intValue = input.nextInt();
System.out.println("You entered integer value: " + intValue);

// Example of reading a long


System.out.print("Enter a long value: ");
long longValue = input.nextLong();
System.out.println("You entered long value: " + longValue);

// Example of reading a float


System.out.print("Enter a float value: ");
float floatValue = input.nextFloat();
System.out.println("You entered float value: " + floatValue);

// Example of reading a double


System.out.print("Enter a double value: ");
double doubleValue = input.nextDouble();
System.out.println("You entered double value: " +
doubleValue);

// Example of reading a boolean


System.out.print("Enter a boolean value (true/false): ");
boolean boolValue = input.nextBoolean();
System.out.println("You entered boolean value: " +
boolValue);

// Close the scanner


input.close();
}
}

Example 5:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
System.out.println("Enter name, age and salary:");
String name = myObj.nextLine();
int age = myObj.nextInt();
double salary = myObj.nextDouble();
System.out.println("Name: " + name);
System.out.println("Age: " + age);

System.out.println("Salary: " + salary);


}
}

Example 6

Examples of Identifiers in Java:

1. Valid Identifiers:

int myAge = 25; // A valid identifier: 'myAge' for a variable


double userBalance = 1500.50; // 'userBalance' is a valid identifier
String $name = "John"; // '$name' is a valid identifier (dollar sign is allowed)
boolean _isActive = true; // '_isActive' is a valid identifier (underscore is allowed

2. Invalid Identifiers:
int 123abc = 10; // Invalid because it starts with a digit
double class = 20.5; // Invalid because 'class' is a reserved keyword
String user-name = "Alice"; // Invalid because it contains a hyphen (-)

Example 7 : type casting


double doubleVal=2.8;
int intVal= (int) doubleVal;
System.out.println("intVal = "+intVal);

int a=35,b=12,d=13;
char valC=(char)(a+b+d);
System.out.println("valC = "+a);

Example 8: When casting is valid : valid


int myInt = 100; // Declare an int variable
double myDouble = myInt; // Implicit casting: int to double

System.out.println("Integer value: " + myInt);


System.out.println("Double value: " + myDouble);
Not valid

double myInt = 100; // Declare an int variable


int myDouble = myInt; // Implicit casting: int to double

System.out.println("Integer value: " + myInt);


System.out.println("Double value: " + myDouble);

Example 9: Reading a String from the Console


Scanner input = new Scanner(System.in);
System.out.println("Enter First String: ");
String First = input.nextLine();
System.out.println("Enter Second String: ");
String Second = input.next();
System.out.println("First String is : "+First);
System.out.println("First Second is : "+Second);

Example 10: Comparing string


// Sample strings
String str1 = "Hello World";
String str2 = "hello world";
String str3 = "Hello";
String str4 = "World";
String str5 = "World";

// equals() - checks if two strings are equal


System.out.println("Using equals(): " + str1.equals(str2)); // false
// equalsIgnoreCase() - checks if two strings are equal ignoring case
System.out.println("Using equalsIgnoreCase(): " + str1.equalsIgnoreCase(str2)); // true
// startsWith() - checks if a string starts with the specified prefix
System.out.println("Using startsWith(): " + str1.startsWith("Hello")); // true
// endsWith() - checks if a string ends with the specified suffix
System.out.println("Using endsWith(): " + str1.endsWith("World")); // true

Substring examples

String mes="welcome to java";


System.out.println(mes.substring(11));
System.out.println(mes.substring(0,11));
int k = mes.indexOf(' ');
String first = mes.substring(0, k);
String last = mes.substring(k + 1);
System.out.println("First ="+first);
System.out.println("last ="+last);
Question Samples Lec 3

1. Which method in Java compares the content of two strings?

a) compareTo()
b) equals()
c) ==
d) substring()

2. What will be the output of the following code?

String str1 = "Hello";


String str2 = "hello";
System.out.println(str1.equals(str2));

a) true
b) false
c) Compilation error
d) Runtime exception

3. What will the following code output?

String str1 = "Apple";


String str2 = "apple";
System.out.println(str1.equalsIgnoreCase(str2));

a) true
b) false
c) Error
d) null

4. Which method would you use to read an entire line of text from the user using Scanner?

a) next()
b) nextLine()
c) nextInt()
d) nextDouble()

5. What is the correct syntax to perform type casting from double to int?

a) int x = (int) 3.14;


b) double x = (int) 3.14;
c) int x = 3.14;
d) float x = (double) 3.14
6. Which of the following statements is true regarding the == operator for string
comparison?

a) It compares the values of the strings


b) It compares the memory references of the strings
c) It ignores case sensitivity
d) It compares the length of the strings

7. What does the method substring(0, 5) do for a string "Hello World"?

a) It extracts "Hello"
b) It extracts "World"
c) It extracts "Hello World"
d) It causes an error

8.Which of the following is a valid identifier in Java?

a) 1stValue
b) first-value
c) firstValue
d) first value

9.What is the value of str1.compareTo(str3) if str1 = "Apple" and str3 = "Apple"?

a) 0
b) 1
c) -1
d) true

a) 0
Explanation: compareTo() returns 0 if the strings are equal.

10. Which method is used to check if a string starts with a specific prefix?

a) compareTo()
b) equals()
c) startsWith()
d) endsWith()
Question 2: Practical programs

2.1 Write a program that takes two strings as input from the user and prints the concatenation of
these two strings with a space in between. Use the example of "Hello" and "World" from the
uploaded content to guide your solution.

2.2 Write a program that extracts substrings from a given string "Welcome to Java". Extract the
substring from index 5 onwards, and extract the first 5 characters. Use the substring() method.

2.3 Write a program that reads multiple values (name, age, and salary) from the user using the
Scanner class. Ensure that the program handles reading a string (name), an integer (age), and a
double (salary) in sequence.
Q2.1 Answer

Scanner scanner = new Scanner(System.in);


System.out.print("Enter the first string: ");
String str1 = scanner.nextLine();
System.out.print("Enter the second string: ");
String str2 = scanner.nextLine();

System.out.println("Concatenated String: " + str1 + " " + str2);


scanner.close();

Q2.2 Answer

String mes = "Welcome to Java";


System.out.println(mes.substring(5));
System.out.println(mes.substring(0, 5));

Q2.3 Answer

Scanner scanner = new Scanner(System.in);

System.out.print("Enter your name: ");


String name = scanner.nextLine();

System.out.print("Enter your age: ");


int age = scanner.nextInt();

System.out.print("Enter your salary: ");


double salary = scanner.nextDouble();

System.out.println("Name: " + name);


System.out.println("Age: " + age);
System.out.println("Salary: " + salary);

scanner.close();
int sum = 0;
int n = 2;
for (int i = 1; i <= n; i++) {
sum += i;
}
System.out.println("Sum = " + sum);
}

Repetitive processing Example


The for loop in programming has a specific structure, typically consisting of three parts:
initialization, condition, and the action performed after each iteration. These parts can be flexible
in certain ways:

1. Initial Action: This part can be one or more comma-separated expressions, such as
initializing variables.
2. Condition: This part evaluates whether the loop should continue.
3. Action After Each Iteration: This part can include one or more comma-separated
statements, which are executed at the end of each iteration

for (int i = 0, j = 0; (i + j < 5); i++, j++) {


System.out.println("i= " + i + " and j= " + j);
}

While Loop
int sum = 0;
Scanner input = new Scanner(System.in);
System.out.println("Enter a number");
int number = input.nextInt();
while (number >= 0) {
sum += number;
System.out.println("Enter a number");
number = input.nextInt();
}
System.out.println("Sum = " + sum);
input.close();
}
Unintended Integer Division
int number1 = 1;
int number2 = 2;
double average = (number1 + number2) / 2;
System.out.println(average);

int number1 = 1;
int number2 = 2;
double average = (number1 + number2) / 2.0;
System.out.println(average);

Common Errors
double radius=-1,area,PI= 3.14;
if (radius <= 0);
{
area = radius*radius*PI;
System.out.println("The area for the circle of radius " + radius + " is " + area);
}

for (int i=0; i<10; i++)


{
System.out.println("i is " + i);
}

Calling Method
// Method to add two numbers and print the sum
public static void addNumbers(int num1, int num2) {
int sum = num1 + num2;
System.out.println("Sum: " + sum);
}

public static void main(String[] args) {


addNumbers(5, 7); // Passing 5 and 7 as arguments
}
}
For each :

int[] marks = { 125, 132, 95, 116, 110 };


int highest_marks = maximum(marks);
System.out.println("The highest score is " + highest_marks);
}
public static int maximum(int[] numbers)
{
int maxSoFar = numbers[0];
// for each loop
for (int num : numbers)
{
if (num > maxSoFar)
{
maxSoFar = num;
}
}
return maxSoFar;
}}
Arrays Copy
Example 1: array copy
public static void main(String[] args) {
int[] source = {1, 2, 3, 4, 5};
int[] destination = new int[source.length];

System.arraycopy(source, 0, destination, 0, source.length);

// Print copied array


for (int num : destination) {
System.out.print(num + " ");
}
}
}

 source: The original array.


 0: Start index in the source array.
 destination: The new array where elements will be copied.
 0: Start index in the destination array.
 source.length: Number of elements to copy.

Second way using loop


int[] sourceArray = {2, 3, 1, 5, 10};
int[] targetArray = new int[sourceArray.length];

for (int i = 0; i < sourceArray.length; i++) { // Fixed typo here


targetArray[i] = sourceArray[i];
}

// Print target array to verify the copy


for (int num : targetArray) {
System.out.print(num + " ");
}
}
}
Copying arrays
public class Main {
public static void main(String[] args) {
int[] sourceArray = {2, 3, 1, 5, 10};
int[] targetArray = {8,9,11,13};
int[] temparray=new int[sourceArray.length];
sourceArray=targetArray;
System.out.println("source array");
for (int i:sourceArray) {
System.out.print(i+" ");
}
System.arraycopy(sourceArray, 0, temparray, 0, sourceArray.length);
System.out.println();
System.out.println("target array");
for (int i:temparray) {
System.out.print(i+" ");
}
System.out.println();
System.out.println("address sourceArray = "+sourceArray);
System.out.println("address targetArray = "+targetArray);
System.out.println("address temparray = "+temparray);
}
}

Notes :

Assigning sourceArray = targetArray;

 This does not copy the contents of targetArray into sourceArray.


 Instead, sourceArray now references the same memory location as targetArray.
 The original {2, 3, 1, 5, 10} array is now lost, and sourceArray now holds {8, 9, 11, 13}.

Copying sourceArray into temparray

 Problem: temparray has size 5, but sourceArray (now targetArray) has only 4 elements.
 System.arraycopy(sourceArray, 0, temparray, 0, sourceArray.length)
 Tries to copy 4 elements (because sourceArray.length = 4) from sourceArray to temparray.
 The first 4 elements of temparray are updated with {8, 9, 11, 13}.
 The 5th element of temparray remains 0, as it was never updated.
 In Java, when printing an array reference like System.out.println(sourceArray), it prints its
memory address (hash code).
Passing Explicit Array to method
public static void printArray(int[] array) {
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
}
public static void main(String[] args) {
int[] list = {3, 1, 2, 6, 4, 2};
printArray(list);

}
}

Passing Anonymous array


public static void printArray(int[] array) {
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
}
public static void main(String[] args) {
printArray(new int[]{3, 1, 2, 6, 4, 2});

}
}

Characteristics of Anonymous Arrays:

 No explicit name.
 Created and used in a single statement.
 Useful for one-time use cases.
 Cannot be reused after method execution.

Pass by value and pass by reference


public class Main {
public static void main(String[] args) {

int x =0; // x represents an int value


int[] y = new int[10]; // y represents an array of int values
y[0]=2222;
m(x, y); // Invoke m with arguments x and y
System.out.println("x is " + x);
System.out.println("y[0] is " + y[0]);
}
public static void m(int number, int[] numbers) {
number = 1001; // Assign a new value to number
numbers[0] = 5555;
System.out.println("number is " + number);// Assign a new value to numbers[0]
}
}

Print reverse array


import java.util.Arrays;

public class Main {


public static int[] reverse(int[] list) {
int[] result = new int[list.length];

for (int i = 0, j = result.length - 1;i < list.length; i--, j++) {


result[j] = list[i];
}
return result;
}
public static void main(String[] args) {
int[] list1 = {1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
// Print the reversed array
System.out.println("Original Array: " + Arrays.toString(list1));
System.out.println("Reversed Array: " + Arrays.toString(list2));
}
}

Note : Arrays.toString(Array)

In Java, if you try to print an array directly using System.out.println(list1); it will print something like
[I@1b6d3586 instead of the actual array elements. This is because arrays do not override the toString()
method from Object, so they display their memory address instead.

Variable-Length Arguments
public class Main {
public static void printMax(double... numbers) {
if (numbers.length == 0) {
System.out.println("No argument passed");
return;
}
double result = numbers[0];
for (int i = 1; i < numbers.length; i++)
if (numbers[i] > result)
result = numbers[i];
System.out.println("The max value is " + result);
}
public static void main(String[] args) {
printMax(34, 3, 3, 2, 56.5);
printMax(new double[]{1, 2, 3}); }
}

When to Use Variable-Length Arguments?

When the number of modify(arr);

 at compile-time.
 When calling a method with different numbers of arguments, without manually creating an
array.
 When you want to simplify method calls by avoiding array instantiation.

Ragged Arrays

public class Main {


public static void main(String[] args) {
int[][] triangleArray = {
{1, 2, 3, 4, 5},
{2, 3, 4, 5},
{3, 4, 5},
{4, 5},
{5}
};
for (int row = 0; row < triangleArray.length; row++) {
for (int column = 0; column < triangleArray[row].length; column++) {
System.out.print(triangleArray[row][column] + " ");
}
System.out.println();
}
}
}
1. How do you correctly declare an array in Java?

A) int arr[5];

B) int arr = new int[5];

C) int[] arr = new int[5];

D) array<int> arr = new array<int>[5];

2. What is the default value for elements in a new integer array?

A) null

B) 0

C) 1

D) undefined

3. What is the output of the following code?

public static void main(String[] args) {


int[] nums = {2, 4, 6, 8};
System.out.println(nums.length);
A) 3
B) 4
C) 5
D) Compilation error

4. What is the result of accessing an array index that is out of bounds?

A) The program ignores it


B) It prints null
C) It throws an ArrayIndexOutOfBoundsException
D) The compiler detects and fixes it

5. What is the correct syntax to copy an array using System.arraycopy()?

A) System.arraycopy(source, srcPos, destination, destPos, length);


B) System.copy(source, dest, length);
C) System.copyArray(source, dest);
D) source.copy(dest, length);
6. What is the output of the following code?

public class Main {

public static void modify(int[] arr) {


arr[0] = 100;
}
public static void main(String[] args) {
{
int[] arr = {10, 20, 30};
modify(arr);
System.out.println(arr[0]);
}
}

A) 10
B) 100
C) Compilation error
D) Runtime error

7. What is the output of this code?


int[] arr = {1, 2, 3, 4, 5};
System.out.println(arr[arr.length - 1]);

A) 1
B) 5
C) Compilation error
D) Runtime error

8. What is the output of this code?


int[][] matrix = new int[3][];
System.out.println(matrix[0].length);

A) 0
B) Compilation error
C) Runtime error
D) NullPointerException

9. What is the output of this code?


int[] arr = {2, 4, 6, 8};
for (int i = 0; i < arr.length; i += 2) {
System.out.print(arr[i] + " ");
A) 2 4 6 8
B) 2 6
C) 2 6 8
D) Compilation error

10. What is the output of this code?


int[] a = {10, 20, 30};
int[] b = a;
b[0] = 100;
System.out.println(a[0]);
A) 10
B) 100
C) Compilation error
D) Runtime error

11. What is the output of this code?


int[] arr = {5, 10, 15, 20};
for (int num : arr) {
num *= 2;
}
System.out.println(arr[1]);

A) 10
B) 20
C) 30
D) 40

12. What is the output of this code?


int[][] arr = new int[2][];
arr[0] = new int[3];
arr[1] = new int[2];
System.out.println(arr.length + " " + arr[0].length);

A) 2 3
B) 3 2
C) Compilation error
D) Runtime error

13. Which of the following describes the role of the JVM's Just-In-Time (JIT)
compiler?

A) It interprets bytecode and converts it into native machine code.


B) It dynamically compiles frequently executed bytecode into native machine code to improve
performance.
C) It loads bytecode into the JVM.
D) It checks for errors during the compilation process.

14. What is the main advantage of Java's "Write Once, Run Anywhere"
(WORA) capability?

A) The Java Virtual Machine (JVM) compiles Java code into machine-specific code.
B) Java code can be run on any operating system without modification because it is compiled
into platform-independent bytecode.
C) Java uses native code to execute on different platforms.
D) The Java Runtime Environment (JRE) automatically adjusts to the OS.

15. In Java, which component is responsible for translating bytecode into


machine code?

A) Java Compiler (javac)


B) ClassLoader
C) Java Virtual Machine (JVM)
D) Just-In-Time Compiler (JIT)

16. In the context of Java, what is meant by "garbage collection"?

A) It is the process of converting Java bytecode into machine code.


B) It is the automatic process of freeing memory by removing objects that are no longer in use.
C) It is the manual process of removing unused variables and methods.
D) It refers to the removal of class definitions that are not used.

17. What happens during the "resolution" phase of the class loading process?

A) The JVM verifies the bytecode of the class file.


B) The JVM prepares memory for class variables.
C) The JVM replaces symbolic references in the bytecode with actual memory addresses.
D) The JVM initializes static variables and executes static blocks.

18. Fix the error in the following code to make it print the correct sum of even numbers in
the array:

nt[] arr = {1, 2, 3, 4, 5, 6};


int sum = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] % 2 = 0) {
sum += arr[i];
}
}
System.out.println(sum);
}

A) Replace arr[i] % 2 = 0 with arr[i] % 2 == 0


B) Replace arr[i] % 2 = 0 with arr[i] = 0
C) Replace sum += arr[i] with sum = arr[i]
D) There is no error in the code
Encapsulation
Data encapsulation is one of the fundamental concepts in Object-Oriented Programming
(OOP), and it offers several significant advantages.

The main idea behind data encapsulation is to restrict direct access to an object's internal data and
instead provide controlled access via public methods ( getters and setters). Here's why
encapsulation is necessary:

1. Data Protection

 Control over data access: Encapsulation allows you to control how the data within an
object is accessed or modified.
 You can provide public methods that allow reading and modifying the data, but the actual
fields (variables) remain private or protected. This prevents unauthorized access or
modification, reducing the risk of bugs or security issues.
 public class Account {
private double balance; // Private variable

// Public getter method to access balance


public double getBalance() {
return balance;
}

// Public setter method to modify balance


public void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
}

2. Abstraction of Complexity

 Hiding implementation details: By encapsulating data, the implementation details of an


object are hidden from the outside world.

3. Data Validation

 Ensuring data integrity: Encapsulation allows you to validate the data before it is set or
modified. By using setter methods, you can add checks (e.g., ensuring that a balance is
never negative or a user’s age is realistic). This ensures that objects are always in a valid
state, preventing incorrect data from being introduced.
 public void setAge(int age) {
if (age > 0 && age < 150) {
this.age = age;
} else {
System.out.println("Invalid age.");
}
}
Package Vs Classes

 Purpose: A package is used to organize classes into a structured namespace, while a class is
used to define the attributes and behaviors of objects.

 Hierarchy: A package can contain multiple classes, but a class can only belong to one
package at a time.

 Visibility: Classes can be public or private within a package, whereas packages themselves are
not directly visible outside their defined namespace unless explicitly imported.

Why need package?

1. Group related classes: Packages help organize classes that are related by functionality. For
example, all the utility classes can be grouped in a com.example.utils package, making it
easier to locate and maintain them.

2. Organization of Code

Group related classes: Packages help organize classes that are related by functionality. For
example, all the utility classes can be grouped in a com.example.utils package, making it
easier to locate and maintain them.

3. Access Control

 Visibility control: Java packages provide access control. By default, classes in the same
package can access each other’s private members, but classes from other packages cannot.
This helps in defining the boundaries of a class's visibility:
o Public: Accessible from anywhere.
o Default (no modifier): Accessible only within the same package.
Example 1 : Example of Data Field Encapsulation

public class CircleWithPrivateDataFields {

private double radius = 1;


static int numberOfObjects = 0;

public CircleWithPrivateDataFields() {
numberOfObjects++;
}

public CircleWithPrivateDataFields(double newRadius) {


radius = newRadius;
numberOfObjects++;
}

public double getRadius() {


return radius;
}

public void setRadius(double newRadius) {


radius = (newRadius >= 0) ? newRadius : 0;
}

public static int getNumberOfObjects() {


return numberOfObjects;
}

public double getArea() {


return radius * radius * Math.PI;
}
}

public class Main {


public static void main(String[] args) {
// Display number of Circle objects before creation
CircleWithPrivateDataFields myCircle = new
CircleWithPrivateDataFields(5.0);

System.out.println(myCircle.radius);
System.out.println("The area of the circle of radius "
+ myCircle.getRadius() + " is " + myCircle.getArea());

myCircle.setRadius(myCircle.getRadius() * 1.1);

System.out.println("The area of the circle of radius "


+ myCircle.getRadius() + " is " + myCircle.getArea());
System.out.println("The number of objects created is "
+ CircleWithPrivateDataFields.getNumberOfObjects());
}
}

Example 2:
public class Person {
// Private fields (encapsulation)
private String name;
private int age;

// Public getter for name


public String getName() {
return name;
}

// Public setter for name


public void setName(String newName) {
name = newName;
}

// Public getter for age


public int getAge() {
return age;
}

// Public setter for age


public void setAge(int newAge) {
if (newAge >= 0) {
age = newAge;
} else {
System.out.println("Age cannot be negative.");
}
}
}

// File: Person.java

public class Main {


public static void main(String[] args) {
{
Person p1 = new Person();

// Set data using public methods


p1.setName("Ahmed");
p1.setAge(25);
// Get data using public methods
System.out.println("Name: " + p1.getName());
System.out.println("Age: " + p1.getAge());

// Try setting invalid age


p1.setAge(-5); // Will print warning and not change age
}
}
}

Array of objects

Remember:

int[] arr = new int[5];

 arr is a reference variable stored on the stack.


 The actual array of 5 int values is created on the heap memory.
 The variable arr holds a reference (pointer) to the memory location of that array

Array of objects:

Person[] people = new Person[5];

This line does NOT create 5 Person objects, it only:

1. Creates an array of 5 references to Person (on the heap).


2. All elements are initially set to null.
3. The variable people is a reference stored on the stack, pointing to the array in the heap.

Example of an array of objects

public class Student {

String name;
int age;

// Constructor
public Student(String name, int age) {
this.name = name;
this.age = age;
}

// Method to display student info


public void displayInfo() {
System.out.println("Name: " + name + ", Age: " + age);
}
}
public class Main {
public static void main(String[] args) {
// Create an array of Student objects
Student[] students = new Student[3];

// Initialize each element


students[0] = new Student("Ahmed", 20);
students[1] = new Student("Sara", 22);
students[2] = new Student("Omar", 21);

// Loop through and display info


for (int i = 0; i < students.length; i++) {
students[i].displayInfo();
}
}

}
Java Classes vs C/C++ Structs

Feature Java Classes C/C++ Structs

Purpose Used for creating objects with behavior Used to group data together

Methods Can contain methods Cannot contain methods (in C)

Typically no encapsulation (public


Encapsulation Supports encapsulation with access modifiers
by default)

No inheritance in C, limited
Inheritance Supports inheritance and polymorphism
inheritance in C++

Access Modifiers Can use private, protected, public By default, public members (in C)

Full object-oriented support (encapsulation,


OOP Features Basic data grouping (no OOP in C)
inheritance, polymorphism)

Memory Manual memory management


Managed by Java garbage collector
Management (stack/heap)

Default Member
Private by default (unless specified) Public by default (in C)
Access

Example 1: Reference variables and assignment


class User {
String userID;
String emailAddress;
int numOfAccesses;

public User(String userID, String emailAddress, int numOfAccesses) {


this.userID = userID;
this.emailAddress = emailAddress;
this.numOfAccesses = numOfAccesses;
}
}

public class Main {


public static void main(String[] args) {
User john = new User("123", "[email protected]", 5);
User jane = john; // jane now references the same object as john

// Accessing attributes through jane (same object as john)


System.out.println(jane.userID); // Output: 123
jane.userID = "Bridgend"; // Modify userID through jane
System.out.println(jane.userID); // Output: Bridgend
System.out.println(john.userID); // Output: Bridgend (john sees the
change)
}
}

 jane is just a reference variable, not a new object.


 john refers to an existing object. This object has its own attributes (like userID, emailAddress, and
numOfAccesses).
 When you write jane = john;, jane becomes a reference to the same object that john is referencing.
In other words, jane and john are both pointing to the same object in memory.

Different types of constructors of java by examples

1. Default Constructor (No-Argument Constructor)

A default constructor is provided automatically by the Java compiler if no constructors are


defined in the class. It initializes the object with default values (e.g., null for objects, 0 for numeric
types, false for booleans).

class Car {
String model;
int year;
}
public class Main {
public static void main(String[] args) {
Car myCar = new Car(); // Calls the default constructor
System.out.println(myCar.model); // Output: null (default value)
System.out.println(myCar.year); // Output: 0 (default value)
}
}
2. Parameterized Constructor

A parameterized constructor is a constructor that takes arguments to initialize an object with


specific values when it is created.

class Car {
String model;
int year;
// Parameterized constructor
public Car(String model, int year) {
this.model = model;
this.year = year;
}
}
public class Main {
public static void main(String[] args) {
Car myCar = new Car(("Toyota",””); // Passes values to the
constructor
System.out.println(myCar.model); // Output: Toyota
System.out.println(myCar.year); // Output: 2022
}
}

In this example, the Car class has a parameterized constructor that takes two
arguments (model and year) and initializes the object's fields accordingly.

3. No-Argument Constructor

A no-argument constructor is similar to the default constructor but can be explicitly defined by
the programmer to perform specific initializations.

 Example of No-Argument Constructor:



 class Car {
String model;
int year;

// No-argument constructor
public Car() {
this.model = "Unknown"; // Assigns default value
this.year = 2020; // Assigns default value
}
}
public class Main {
public static void main(String[] args) {
Car myCar = new Car(); // Calls the no-argument constructor
System.out.println(myCar.model); // Output: Unknown
 myCar.model=”fdfsdfdsf”
System.out.println(myCar.year); // Output: 2020
}
}
Here, the constructor initializes model to "Unknown" and year to 2020 when no arguments are passed.

4. Constructor Overloading

 Constructor overloading allows a class to have more than one constructor, each with a
different set of parameters.
 The correct constructor is called based on the number and type of arguments passed when
creating an object.

class Car {
String model;
int year;
// Default constructor
public Car() {
this.model = "Unknown";
this.year = 2020;
}
// Parameterized constructor
public Car(String model) {
this.model = model;
this.year = 2020;
}
// Parameterized constructor with both model and year
public Car(String model, int year) {
this.model = model;
this.year = year;
}
}
public class Main {
public static void main(String[] args) {
Car car1 = new Car(); // Calls default constructor
Car car2 = new Car("BMW"); // Calls constructor with model
Car car3 = new Car(“skoda”,2023); // Calls constructor with
model and year

System.out.println(car1.model + " " + car1.year); // Output:


Unknown 2020
System.out.println(car2.model + " " + car2.year); // Output:
BMW 2020
System.out.println(car3.model + " " + car3.year); // Output:
Audi 2023
}
}

the Car class is overloaded with multiple constructors. Based on the arguments passed (no arguments,
one argument, or two arguments), the corresponding constructor is called.
Circle Example

public class SimpleCircle {

double radius;
/** Construct a circle with radius 1 */
SimpleCircle() {
radius = 1;
}
/** Construct a circle with a specified radius */
SimpleCircle(double newRadius) {
radius = newRadius;
}
/** Return the area of this circle */
double getArea() {

return radius * radius * Math.PI;


}

/** Return the perimeter of this circle */


double getPerimeter() {
return 2 * radius * Math.PI;
}
/** Set a new radius for this circle */
void setRadius(double newRadius) {
radius = newRadius;
}
}

public class Main {


public static void main(String[] args) {
// Create a circle with radius 1
SimpleCircle circle1 = new SimpleCircle();
System.out.println("The area of the circle of radius "
+ circle1.radius + " is " + circle1.getArea());

// Create a circle with radius 25


SimpleCircle circle2 = new SimpleCircle(25);
System.out.println("The area of the circle of radius "
+ circle2.radius + " is " + circle2.getArea());

// Create a circle with radius 125


SimpleCircle circle3 = new SimpleCircle(125);
System.out.println("The area of the circle of radius "
+ circle3.radius + " is " + circle3.getArea());

// Modify circle2 radius


circle2.radius = 100; // or circle2.setRadius(100)
System.out.println("The area of the circle of radius "
+ circle2.radius + " is " + circle2.getArea());
}
}

1. Static Variables

Static variables are shared by all instances (objects) of a class. They are not specific to any one
object but belong to the class itself. Each time a new object is created, it doesn’t get a new copy
of the static variable; instead, all objects refer to the same static variable.

 Declaring a Static Variable: To declare a static variable, use the static keyword.
 class Counter {
static int count = 0; // Static variable
public Counter() {
count++; // Increment the static variable
}
public void displayCount() {
System.out.println("Count: " + count);
}
}
public class Main {
public static void main(String[] args) {
Counter c1 = new Counter(); // count = 1
Counter c2 = new Counter(); // count = 2
c1.displayCount(); // Output: Count: 2
c2.displayCount(); // Output: Count: 2
}
}

 The variable count is static, so it is shared between all instances of the Counter class.
 Both c1 and c2 increment the same count variable.
 After two objects are created, the static variable count is 2 for both c1 and c2.

Check it without static

 class Counter {
int count = 0;
public Counter() {
count++; // Increment the static variable
}
public void displayCount() {
System.out.println("Count: " + count);
}
}
public class Main {
public static void main(String[] args) {
Counter c1 = new Counter(); // count = 1
Counter c2 = new Counter(); // count = 1
c1.displayCount(); // Output: Count: 1
c2.displayCount(); // Output: Count: 1
}
Static Methods

Static methods are not tied to a specific instance of the class but rather to the class itself.
Therefore, you can call a static method without creating an instance of the class.

 Declaring a Static Method: To declare a static method, use the static keyword.

 class MathUtil {
// Static method
public static int square(int num) {
return num * num;
}
}
public class Main {
public static void main(String[] args) {
int result = MathUtil.square(5); // Call the static method
without creating an object
System.out.println("Square of 5: " + result); // Output:
Square of 5: 25
}
}

Static Constants

Static constants are final variables that are shared by all instances of a class. Since they are
final, they cannot be changed once initialized. They are typically used for values that remain
constant across all objects of the class.

 Declaring Static Constants: Use the static and final keywords together.

When use?

 Static variables are useful when you need to keep track of a value that is common to all
instances, such as a counter.
 Static methods are used when the behavior is related to the class as a whole rather than a
particular instance, like mathematical operations.
 Static constants provide a convenient way to define constant values that don’t change,
ensuring that they are consistent throughout the class.
Slide 36 Example code :
public class CircleWithStaticMembers {

double radius;
static int numberOfObjects = 0; // Static variable to track the number of
objects created

// Default constructor
CircleWithStaticMembers() {
radius = 1.0; // Initialize radius to 1.0 by default
numberOfObjects++; // Increment the static counter whenever an object
is created
}

// Constructor with parameter to initialize radius


CircleWithStaticMembers(double newRadius) {
radius = newRadius;
numberOfObjects++; // Increment the static counter
}

// Static method to get the number of objects created


static int getNumberOfObjects() {
return numberOfObjects;
}

// Method to calculate the area of the circle


double getArea() {
return radius * radius * Math.PI;
}
}

public class Main {


public static void main(String[] args) {
// Display number of Circle objects before creation
System.out.println("Before creating objects");
System.out.println("The number of Circle objects is " +
CircleWithStaticMembers.numberOfObjects);

// Create the first circle object


CircleWithStaticMembers c1 = new CircleWithStaticMembers();
System.out.println("\nAfter creating c1");
System.out.println("c1: radius (" + c1.radius + ") and number of
Circle objects (" + c1.numberOfObjects + ")");

// Create the second circle object with radius 5


CircleWithStaticMembers c2 = new CircleWithStaticMembers(5);
c1.radius = 9; // Modify radius of c1

System.out.println("\nAfter creating c2 and modifying c1");


System.out.println("c1: radius (" + c1.radius + ") and number of
Circle objects (" + c1.numberOfObjects + ")");
System.out.println("c2: radius (" + c2.radius + ") and number of
Circle objects (" + c2.numberOfObjects + ")");
System.out.println(CircleWithStaticMembers.getNumberOfObjects());
System.out.println(c1.getArea());
}
}
Advanced Programming
Lab 1

By Eng. Ziad & Eng. Lujaeen


JDK and IDE Download (NetBeans IDE)

Links to use:

• Download the JDK first from here

• Next, Download the IDE (Netbeans) from here


My First Java Program

public class HelloWorld {

public static void main(String[] args) {

System.out.println("Hello Java!");

}
Java Program Demonstrating Different Data Types:

public class DataTypeDemo {


public static void main(String[] args) {
int num = 25; // Integer type
float f = 5.75f; // Float type
char c = 'A'; // Character type
boolean flag = true; // Boolean type
double d = 3.14159; // Double type

// Printing values
System.out.println("Integer: " + num);
System.out.println("Float: " + f);
System.out.println("Character: " + c);
System.out.println("Boolean: " + flag);
System.out.println("Double: " + d);
}
}
Significance of final Keyword in Java:

public class FinalVariableExample {

public static void main(String[] args) {

final int MAX_VALUE = 100;


System.out.println("Max Value: " + MAX_VALUE);
// MAX_VALUE = 200; // This will cause a compilation error
}

}
Your First Java Program

Now try it yourself!


Write a Java program that declares the following variables:
1.A String
2.A float
3.A double
4.A final String
after assigning values to these variables, print the outputs.
Your First Java Program

Solution
public class Section1 {

public static void main(String[] args) {


String Name="Ahmed";
float x= 2.5f;
double y=2.5;
final String message="this message is final";

System.out.print(" My name is "+ Name);


System.out.print("\n the float number is " + x);
System.out.print("\n the double number is "+y);
System.out.print("\n the message says "+message);

}
}
Advanced Programming
Lab 2

By Eng. Ziad & Eng. Lujaeen


How Do You Create Strings?

Using String Literals:


String str1 = "Java";

Using the (new) Keyword :


String str2 = new String("Java");
Strings are immutable:

String name = "Ahmed";


name = "Ali"; // "Ahmed" is still sitting in the memory, and "Ali" gets its own
space!
Common String Methods:

length():
String str = "Hello"; int len = str.length(); // 5 because "Hello" has 5 characters

charAt (index):
String str = "Java"; char ch = str.charAt(1); // 'a' (position 1 is 'a')

substring(start, end):
String str = "Hello"; String sub = str.substring(1, 4);

toUpperCase ():
String str = "java"; String upper = str.toUpperCase(); // "JAVA"

toLowerCase ():
String str = "JAVA"; String lower = str.toLowerCase(); // "java"
Common String Methods:

indexOf ():
First occurrence of a character:
String text = "Java is cool!";
int index = text.indexOf('i');
System.out.println(index); // Output: 5

First occurrence of a substring:


String text = "Java is cool!";
int index = text.indexOf("cool");
System.out.println(index);
Reference Comparison VS Content Comparison

Reference Comparison ==:


String str1 = new String("Java");
String str2 = new String("Java");
System.out.println(str1 == str2); // false (Different objects in Heap)

Content Comparison equals():


String str1 = new String("Java");
String str2 = new String("Java");
System.out.println(str1.equals(str2)); // true (Same content)
concat (), StringBuilder, StringBuffer :

concat ():
String str1 = "Java";
String result = str1.concat(" is cool!");
System.out.println(result); // Output: Java is cool!

StringBuilder:
StringBuilder sb = new StringBuilder();
sb.append("Hello");
sb.append(" World!");
System.out.println(sb.toString()); // "Hello World!"

StringBuffer :(thread safe)


StringBuffer sbf = new StringBuffer();
sbf.append("Hello");
sbf.append(" World!");
System.out.println(sbf.toString()); // "Hello World!"
Now try it yourself!

Write a Java program that:


1. Counts the number of characters in a string.
2. Converts the string to uppercase.
3. Extracts a part of the string.
4. Uses StringBuffer to modify the string.
Sloution
public class StringManipulation {
public static void main(String[] args) {

String text = "Hello, Java!";


int length = text.length(); System.out.println("Number of characters: " + length);

String upperText = text.toUpperCase();


System.out.println("Uppercase: " + upperText);

String subText = text.substring(7, 11);


System.out.println("Substring (7-11): " + subText);

StringBuffer sb = new StringBuffer(text);


sb.append(" Let's learn!");
System.out.println("Modified with StringBuffer: " + sb.toString());
}}
Sloution

Output:
Number of characters: 12
Uppercase: HELLO, JAVA!
Substring (7-11): Java
Modified with StringBuffer: Hello, Java! Let's learn!
Advanced Programming
Lab 3

By Eng. Ziad & Eng. Lujaeen


How to Scan from the user

1.Importing Scanner:
import java.util.Scanner;

2. Creating a Scanner Object:


Scanner scanner = new Scanner(System.in);
Scanner Methods:

Method Description
next() Reads the next word (until space)
nextLine() Reads the entire line
nextInt() Reads an integer
nextLong() Reads a long integer
nextDouble() Reads a double value
nextFloat() Reads a float value
nextBoolean() Reads a boolean (true or false)
nextByte() Reads a byte value
nextShort() Reads a short integer
Example:

Scanner scanner = new Scanner(System.in);

// nextInt() - Reads an integer


System.out.print("Enter your age: ");
int age = scanner.nextInt();

// Consume the leftover newline


scanner.nextLine();

// next() - Reads a single word


System.out.print("Enter your first name: ");
String firstName = scanner.next();

// Consume the leftover newline


scanner.nextLine();
Example:

// nextLine() - Reads the full line


System.out.print("Enter your full address: ");
String address = scanner.nextLine();

// nextBoolean() - Reads a boolean value (true/false)


System.out.print("Do you like programming? (true/false): ");
boolean likesProgramming = scanner.nextBoolean();

// Display the inputs


System.out.println("\n--- User Input Summary ---");
System.out.println("Age: " + age);
System.out.println("First Name: " + firstName);
System.out.println("Full Address: " + address);
System.out.println("Likes Programming: " + likesProgramming);

scanner.close();
} }
Output

Age: 25
First Name: John
Full Address: 123 Main Street, New York
Likes Programming: true
1. Relational (Comparison) Operators

Relational operators are used to compare two values and return a boolean result
(true or false).
1. Relational (Comparison) Operators

public class RelationalOperatorsExample {


public static void main(String[] args) {
int a = 10, b = 5;

System.out.println(a == b); // false


System.out.println(a != b); // true
System.out.println(a > b); // true
System.out.println(a < b); // false
System.out.println(a >= 10); // true
System.out.println(b <= 5); // true
}
}
1. Relational (Comparison) Operators

Logical operators are used to combine multiple conditions and return a boolean
(true or false):

public class LogicalOperatorsExample {


public static void main(String[] args) {
boolean x = true, y = false;

System.out.println(x && y); // false (because one condition is false)


System.out.println(x || y); // true (because one condition is true)
System.out.println(!x); // false (negating true)
System.out.println(!y); // true (negating false)
}
}
Conditional Statements (if, else, switch)

Conditional statements allow the program to execute specific code based on


conditions:

int marks = 85;


if (marks >= 90) {
System.out.println("Grade: A");
} else if (marks >= 75) {
System.out.println("Grade: B");
} else if (marks >= 50) {
System.out.println("Grade: C");
} else {
System.out.println("Fail");
}
Conditional Statements (if, else, switch)

Switch case:
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("Invalid day"); }
Loops (While loop):

Repeats as long as the condition is true:

Example:

int i = 1;
while (i <= 5) {
System.out.println(i);
i++; // Increment i
}

Output:
12345
Loops (for loop):

A for loop is used when the number of iterations is known .

Example:

for (int i = 1; i <= 5; i++) {


System.out.println(i);
}

Output:
12345
Loop Control Statements (Break, Continue statement):

Break: Exits the loop immediately:


for (int i = 1; i <= 5; i++) {
if (i == 3) {
break;
}
System.out.println(i); }

Continue : Skips the current iteration and moves to the next one:
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue;
}
System.out.println(i); }
Nested Loops:

Loops inside another loop:

for (int i = 1; i <= 3; i++) {


for (int j = 1; j <= 3; j++) {
System.out.print(i * j + " ");
}
System.out.println();
}

Output:
123
246
369
1D Arrays:

A 1D array is a linear collection of elements of the same type, stored in


contiguous memory locations:

Declaration & Initialization:


int[] numbers = new int[5]; // Creates an array of size 5

Alternative Way (Declaration & Initialization in One Line):


int[] numbers = {10, 20, 30, 40, 50}; // Directly initializes the array
1D Arrays:

Array elements are accessed using an index, starting from 0, The last element is
at index size - 1.

int[] numbers = {10, 20, 30, 40, 50};


System.out.println(numbers[0]); // 10
System.out.println(numbers[4]); // 50
System.out.println(numbers[5]); // ERROR: IndexOutOfBoundsException
1D Arrays:

Traversing a 1D Array: (Using for loop)

int[] numbers = {10, 20, 30, 40, 50};

for (int i = 0; i < numbers.length; i++) {


System.out.println(numbers[i]);
}
1D Arrays:

Traversing a 1D Array: (Using for loop)

int[] numbers = {10, 20, 30, 40, 50};

for (int i = 0; i < numbers.length; i++) {


System.out.println(numbers[i]);
}
1D Arrays:

Updating Elements:

int[] numbers = {10, 20, 30};


numbers[1] = 50; // Update second element
System.out.println(numbers[1]); // 50

Finding the Length of an Array:


System.out.println(numbers.length); // Output: 3
Common Operations on 1D Arrays

Sum of All Elements:

int[] numbers = {1, 2, 3, 4, 5};

int sum = 0;

for (int i = 0; i < numbers.length; i++) {


sum += numbers[i];
}

System.out.println("Sum: " + sum); // Output: 15


Common Operations on 1D Arrays

Finding the Maximum Element:

int[] numbers = {5, 10, 25, 8, 12};

int max = numbers[0];

for (int i = 1; i < numbers.length; i++) {


if (numbers[i] > max) {
max = numbers[i];
}
}
System.out.println("Maximum: " + max); // Output: 25
2D Arrays

Declaration & Initialization:

int[][] matrix = new int[3][3]; // 3x3 matrix

Alternative Way (Declaration & Initialization in One Line):


int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
2D Arrays

Accessing Elements:

int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
//matrix[rows][columns]
System.out.println(matrix[0][0]); // Output: 1
System.out.println(matrix[1][2]); // Output: 6
System.out.println(matrix[3][1]); // ERROR: IndexOutOfBoundsException
2D Arrays

Traversing a 2D Array:(Using nested for loops)

int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9} };

for (int i = 0; i < matrix.length; i++) { // Rows


for (int j = 0; j < matrix[i].length; j++) { // Columns
System.out.print(matrix[i][j] + " ");
}
System.out.println(); // New line after each row }
2D Arrays

Updating Elements:

matrix[1][1] = 99; // Updating element at row 1, column 1


System.out.println(matrix[1][1]); // Output: 99

Finding the Length of a 2D Array:


System.out.println(matrix.length); // Output: 3, number of rows
System.out.println(matrix[0].length); // Output: 3, number of columns
2D Arrays

Calculating the Sum Using a nested for Loop:


int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9} };

int sum = 0;

for (int i = 0; i < matrix.length; i++) { // Loop through rows


for (int j = 0; j < matrix[i].length; j++) { // Loop through columns
sum += matrix[i][j];
}}
System.out.println("Sum: " + sum); //sum=45
2D Arrays

Finding Maximum Using a nested for Loop:


int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9} };

int max = matrix[0][0];

for (int i = 0; i < matrix.length; i++) { // Loop through rows


for (int j = 0; j < matrix[i].length; j++) { // Loop through columns
if (matrix[i][j] > max) {
max = matrix[i][j];
} } }
System.out.println("Maximum: " + max);
Now try it yourself!

Write a Java program that prompts the user to enter 5 integers , stores them in a
1D array, and then uses a for loop to find and print the largest number in the
array.
Solution!
import java.util.Scanner; // Import Scanner class

public class FindMaxUserInput {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in); // Create Scanner object

// Step 1: Create a 1D array of 5 integers


int[] numbers = new int[5];

// Step 2: Take input from the user


System.out.println("Enter 5 integers:");

for (int i = 0; i < numbers.length; i++) {


numbers[i] = scanner.nextInt(); // Scan each number }
Solution!
// Step 3: Assume the first element is the maximum
int max = numbers[0];

// Step 4: Use a regular for loop to find the largest number


for (int i = 1; i < numbers.length; i++) {
if (numbers[i] > max) {
max = numbers[i]; // Update max if a larger number is found
}
}

// Step 5: Print the maximum number


System.out.println("Maximum: " + max);

scanner.close(); // Close the scanner } }


Advanced Programming
Lab 4

By Eng. Ziad & Eng. Lujaeen


What is a OOP?

OOP is a programing paradigm or a way of thinking about software, based on the


concept of object.

OOP concepts: (to be discussed in the following sections)


1.Encapsulation
2.Inheritance
3.Polymorphism
4.Abstraction
What is an object?

The Object is anything that I need to collect information about in my program.

Exercise: Mention the possible objects that we might need in a Hospital


management system.
What is an object?

Hospital management system

1.Patients (name, ID, age, medical history)


2.Doctors (name, ID, specialization)
3.nurses (name, ID, assigned tasks)
4.medical record (ID, patient, diagnosis)
5.appointment (ID, patient, doctor, date, time)
What is a class?

Class is the blueprint for my objects.

// Defining the Student class


class Student {
String name;
int age;
String grade;

// Main method to test the Student class


public static void main(String[] args) {
Student student1 = new Student();
student1.displayStudent();
}}
What is a class (rectangle class)?

// Defining the Rectangle class


class Rectangle {
private double length;
private double width;

// Getter for length


public double getLength() {
return length;
}

// Setter for length


public void setLength(double length) {
this.length = length;
}
What is a class (rectangle class)?

// Getter for width


public double getWidth() {
return width;
}

// Setter for width


public void setWidth(double width) {
this.width = width;
}

// Method to calculate area


public double calculateArea() {
return length * width;
}
What is a class (rectangle class)?

// Main method to test the Rectangle class


public static void main(String[] args) {
// Creating an object
Rectangle rect1 = new Rectangle();

// initializing values using setters


rect1.setLength(7.5);
rect1.setWidth(4.5);

// Printing values using getter methods


System.out.println("Rectangle - Length: " + rect1.getLength() + ", Width: " +
rect1.getWidth());
System.out.println("Area: " + rect1.calculateArea());
}
}
Constructors:

Constructor is a special methos that is called automatically when the object is


created.

// Constructor with fixed values (default constructor)


public Rectangle() {
this.length = 20; // Default length set to 20
this.width = 5; // Default width set to 5
}
//Constructor that allows users to specify their own values (parameterized
constructor)
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
Constructor vs. Method
Additional Example:

public class Test {

public static void main(String[] args) {

Animal cat = new Animal(“Nola", 2);


cat.showAnimal();

Animal dog = new Animal();


dog.showAnimal();
}
}
Additional Example: ( cont)
public class Animal {
private String name;
private int age;

public Animal(){
this.name = "myDog";
this.age = 1;
}
public Animal(String name, int age){
this.name = name;
this.age = age;
}
public void setName(String name){
this.name = name;
}
public void setAge(int age){
this.age = age;
}
public int getAge(){
return age;
}
public void showAnimal(){
System.out.println(name + " " + age);
}
}
Advanced Programming
Lab 5

By Eng. Ziad & Eng. Lujaeen


What is a static member?

static members belong to the class itself . So you don’t need to create an object
to use them.

• Static variable : shared across all instances.


• Static method : can be called without creating an object.
• You access them with ClassName.staticMember.
What is a static member?

public class Counter {


// static variable - shared across all instances
static int count = 0;

// constructor - every time you make an object, count increases


Counter() {
count++;
System.out.println("Objects created: " + count);
}

// static method - can be called without an object


static void showCount() {
System.out.println("Total objects created: " + count);
}}
What is a static member?

public class Main {


public static void main(String[] args) {
Counter c1 = new Counter(); // count = 1
Counter c2 = new Counter(); // count = 2
Counter c3 = new Counter(); // count = 3

// Call static method directly using the class name


Counter.showCount(); // Output: Total objects created: 3
}
}
What is a static member?

In the previous example:


• count is static , so it’s shared across all Counter objects .
• Every time a new Counter object is created, count increases.
• showCount() is static too, so we can call it without creating a Counter object .
Just use Counter.showCount().
Encapsulation:

We hide variables inside a class using private, and expose them safely through
getters and setters
Encapsulation:

public class Person {


// private = hidden from outside access
private String name;
private int age;

// public getter for name


public String getName() {
return name;
}

// public setter for name


public void setName(String name) {
this.name = name;
}
Encapsulation:

// public getter for age


public int getAge() {
return age;
}

// public setter for age with validation


public void setAge(int age) {
if (age > 0) {
this.age = age;
} else {
System.out.println("Age must be positive!");
}
}
}
Encapsulation:

public class Main {


public static void main(String[] args) {
Person p = new Person();

// Use setters to safely set values


p.setName("Alice");
p.setAge(25);

// Use getters to read values


System.out.println("Name: " + p.getName());
System.out.println("Age: " + p.getAge());

// Try to set invalid age


p.setAge(-5); // Will print "Age must be positive!"
}}
Advanced Programming
Lab 6

By Eng. Ziad & Eng. Lujaeen


What is a Inheritance?

where one class (child/subclass) inherits the properties and behaviors (methods
and fields) of another class (parent/superclass).

Purpose: Promotes code reuse.


What is a inheritance?

public class person {

String name;
int age;

public person() {
}

public person(String name, int age) {


this.name = name;
this.age = age;
}
What is a inheritance?

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public int getAge() {


return age;
}

public void setAge(int age) {


this.age = age;
} }
What is a inheritance?
public class employee extends person{
int salary;
public employee() {
}

public employee(int salary, int age, String name) {


super(name,age);
this.salary = salary;
}

public int getSalary() {


return salary;
}

public void setSalary(int salary) {


this.salary = salary;}
What is a inheritance?

public static void main(String[] args) {


employee e=new employee();
System.out.println(e.getName()); //inherited from super class
System.out.println(e.getSalary());
}
Access modifiers
Advanced Programming
Lab 6

By Eng. Ziad & Eng. Lujaeen


What is abstract classes?

It’s a class that can’t be used to create objects, but it’s meant to be inherited by
other classes, its like a blueprint for other classes.

Because sometimes, we want to define some shared code (like variables or


methods) in a parent class, but also force child classes to implement certain
methods their own way .
What is abstract classes?

public abstract class employee {


String name;
double salary;

public employee() {
}

employee(String name, double salary) {


this.name = name;
this.salary = salary;
}
What is abstract classes?

void displayInfo() {
System.out.println("Name: " + name);
System.out.println("Salary: $" + salary);
}

abstract double calculateBonus();


}
What is abstract classes?

public class developer extends employee{

public developer() {
}

public developer(String name, double salary) {


super(name, salary);
}

@Override
double calculateBonus()
{
return salary*0.2; }}
What is abstract classes?

public class Section9 {

public static void main(String[] args) {


developer d = new developer();
d.name="ahmed";
d.salary=2000;
d.displayInfo();
System.out.println("Bonus: $" + d.calculateBonus());
d.explicitmethod();
}
}
What is interface?

• An interface is like a contract or blueprint that defines what a class must do ,


but not how it does it.
• Interfaces only declare methods.
• They don’t contain method bodies
What is interface?

interface Flyable {
void fly(); // any class that implements this must define fly()
}

class Bird implements Flyable {


public void fly() {
System.out.println("Bird flaps wings and flies!");
}
}
polymorphism

polymorphism means "many forms" .

In Java, polymorphism means that a single action can behave differently based
on the object that performs it.

Two Types of Polymorphism in Java:


1. Compile-Time Polymorphism (aka Method Overloading)
2. Runtime Polymorphism (aka Method Overriding)
polymorphism

polymorphism means "many forms" .

In Java, polymorphism means that a single action can behave differently based
on the object that performs it.

Two Types of Polymorphism in Java:


1. Compile-Time Polymorphism (aka Method Overloading)
2. Runtime Polymorphism (aka Method Overriding)
Method Overloading

public class overload {

// Overloaded methods
int add(int a, int b) {
return a + b;
}

double add(double a, double b) {


return a + b;
}

int add(int a, int b, int c) {


return a + b + c;
}
Method Overloading

// Main method to test


public static void main(String[] args) {
overload obj = new overload();

System.out.println("add(int, int): " + obj.add(3, 4)); // Output: 7


System.out.println("add(double, double): " + obj.add(2.5, 3.5)); // Output: 6.0
System.out.println("add(int, int, int): " + obj.add(1, 2, 3)); // Output: 6
}
}
Method overriding
class Animal {
void makeSound() {
System.out.println("Some generic animal sound");
}
}

class Dog extends Animal {


void makeSound() {
System.out.println("Woof!");
}
}

class Cat extends Animal {


void makeSound() {
System.out.println("Meow!"); }}
Method overriding
class Animal {
void makeSound() {
System.out.println("Some generic animal sound");
}
}

class Dog extends Animal {


void makeSound() {
System.out.println("Woof!");
}
}

class Cat extends Animal {


void makeSound() {
System.out.println("Meow!"); }}
Method overriding

public static void main(String[] args) {


Animal a1 = new Dog();
Animal a2 = new Cat();

a1.makeSound(); // Woof!
a2.makeSound(); // Meow!
}
INTRODUCTION TO OOP

Objective:

•Know the difference between structured programming


and OOP
• Know basic terminology in OOP
• Know the importance of OOP
• Class Vs Object

1
STRUCTURED vs. OO PROGRAMMING

STRUCTURED PROGRAMMING:

MAIN PROGRAM GLOBAL DATA

FUNCTION FUNCTION 2 FUNCTION 3


1

FUNCTION 4 FUNCTION 5

2
Structured Programming

• Using function
• Is a list of instructions that execute one after
the other starting from the top of the line.
• Function & program is divided into modules
• Every module has its own data and function
which can be called by other modules.

3
public class SimpleProgram {

// Function to add two numbers


public static int add(int a, int b) {
return a + b;
}

// Function to subtract two numbers


public static int subtract(int a, int b) {
return a - b;
}

// Function to multiply two numbers


public static int multiply(int a, int b) {
return a * b;
Example of
}
Structured
// Function to display the result
public static void displayResult(int result) {
System.out.println("The result is: " + result);
Programming
}

public static void main(String[] args) {


int num1 = 10;
int num2 = 5;

// Performing operations
int sum = add(num1, num2);
int difference = subtract(num1, num2);
int product = multiply(num1, num2);

// Displaying results
displayResult(sum);
displayResult(difference);
4
Structured Programming
Advantages:-

•Best for general-purpose programming.


•It is easy to trace the flow of the program.

Disadvantages:-

•The data is exposed (security issues).


•Difficult to solve real-world problems.

5
OBJECT ORIENTED PROGRAMMING

Object 2
Object 1

Data Data

Function Function

Object 3
Int x
Data

Function

6
OBJECT ORIENTED
PROGRAMMING
• Object-Oriented Programming is one of the most
popular approaches to solve a programming problem,
it is done by creating objects.

An object has two characteristics:-


• Attributes
• Behaviors

• For example, an object could represent an employee


with attributes such as name, title, experience, etc.,
with behaviors like working, on-leave,
underperformed, etc., 7
Basic terminology

•object
- usually a person, place or thing (a noun)
•method
- an action performed by an object (a verb)
•attribute
- description of objects in a class
•class
- a category of similar objects (such as automobiles)
- does not hold any values of the object’s attributes

8
Why OOP?

• Save development time (and cost) by reusing code


•once an object class is created it can be used in
other applications
• Easier debugging
•classes can be tested independently
•reused objects have already been tested

9
Example for attributes and methods
Attributes: Methods:
• manufacturer’s • Define data items
name (specify
• model name manufacturer’s
• year made name, model,
• color year, etc.)
• number of doors • Change a data
item (color,
• size of engine
engine, etc.)
• etc.
• Display data items
• Calculate cost
• etc. 10
Class and Objects
• In Java, everything is an object. A class is a blueprint
for the object.
• To create an object, we require a model or plan or
blueprint which is nothing but class.
• For example, you are creating a vehicle according to
the Vehicle blueprint (template). The plan contains all
dimensions and structure.
• Based on these descriptions, we can construct a car,
truck, bus, or any vehicle. Here, a car, truck, bus are
objects of Vehicle class

11
Class and Objects

• A class contains the properties


(attribute) and action
(behavior) of the object.

• Properties represent variables,


and the methods represent
actions. Hence class includes
both variables and methods.

12

You might also like