java mug2
java mug2
Lab 8
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;
import java.io.FileWriter;
import java.io.IOException;
import java.io.File;
The JDK is the most important tool. It contains everything needed to write, compile, and run Java
programs.
It also includes the JVM (Java Virtual Machine) to run Java programs on any computer.
- What is it?
An IDE (Integrated Development Environment) is a special software that helps you write, test, and run
Java programs easily.
If you want to create Java applications with buttons, windows, and graphics (GUI), you need Scene
Builder.
JavaFX is a set of tools that helps you create modern graphical applications with Java.
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).
Git is a tool used to track changes in your code and work on projects with a team.
Maven and Gradle help manage dependencies (extra tools & libraries) that Java projects need.
If you build large projects, you will need Maven or Gradle to manage external libraries.
Recommended:
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
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.
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: return
mov rax, 1
mov rdi, 1
lea rsi, [Hello_Java]
mov rdx, 13
syscall
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)
This was useful for external APIs, security libraries, and cryptography extensions.
Where is it Now?
It loads classes from the directories and JAR files specified in the CLASSPATH.
Loading Steps
In Java's class loading process, the preparation phase only assigns default values to static
variables.
Parent.display()
Child.show()
2. During 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.
class Example {
static int count = 10; // Stored in Method Area
}
void display() {
System.out.println("Hello");
}
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.
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.
int square(int x) {
return x * x;
}
int result = square(5); // Function call
Converts the optimized intermediate representation (IR) into native machine code for the
CPU.
return a + b;
Profiler
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 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);
Example 6
1. Valid Identifiers:
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 (-)
int a=35,b=12,d=13;
char valC=(char)(a+b+d);
System.out.println("valC = "+a);
Substring examples
a) compareTo()
b) equals()
c) ==
d) substring()
a) true
b) false
c) Compilation error
d) Runtime exception
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) It extracts "Hello"
b) It extracts "World"
c) It extracts "Hello World"
d) It causes an error
a) 1stValue
b) first-value
c) firstValue
d) first value
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
Q2.2 Answer
Q2.3 Answer
scanner.close();
int sum = 0;
int n = 2;
for (int i = 1; i <= n; i++) {
sum += i;
}
System.out.println("Sum = " + sum);
}
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
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);
}
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);
}
Notes :
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);
}
}
}
}
No explicit name.
Created and used in a single statement.
Useful for one-time use cases.
Cannot be reused after method execution.
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}); }
}
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
A) int arr[5];
A) null
B) 0
C) 1
D) undefined
A) 10
B) 100
C) Compilation error
D) Runtime error
A) 1
B) 5
C) Compilation error
D) Runtime error
A) 0
B) Compilation error
C) Runtime error
D) NullPointerException
A) 10
B) 20
C) 30
D) 40
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?
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.
17. What happens during the "resolution" phase of the class loading process?
18. Fix the error in the following code to make it print the correct sum of even numbers in
the array:
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
2. Abstraction of Complexity
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.
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 CircleWithPrivateDataFields() {
numberOfObjects++;
}
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);
Example 2:
public class Person {
// Private fields (encapsulation)
private String name;
private int age;
// File: Person.java
Array of objects
Remember:
Array of objects:
String name;
int age;
// Constructor
public Student(String name, int age) {
this.name = name;
this.age = age;
}
}
Java Classes vs C/C++ Structs
Purpose Used for creating objects with behavior Used to group data together
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)
Default Member
Private by default (unless specified) Public by default (in C)
Access
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
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.
// 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
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
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() {
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.
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
}
Links to use:
System.out.println("Hello Java!");
}
Java Program Demonstrating Different Data Types:
// 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:
}
Your First Java Program
Solution
public class Section1 {
}
}
Advanced Programming
Lab 2
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
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!"
Output:
Number of characters: 12
Uppercase: HELLO, JAVA!
Substring (7-11): Java
Modified with StringBuffer: Hello, Java! Let's learn!
Advanced Programming
Lab 3
1.Importing Scanner:
import java.util.Scanner;
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.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
Logical operators are used to combine multiple conditions and return a boolean
(true or false):
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):
Example:
int i = 1;
while (i <= 5) {
System.out.println(i);
i++; // Increment i
}
Output:
12345
Loops (for loop):
Example:
Output:
12345
Loop Control Statements (Break, Continue statement):
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:
Output:
123
246
369
1D Arrays:
Array elements are accessed using an index, starting from 0, The last element is
at index size - 1.
Updating Elements:
int sum = 0;
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
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9} };
Updating Elements:
int sum = 0;
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 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
static members belong to the class itself . So you don’t need to create an object
to use them.
We hide variables inside a class using private, and expose them safely through
getters and setters
Encapsulation:
where one class (child/subclass) inherits the properties and behaviors (methods
and fields) of another class (parent/superclass).
String name;
int age;
public person() {
}
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.
public employee() {
}
void displayInfo() {
System.out.println("Name: " + name);
System.out.println("Salary: $" + salary);
}
public developer() {
}
@Override
double calculateBonus()
{
return salary*0.2; }}
What is abstract classes?
interface Flyable {
void fly(); // any class that implements this must define fly()
}
In Java, polymorphism means that a single action can behave differently based
on the object that performs it.
In Java, polymorphism means that a single action can behave differently based
on the object that performs it.
// Overloaded methods
int add(int a, int b) {
return a + b;
}
a1.makeSound(); // Woof!
a2.makeSound(); // Meow!
}
INTRODUCTION TO OOP
Objective:
1
STRUCTURED vs. OO PROGRAMMING
STRUCTURED PROGRAMMING:
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 {
// 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:-
Disadvantages:-
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.
•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?
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
12