Uploaded by hamzashahzad2600

OOP manual

advertisement
CS-162 Object Oriented Programming
Department of Computer Science
First Semester
Submitted by:
Hamza Shahzad
Roll no.:
22-CS-19
Submitted to:
Mr. Asim Mubarak
S.No LAB
No
TOPIC
DATE
MARKS
LAB 01
How to install java compiler
To install the Java JDK (Java Development Kit) and compiler on your PC, follow these steps:
1. Visit the official Oracle website for Java SE downloads at:
https://www.oracle.com/java/technologies/javase-jdk11-downloads.html
2. Accept the license agreement for the version of the JDK you want to download (e.g., JDK 11).
3. Choose the appropriate JDK package for your operating system (Windows, macOS, or Linux)
and download it.
4. Once the download is complete, run the installer program.
5. Follow the installation wizard's instructions to complete the installation. Make sure to specify
the desired installation directory if prompted.
6. After the installation is finished, open a terminal or command prompt and verify the
installation by typing the following command: `java -version`. This should display the installed
Java version if the installation was successful.
To compile and run Java programs, you can use an Integrated Development Environment (IDE)
like Eclipse, IntelliJ IDEA, or NetBeans. Alternatively, you can compile and run Java programs
from the command line using the `javac` compiler and `java` command.
Run our first program of java of printing hello world on screen
To run a Java program that prints "Hello, World!" using Notepad and the terminal, follow these
steps:
1. Open Notepad or any text editor and create a new file.
2. Type the following Java code into the file:
3. Save the file with a `.java` extension, for example, `HelloWorld.java`. Make sure to save it in a
directory of your choice.
4. Open the terminal or command prompt.
5. Navigate to the directory where you saved the `HelloWorld.java` file using the `cd` command.
For example, if you saved the file on the desktop, you would use the command `cd Desktop`.
6. Once you are in the correct directory, compile the Java program by entering the following
command:
7. If there are no errors, the Java compiler will generate a `HelloWorld.class` file in the same
directory.
8. Finally, run the compiled program by typing the following command:
9. The program will execute, and you should see the output `Hello, World!` printed in the
terminal.
Congratulations! You have successfully run your first Java program using Notepad and the
terminal.
LAB 02
********
The Complete Reference JAVA
Programs from book The Complete Reference JAVA
Program no. 1
class number1 {
public static void main(String args[]) {
int num; // this declares a variable called num
num = 100; // this assigns num the value 100
System.out.println("This is num: " + num);
num = num * 2;
System.out.print("The value of num * 2 is ");
System.out.println(num);
}
}
Output
'number1'
This is num: 100
The value of num * 2 is 200
Explanation
1.
2.
3.
4.
First, we initialize a integer
Then, print it on screen
Multiply it and store it in same variable
At last, print string and value individually on screen
Program no. 2
/*
Demonstrate the if.
Call this file "IfSample.java".
*/
class IfSample {
public static void main(String args[]) {
int x, y;
x = 10;
y = 20;
if(x < y) System.out.println("x is less than y");
x = x * 2;
if(x == y) System.out.println("x now equal to y");
x = x * 2;
if(x > y) System.out.println("x now greater than y");
}
}
Output
x is less than y
x now equal to y
x now greater than y
Explanation
1. Initialize 2 variables with 10 and 20
2. Using if to condition x<y and then x==y and then x>y
3. In the body of if we print the string to justify the condition
Program no. 3
class ForTest {
public static void main(String args[]) {
int x;
for(x = 0; x<10; x = x+1)
System.out.println("This is x: " + x);
}
}
Output
This is x: 0
This is x: 1
This is x: 2
This is x: 3
This is x: 4
This is x: 5
This is x: 6
This is x: 7
This is x: 8
This is x: 9
Explanation
1.
2.
3.
4.
We use loop in java in this program for loop first initialize the variable
Then use condition, if condition is true then use the body of the loop is execute
If false body will be skipped
This loop execute 10 time from 0 to 9
Program no. 4
/*
Demonstrate a block of code.
Call this file "BlockTest.java"
*/
class BlockTest {
public static void main(String args[]) {
int x, y;
y = 20;
// the target of this loop is a block
for(x = 0; x<10; x++) {
System.out.println("This is x: " + x);
System.out.println("This is y: " + y);
y = y - 2;
}
}
}
Output
This is x: 0
This is y: 20
This is x: 1
This is y: 18
This is x: 2
This is y: 16
This is x: 3
This is y: 14
This is x: 4
This is y: 12
This is x: 5
This is y: 10
This is x: 6
This is y: 8
This is x: 7
This is y: 6
This is x: 8
This is y: 4
This is x: 9
This is y: 2
Explanation
1.
2.
3.
4.
5.
Define two variable and initialize one of them by 20
Then we use for loop
In the body of loop we print the value to x and y
Then we decrement in y by 2 each time
The loop execute 10 time
Program no. 5
// Compute distance light travels using long variables.
class Light {
public static void main(String args[]) {
int lightspeed;
long days;
long seconds;
long distance;
// approximate speed of light in miles per second
lightspeed = 186000;
days = 1000; // specify number of days here
seconds = days * 24 * 60 * 60; // convert to seconds
distance = lightspeed * seconds; // compute distance
System.out.print("In " + days);
System.out.print(" days light will travel about ");
System.out.println(distance + " miles.");
}
}
Output
In 1000 days light will travel about 16070400000000 miles.
Explanation
1. In this program we use long variable
2. We initialize all variable with specific value
3. And print the variable and string as in ouput
Program no. 6
// Compute the area of a circle.
class Area {
public static void main(String args[]) {
double pi, r, a;
r = 10.8; // radius of circle
pi = 3.1416; // pi, approximately
a = pi * r * r; // compute area
System.out.println("Area of circle is " + a);
}
}
Output
Area of circle is 366.436224
Explanation
1. We initialize the double variable to specific value
2. And then find the area of it using formula
3. And print it on screen
Program no. 7
// Demonstrate char data type.
class CharDemo {
public static void main(String args[]) {
char ch1, ch2;
ch1 = 88; // code for X
ch2 = 'Y';
System.out.print("ch1 and ch2: ");
System.out.println(ch1 + " " + ch2);
}
}
Output
ch1 and ch2: X Y
Explanation
1. Here we use char variable
2. And print the print it on the screen
Program no. 8
// char variables behave like integers.
class CharDemo2 {
public static void main(String args[]) {
char ch1;
ch1 = 'X';
System.out.println("ch1 contains " + ch1);
ch1++; // increment ch1
System.out.println("ch1 is now " + ch1);
}
}
Output
ch1 contains X
ch1 is now Y
Explanation
1.
2.
3.
4.
Store a char string
Print it
Then increment in it
And show the result
Program no. 9
// Demonstrate boolean values.
//THE JAVA LANGUAGE
class BoolTest {
public static void main(String args[]) {
boolean b;
b = false;
System.out.println("b is " + b);
b = true;
System.out.println("b is " + b);
// a boolean value can control the if statement
if(b) System.out.println("This is executed.");
b = false;
if(b) System.out.println("This is not executed.");
// outcome of a relational operator is a boolean value
System.out.println("10 > 9 is " + (10 > 9));
}
}
Output
b is false
b is true
This is executed.
10 > 9 is true
Explanation
1. We use Boolean function in this example
2. We use the variable in if and when the value become true the if execute
Program no. 10
// Demonstrate dynamic initialization.
class DynInit {
public static void main(String args[]) {
double a = 3.0, b = 4.0;
// c is dynamically initialized
double c = Math.sqrt(a * a + b * b);
System.out.println("Hypotenuse is " + c);
}
}
Output
Hypotenuse is 5.0
Explanation
1. Two variables a and b are assigned the values 3.0 and 4.0 respectively.
2. The variable c is dynamically initialized using the square root of the sum of the squares
of a and b.
3. The calculated hypotenuse value, c, is printed as output.
Program no. 11
// Demonstrate block scope.
class Scope {
public static void main(String args[]) {
int x; // known to all code within main
x = 10;
if(x == 10) { // start new scope
int y = 20; // known only to this block
// x and y both known here.
System.out.println("x and y: " + x + " " + y);
x = y * 2;
}
// y = 100; // Error! y not known here
// x is still known here.
System.out.println("x is " + x);
}
}
Output
x and y: 10 20
x is 40
Explanation
1. The variable x is declared and assigned the value 10.
2. If x is equal to 10, a new block scope begins.
3. Inside the block, the variable y is declared and assigned the value 20.
4. The values of x and y are printed.
5. x is updated to y multiplied by 2.
6. The block ends, and y is no longer known.
7. An attempt to access y outside the block would result in an error.
8. The final value of x is printed.
Program no. 12
// Demonstrate lifetime of a variable.
class LifeTime {
public static void main(String args[]) {
int x;
for(x = 0; x < 3; x++) {
int y = -1; // y is initialized each time block is entered
System.out.println("y is: " + y); // this always prints -1
y = 100;
System.out.println("y is now: " + y);
}
}
}
Output
y is: -1
y is now: 100
y is: -1
y is now: 100
y is: -1
y is now: 100
Explanation
1. An integer variable x is declared.
2. A for loop iterates three times.
3. Inside the loop, an integer variable y is declared and initialized to -1.
4. The value of y is printed as -1.
5. y is updated to 100.
6. The updated value of y is printed as 100.
7. The loop continues until completion.
Program no. 13
// Demonstrate casts.
class Conversion {
public static void main(String args[]) {
byte b;
int i = 257;
double d = 323.142;
System.out.println("\nConversion of int to byte.");
b = (byte) i;
System.out.println("i and b " + i + " " + b);
System.out.println("\nConversion of double to int.");
i = (int) d;
System.out.println("d and i " + d + " " + i);
System.out.println("\nConversion of double to byte.");
b = (byte) d;
System.out.println("d and b " + d + " " + b);
}
}
Output
Conversion of int to byte.
i and b 257 1
Conversion of double to int.
d and i 323.142 323
Conversion of double to byte.
d and b 323.142 67
Explanation
1. A byte variable b, an int variable i, and a double variable d are declared.
2. i is assigned the value 257, and d is assigned the value 323.142.
3. The value of i is cast to a byte and assigned to b. The values of i and b are printed.
4. d is cast to an int and assigned to i. The values of d and i are printed.
5. d is cast to a byte and assigned to b. The values of d and b are printed.
Program no. 14
// Demonstrate a one-dimensional array.
class Array {
public static void main(String args[]) {
int month_days[];
month_days = new int[12];
month_days[0] = 31;
month_days[1] = 28;
month_days[2] = 31;
month_days[3] = 30;
month_days[4] = 31;
month_days[5] = 30;
month_days[6] = 31;
month_days[7] = 31;
month_days[8] = 30;
month_days[9] = 31;
month_days[10] = 30;
month_days[11] = 31;
System.out.println("April has " + month_days[3] + " days.");
}
}
Output
April has 30 days.
Explanation
1. An integer array month_days is declared with a size of 12.
2. The elements of the month_days array are assigned values representing the number of
days in each corresponding month.
3. The number of days in April is printed by accessing the element at index 3 using
month_days[3].
Program no. 15
// An improved version of the previous program.
class AutoArray {
public static void main(String args[]) {
int month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31,
30, 31 };
System.out.println("April has " + month_days[3] + " days.");
}
}
Output
April has 30 days.
Explanation
1. The class AutoArray is defined, which contains the main method. The main method is
the entry point of the program.
2. An integer array month_days is declared and initialized in a single line using curly braces
and comma-separated values. This initializes the array with 12 elements representing
the number of days in each month.
3. The number of days in April is printed by accessing the element at index 3 using
month_days[3]. The output is displayed as "April has [number of days] days."
Program no. 16
// Demonstrate a two-dimensional array.
class TwoDArray {
public static void main(String args[]) {
int twoD[][] = new int[4][5];
int i, j, k = 0;
for (i = 0; i < 4; i++)
for (j = 0; j < 5; j++) {
twoD[i][j] = k;
k++;
}
for (i = 0; i < 4; i++) {
for (j = 0; j < 5; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
}
}
}
Output
01234
56789
10 11 12 13 14
15 16 17 18 19
Explanation
1. A two-dimensional integer array twoD is declared and initialized with dimensions 4 rows
and 5 columns.
2. Values are assigned to each element of the twoD array in a sequential manner.
3. The elements of the twoD array are printed in a tabular format
Program no. 17
// Manually allocate differing size second dimensions.
class TwoDAgain {
public static void main(String args[]) {
int twoD[][] = new int[4][];
twoD[0] = new int[1];
twoD[1] = new int[2];
twoD[2] = new int[3];
twoD[3] = new int[4];
int i, j, k = 0;
for(i=0; i<4; i++)
for(j=0; j<i+1; j++) {
twoD[i][j] = k;
k++;
}
for(i=0; i<4; i++) {
for(j=0; j<i+1; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
}
}
}
Output
0
12
345
6789
Explanation
1. A two-dimensional integer array twoD is declared with 4 rows.
2. Different-sized second dimensions are manually allocated to each row of the twoD
array.
3. Values are assigned to each element of the twoD array in a sequential manner.
4. The elements of the twoD array are printed in a tabular format.
Program no. 18
// Initialize a two-dimensional array.
class Matrix {
public static void main(String args[])
double m[][] = {
{ 0 * 0, 1 * 0, 2 * 0, 3 *
{ 0 * 1, 1 * 1, 2 * 1, 3 *
{ 0 * 2, 1 * 2, 2 * 2, 3 *
{ 0 * 3, 1 * 3, 2 * 3, 3 *
};
int i, j;
for (i = 0; i < 4; i++) {
for (j = 0; j < 4; j++)
System.out.print(m[i][j] +
System.out.println();
}
}
}
Output
0.0 0.0 0.0 0.0
0.0 1.0 2.0 3.0
0.0 2.0 4.0 6.0
{
0
1
2
3
},
},
},
}
" ");
0.0 3.0 6.0 9.0
Explanation
1. The class Matrix is defined, which contains the main method. The main method is the
entry point of the program.
2. A two-dimensional double array m is declared and initialized in a single line using curly
braces and comma-separated values. The array represents a 4x4 matrix.
3. Each element of the m array is initialized with the product of its row index and column
index.
4. Two integer variables i and j are declared.
5. Two nested for loops are used to iterate through the elements of the m array. The outer
loop iterates over the rows, and the inner loop iterates over the columns.
6. Inside the nested loops, each element of the m array is printed using System.out.print(),
followed by a space.
7. After printing each row, System.out.println() is used to move to the next line
Program no. 19
// Demonstrate a three-dimensional array.
class threeDMatrix {
public static void main(String args[]) {
int threeD[][][] = new int[3][4][5];
int i, j, k;
for (i = 0; i < 3; i++)
for (j = 0; j < 4; j++)
for (k = 0; k < 5; k++)
threeD[i][j][k] = i * j * k;
for (i = 0; i < 3; i++) {
for (j = 0; j < 4; j++) {
for (k = 0; k < 5; k++)
System.out.print(threeD[i][j][k] + " ");
System.out.println();
}
System.out.println();
}
}
}
Output
00000
00000
00000
00000
00000
01234
02468
0 3 6 9 12
00000
02468
0 4 8 12 16
0 6 12 18 24
Explanation
1. A three-dimensional integer array threeD is declared and initialized with dimensions 3,
4, and 5.
2. Values are assigned to each element of the threeD array based on the product of its
indices.
3. The elements of the threeD array are printed in a structured format using nested loops.
4. Each slice of the third dimension is separated by an empty line.
Program no. 20
// Demonstrate the basic arithmetic operators.
class BasicMath {
public static void main(String args[]) {
// arithmetic using integers
System.out.println("Integer Arithmetic");
int a = 1 + 1;
int b = a * 3;
int c = b / 4;
int d = c - a;
int e = -d;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
System.out.println("e = " + e);
// arithmetic using doubles
System.out.println("\nFloating Point Arithmetic");
double da = 1 + 1;
double db = da * 3;
double dc = db / 4;
double dd = dc - a;
double de = -dd;
System.out.println("da = " + da);
System.out.println("db = " + db);
System.out.println("dc = " + dc);
System.out.println("dd = " + dd);
System.out.println("de = " + de);
}
}
Output
Integer Arithmetic
a=2
b=6
c=1
d = -1
e=1
Floating Point Arithmetic
da = 2.0
db = 6.0
dc = 1.5
dd = -0.5
de = 0.5
Explanation
1. The class BasicMath is defined, which contains the main method. The main method is
the entry point of the program.
2. Integer arithmetic:

Integer variables a, b, c, d, and e are declared and assigned values based on
arithmetic operations using integers.

The values of a, b, c, d, and e are printed using System.out.println().
3. Floating-point arithmetic:

Double variables da, db, dc, dd, and de are declared and assigned values based
on arithmetic operations using doubles.

The values of da, db, dc, dd, and de are printed using System.out.println()
Program no. 21
// Demonstrate the % operator.
class Modulus {
public static void main(String args[]) {
int x = 42;
double y = 42.25;
System.out.println("x mod 10 = " + x % 10);
System.out.println("y mod 10 = " + y % 10);
}
}
Output
x mod 10 = 2
y mod 10 = 2.25
Explanation
1. The class Modulus is defined, which contains the main method. The main method is the
entry point of the program.
2. Integer and double variables x and y are declared and assigned values.
3. The remainder of dividing x by 10 is calculated using the % operator and printed using
System.out.println().
4. The remainder of dividing y by 10 is calculated using the % operator and printed using
System.out.println().
Program no. 22
// Demonstrate several assignment operators.
class OpEquals {
public static void main(String args[]) {
int a = 1;
int b = 2;
int c = 3;
a += 5;
b *= 4;
c += a * b;
c %= 6;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
}
}
Output
a=6
b=8
c=3
Explanation
1. The class OpEquals is defined, which contains the main method. The main method is
the entry point of the program.
2. Integer variables a, b, and c are declared and assigned initial values.
3. The += assignment operator is used to add 5 to the value of a.
4. The *= assignment operator is used to multiply the value of b by 4.
5. The value of a is multiplied by the value of b, and the result is added to the value of c
using the += assignment operator.
6. The %= assignment operator is used to assign the remainder of dividing c by 6 to c.
7. The values of a, b, and c are printed using System.out.println().
Program no. 23
// Demonstrate ++.
class IncDec {
public static void main(String args[]) {
int a = 1;
int b = 2;
int c;
int d;
c = ++b;
d = a++;
c++;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
}
}
Output
a=2
b=3
c=4
d=1
Explanation
1. Integer variables a, b, c, and d are declared and assigned initial values.
2. The ++ operator is used as a prefix on b, incrementing its value and assigning it to c.
3. The ++ operator is used as a postfix on a, assigning its value to d and then incrementing
a.
4. The value of c is incremented by 1 using the ++ operator.
5. The values of a, b, c, and d are printed.
Program no. 24
// Demonstrate the bitwise logical operators.
class BitLogic {
public static void main(String args[]) {
String binary[] = {
"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111",
"1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"
};
int a = 3; // 0 + 2 + 1 or 0011 in binary
int b = 6; // 4 + 2 + 0 or 0110 in binary
int c = a | b;
int d = a & b;
int e = a ^ b;
int f = (~a & b) | (a & ~b);
int g = ~a & 0x0f;
System.out.println(" a = " + binary[a]);
System.out.println(" b = " + binary[b]);
System.out.println(" a|b = " + binary[c]);
System.out.println(" a&b = " + binary[d]);
System.out.println(" a^b = " + binary[e]);
System.out.println("~a&b|a&~b = " + binary[f]);
System.out.println(" ~a = " + binary[g]);
}
}
Output
a = 0011
b = 0110
a|b = 0111
a&b = 0010
a^b = 0101
~a&b|a&~b = 0101
~a = 1100
Explanation
1. The BitLogic class defines the main method as the entry point of the program.
2. An array named binary is initialized with binary representations of numbers from 0 to
15.
3. Integer variables a and b are declared and assigned values.
4. The bitwise OR operator | is used to compute the bitwise OR of a and b, storing the
result in c.
5. The bitwise AND operator & is used to compute the bitwise AND of a and b, storing the
result in d.
6. The bitwise XOR operator ^ is used to compute the bitwise XOR of a and b, storing the
result in e.
7. The expression (~a & b) | (a & ~b) is used to perform a combination of bitwise NOT,
bitwise AND, and bitwise OR operations, storing the result in f.
8. The bitwise NOT operator ~ is used to compute the bitwise complement of a and store it
in g.
9. The values of a, b, c, d, e, f, and g are printed along with their binary representations
using System.out.println().
Program no. 25
// Left shifting a byte value.
// THE JAVA LANGUAGE
class ByteShift {
public static void main(String args[]) {
byte a = 64, b;
int i;
i = a << 2;
b = (byte) (a << 2);
System.out.println("Original value of a: " + a);
System.out.println("i and b: " + i + " " + b);
}
}
Output
Original value of a: 64
i and b: 256 0
Explanation
1. A byte variable a is declared and assigned the value 64.
2. An int variable i is declared and assigned the result of left shifting a by 2 bits.
3. A byte variable b is declared and assigned the result of left shifting a by 2 bits, with a
cast to byte.
4. The original value of a and the values of i and b are printed.
Program no. 26
// Left shifting as a quick way to multiply by 2.
class MultByTwo {
public static void main(String args[]) {
int i;
int num = 0xFFFFFFE;
for (i = 0; i < 4; i++) {
num = num << 1;
System.out.println(num);
}
}
}
Output
536870908
1073741816
2147483632
-32
Explanation
1. An int variable num is initialized with the value 0xFFFFFFE.
2. In a loop that iterates 4 times, the value of num is left-shifted by 1 bit using <<.
3. The updated value of num is printed.
Program no. 27
// Demonstrate if-else-if statements.
class IfElse {
public static void main(String args[]) {
int month = 4; // April
String season;
if (month == 12 || month == 1 || month == 2)
season = "Winter";
else if (month == 3 || month == 4 || month == 5)
season = "Spring";
else if (month == 6 || month == 7 || month == 8)
season = "Summer";
else if (month == 9 || month == 10 || month == 11)
season = "Autumn";
else
season = "Bogus Month";
System.out.println("April is in the " + season + ".");
}
}
Output
April is in the Spring.
Explanation
1. An integer variable month is initialized with the value 4, representing the month of
April.
2. A string variable season is declared to store the corresponding season.
3. Using if-else-if statements, the code checks the value of month and assigns the
appropriate season to the season variable.
4. If month is 12, 1, or 2, it is considered winter. If it is 3, 4, or 5, it is considered spring. If it
is 6, 7, or 8, it is considered summer. If it is 9, 10, or 11, it is considered autumn.
Otherwise, it is considered a "Bogus Month."
5. The final determined season is printed as part of the output.
Program no. 28
// A simple example of the switch.
// THE JAVA LANGUAGE
class SampleSwitch {
public static void main(String args[]) {
for (int i = 0; i < 6; i++)
switch (i) {
case 0:
System.out.println("i is
break;
case 1:
System.out.println("i is
break;
case 2:
System.out.println("i is
break;
case 3:
System.out.println("i is
break;
default:
System.out.println("i is
}
}
}
zero.");
one.");
two.");
three.");
greater than 3.");
Output
i is zero.
i is one.
i is two.
i is three.
i is greater than 3.
i is greater than 3.
Explanation
1. The code defines a class named SampleSwitch with a main method.
2. The main method contains a for loop that iterates from 0 to 5.
3. Inside the loop, a switch statement checks the value of the loop variable i.
4. Based on the value of i, different messages are printed using System.out.println.
5. The program output displays the messages corresponding to the values of i.
Example no. 29
// In a switch, break statements are optional.
class MissingBreak {
public static void main(String args[]) {
for (int i = 0; i < 12; i++)
switch (i) {
case 0:
case 1:
case 2:
case 3:
case 4:
System.out.println("i is less than 5");
break;
case 5:
case 6:
case 7:
case 8:
case 9:
System.out.println("i is less than 10");
break;
default:
System.out.println("i is 10 or more");
}
}
}
Output
i is less than 5
i is less than 5
i is less than 5
i is less than 5
i is less than 5
i is less than 10
i is less than 10
i is less than 10
i is less than 10
i is less than 10
i is 10 or more
i is 10 or more
Explanation
1. Declare and define a class named MissingBreak.
2. Inside the class, define the main method.
3. Initialize an integer variable i with a value of 0.
4. Start a for loop that iterates as long as i is less than 12.
5. Within the loop, evaluate the value of i using a switch statement.

If i is 0, 1, 2, 3, or 4, print "i is less than 5".

If i is 5, 6, 7, 8, or 9, print "i is less than 10".

For any other value of i, print "i is 10 or more".
6. Since there are no break statements after each case, the execution will fall through to
the next case if a match is found.
7. Repeat the loop until i reaches 12.
8. The program execution completes.
Example no. 30
// An improved version
class Switch {
public static void
int month = 4;
String season;
switch (month)
case 12:
case 1:
case 2:
season
break;
case 3:
case 4:
of the season program.
main(String args[]) {
{
= "Winter";
case 5:
season
break;
case 6:
case 7:
case 8:
season
break;
case 9:
case 10:
case 11:
season
break;
default:
season
= "Spring";
= "Summer";
= "Autumn";
= "Bogus Month";
}
System.out.println("April is in the " + season + ".");
}
}
Output
April is in the Spring.
Explanation
1. Declare and define a class named Switch.
2. Inside the class, define the main method.
3. Initialize an integer variable month with a value of 4.
4. Declare a string variable season.
5. Use a switch statement to evaluate the value of month.

If month is 12, 1, or 2, assign the string "Winter" to the season variable and
break out of the switch statement.

If month is 3, 4, or 5, assign the string "Spring" to the season variable and break
out of the switch statement.

If month is 6, 7, or 8, assign the string "Summer" to the season variable and
break out of the switch statement.

If month is 9, 10, or 11, assign the string "Autumn" to the season variable and
break out of the switch statement.

For any other value of month, assign the string "Bogus Month" to the season
variable.
6. Print the message "April is in the " concatenated with the value of the season variable.
7. The program execution completes.
Example no. 31
// Demonstrate the while loop.
class While {
public static void main(String args[]) {
int n = 10;
while (n > 0) {
System.out.println("tick " + n);
n--;
}
}
}
Output
tick 10
tick 9
tick 8
tick 7
tick 6
tick 5
tick 4
tick 3
tick 2
tick 1
Explanation
1. Declare and define a class named While.
2. Inside the class, define the main method.
3. Initialize an integer variable n with a value of 10.
4. Enter a while loop with the condition n > 0.
5. Print the message "tick" concatenated with the value of n.
6. Decrement the value of n by 1.
7. Repeat steps 5 and 6 until the condition n > 0 becomes false.
8. The program execution completes.
Example no. 32
// The target of a loop can be empty.
class NoBody {
public static void main(String args[]) {
int i, j;
i = 100;
j = 200;
// find midpoint between i and j
while (++i < --j)
; // no body in this loop
System.out.println("Midpoint is " + i);
}
}
Output
Midpoint is 150
Explanation
1. Declare and define a class named NoBody.
2. Inside the class, define the main method.
3. Declare and initialize two integer variables i and j with values 100 and 200, respectively.
4. Enter a while loop with the condition ++i < --j.
5. Since the loop body is empty, there is a semicolon (;) placed after the loop.
6. The while loop continues to increment i and decrement j until the condition ++i < --j
becomes false.
7. Once the condition is false, exit the while loop.
8. Print the message "Midpoint is" concatenated with the value of i.
9. The program execution completes.
Example no. 33
// Demonstrate the do-while loop.
class DoWhile {
public static void main(String args[]) {
int n = 10;
do {
System.out.println("tick " + n);
n--;
} while (n > 0);
}
}
Output
tick 10
tick 9
tick 8
tick 7
tick 6
tick 5
tick 4
tick 3
tick 2
tick 1
Explanation
1. Declare and define a class named DoWhile.
2. Inside the class, define the main method.
3. Declare and initialize an integer variable n with the value 10.
4. Enter a do-while loop.
5. Print the message "tick" concatenated with the value of n.
6. Decrement n by 1.
7. Check the loop condition n > 0.
8. If the condition is true, repeat steps 5-7.
9. If the condition is false, exit the do-while loop.
10. The program execution completes.
Example no. 34
// Using a do-while to process a menu selection
class Menu {
public static void main(String args[])
throws java.io.IOException {
char choice;
do {
System.out.println("Help on:");
System.out.println(" 1. if");
System.out.println(" 2. switch");
System.out.println(" 3. while");
System.out.println(" 4. do-while");
System.out.println(" 5. for\n");
System.out.println("Choose one:");
choice = (char) System.in.read();
} while (choice < '1' || choice > '5');
System.out.println("\n");
switch (choice) {
case '1':
System.out.println("The if:\n");
System.out.println("if(condition) statement;");
System.out.println("else statement;");
break;
case '2':
System.out.println("The switch:\n");
System.out.println("switch(expression) {");
System.out.println(" case constant:");
System.out.println(" statement sequence");
System.out.println(" break;");
System.out.println(" // ...");
System.out.println("}");
break;
case '3':
System.out.println("The while:\n");
System.out.println("while(condition) statement;");
break;
case '4':
System.out.println("The do-while:\n");
System.out.println("do {");
System.out.println(" statement;");
System.out.println("} while (condition);");
break;
case '5':
System.out.println("The for:\n");
System.out.print("for(init; condition; iteration)");
System.out.println(" statement;");
break;
}
}
}
Output
Help on:
1. if
2. switch
3. while
4. do-while
5. for
Choose one:
2
The switch:
switch(expression) {
case constant:
statement sequence
break;
// ...
}
Explanation
1. Declare and define a class named Menu.
2. Inside the class, define the main method.
3. Declare a character variable choice.
4. Enter a do-while loop.
5. Print a menu of options for the user to choose from.
6. Read a single character from the user's input using System.in.read(), and assign it to
choice.
7. Continue the loop as long as the entered choice is not between '1' and '5'.
8. Exit the do-while loop once a valid choice is entered.
9. Print a newline character to separate the menu from the subsequent output.
10. Enter a switch statement based on the value of choice.
11. Compare choice with different cases and execute the corresponding code block based
on the selected option.
12. Print the explanation of the selected option.
13. Break out of the switch statement.
14. The program execution completes.
Example no. 35
class Sample {
public static void main(String args[]) {
int a, b;
b = 4;
for (a = 1; a < b; a++) {
System.out.println("a = " + a);
System.out.println("b = " + b);
b--;
}
}
}
Output
a=1
b=4
a=2
b=3
Explanation
1. Inside the class, define the main method.
2. Declare two integer variables a and b.
3. Assign the value 4 to variable b.
4. Enter a for loop with an initialization expression a = 1, termination condition a < b, and
update expression a++.
5. Within the for loop, print the value of a.
6. Within the for loop, print the value of b.
7. Decrement the value of b by 1.
8. Repeat steps 6-8 until the termination condition (a < b) becomes false.
Example no. 35
// Using the comma.
class Comma {
public static void main(String args[]) {
int a, b;
for (a = 1, b = 4; a < b; a++, b--) {
System.out.println("a = " + a);
System.out.println("b = " + b);
}
}
}
Output
a=1
b=4
a=2
b=3
Explanation
1. Declare and define a class named Comma.
2. Inside the class, define the main method.
3. Declare two integer variables a and b.
4. Enter a for loop with an initialization expression a = 1, b = 4, termination condition a < b,
and update expression a++, b--.
5. Within the for loop, print the value of a.
6. Within the for loop, print the value of b.
7. Repeat steps 5-6 until the termination condition (a < b) becomes false.
8. The program execution completes.
Example no. 37
// Parts of the for loop can be empty.
class ForVar {
public static void main(String args[]) {
int i;
boolean done = false;
i = 0;
for (; !done;) {
System.out.println("i is " + i);
if (i == 10)
done = true;
i++;
}
}
}
Output
i is 0
i is 1
i is 2
i is 3
i is 4
i is 5
i is 6
i is 7
i is 8
i is 9
i is 10
Explanation
1. Declare and define a class named ForVar.
2. Inside the class, define the main method.
3. Declare an integer variable i.
4. Declare and initialize a boolean variable done to false.
5. Assign a value of 0 to the variable i.
6. Enter a for loop with an empty initialization expression, termination condition !done,
and an empty update expression.
7. Within the for loop, print the value of i.
8. Check if the value of i is equal to 10. If so, set the done variable to true.
9. Increment the value of i by 1.
10. Repeat steps 7-9 until the termination condition !done becomes false.
Example no. 38
// Loops may be nested.
class Nested {
public static void main(String args[]) {
int i, j;
for (i = 0; i < 10; i++) {
for (j = i; j < 10; j++)
System.out.print(".");
System.out.println();
}
}
}
Output
..........
.........
........
.......
......
.....
....
...
..
.
Explanation
1. Declare and define a class named Nested.
2. Inside the class, define the main method.
3. Declare two integer variables, i and j.
4. Enter an outer for loop with the initialization expression i = 0, termination condition i <
10, and the update expression i++.
5. Within the outer for loop, enter an inner for loop with the initialization expression j = i,
termination condition j < 10, and the update expression j++.
6. Inside the inner for loop, print a dot (.) using the System.out.print() method.
7. After the inner for loop, print a newline character (\n) using the System.out.println()
method to move to the next line.
8. Repeat steps 5-7 until the termination condition i < 10 of the outer for loop becomes
false.
Example no. 39
// Using break to exit a loop.
class BreakLoop {
public static void main(String args[]) {
for (int i = 0; i < 100; i++) {
if (i == 10)
break; // terminate loop if i is 10
System.out.println("i: " + i);
}
System.out.println("Loop complete.");
}
}
Output
i: 0
i: 1
i: 2
i: 3
i: 4
i: 5
i: 6
i: 7
i: 8
i: 9
Explanation
1. Declare and define a class named BreakLoop.
2. Inside the class, define the main method.
3. Enter a for loop with the initialization expression int i = 0, termination condition i < 100,
and the update expression i++.
4. Within the for loop, check if the value of i is equal to 10 using the if statement.
5. If i is equal to 10, execute the break statement, which terminates the loop and jumps to
the statement immediately following the loop.
6. If the if condition is not satisfied, execute the System.out.println() statement to print
the value of i.
7. Repeat steps 4-6 until the termination condition i < 100 of the for loop becomes false or
the break statement is encountered.
8. After the loop, execute the System.out.println() statement to print "Loop complete."
9. The program execution completes.
Example no. 40
// Using break as a civilized form of goto.
class Break {
public static void main(String args[]) {
boolean t = true;
first: {
second: {
third: {
System.out.println("Before the break.");
if (t)
break second; // break out of second
block
System.out.println("This won't execute");
}
System.out.println("This won't execute");
}
System.out.println("This is after second block.");
}
}
}
Output
efore the break.
This is after second block.
Explanation
1. The program starts with the declaration of a boolean variable t set to true.
2. It defines a labeled block called first using the syntax first: { ... }.
3. Inside the first block, there is another labeled block called second.
4. Inside the second block, there is another labeled block called third.
5. The program outputs the message "Before the break."
6. It checks if the boolean variable t is true.
7. If t is true, it executes the break statement, which causes the program to break out of
the second block and continue execution after the first block.
8. If t is false, the code following the break statement will not be executed.
9. The program outputs the message "This is after the second block."
10. The program execution is complete.
Example no. 41
// Using break to exit from nested
class BreakLoop4 {
public static void main(String
outer: for (int i = 0; i <
System.out.print("Pass
loops
args[]) {
3; i++) {
" + i + ": ");
for (int j = 0; j < 100; j++) {
if (j == 10)
break outer; // exit both loops
System.out.print(j + " ");
}
System.out.println("This will not print");
}
System.out.println("Loops complete.");
}
}
Output
Pass 0: 0 1 2 3 4 5 6 7 8 9 Loops complete.
Explanation
1. The program starts by defining a labeled loop called outer.
2. It declares and initializes a loop variable i to 0.
3. Prints "Pass 0: ".
4. Enters a nested loop and declares a loop variable j initialized to 0.
5. Checks if j is equal to 10.
6. If true, breaks out of both the outer and nested loop.
7. If false, prints the value of j.
8. Increments j and repeats steps 5-8 until j reaches 100 or a break statement is
encountered.
9. After the nested loop, prints "This will not print".
10. Increments i.
11. Repeats steps 3-10 for i values 1 and 2.
12. After the outer loop completes, prints "Loops complete." to indicate the end of both
loops.
Notes from program
Program from notes
Program no. 1
public class note1 {
public static void main(String[] args) {
int i = 4;
int j = 5;
System.out.println("Hello" + i); // will print Hello4
System.out.println(i + j); // will print 9
String s1 = new String("pakistan");
String s2 = "pakistan";
if (s1 == s2) {
System.out.println("comparing string using == operator");
}
if (s1.equals(s2)) {
System.out.println("comparing string using equal method");
}
}
}
Output
Hello4
9
comparing string using equal method
Explanation
1. The program declares and initializes two integer variables i and j.
2. Prints "Hello" concatenated with the value of i.
3. Prints the sum of i and j.
4. Declares a String object s1 using the new keyword and assigns it the value "pakistan".
5. Declares a String object s2 and assigns it the value "pakistan".
6. Checks if s1 and s2 are the same object using == operator.
7. Prints "comparing string using == operator" if they are the same.
8. Checks if s1 and s2 have the same content using equals method.
9. Prints "comparing string using equal method" if they have the same content.
Program no. 2
public class note2{
public static void main(String[] args){
System.out.println("where you from" + args[0]);
System.out.println("where your friend from" + args[1]);
System.out.println("where your other friend from" +
args[2]);
int x=5;
int y=9;
int z= x+y;
System.out.println(z);
System.out.println(args[0] +" " + args[1]);
if(args[0].equals(args[1])){
System.out.println("both are same");
}
}
}
Output
where you fromfsd
where your friend fromlhr
where your other friend fromisb
14
fsd lhr
Explanation
Java How to Program, Early Objects, 11th
Edition
Exercise chapter 1
1.Fill in the blanks in each of the following statements.
1) The logical unit that receives information from outside the computer for use by the
computer is the input unit or simply known as input devices.
2) The process of instructing the computer to solve a problem is called coding or
programing.
3) Assembly language is a type of computer language that uses English like abbreviations
for machine-language instructions
4) Output unit is a logical unit that sends information which has already been processed by
the computer to various devices so that it may be used outside the computer.
5) Memory and are logical units of the computer that retain information.
6) ALU or simply Arithmetic Logic Unit is a logical unit of the computer that performs
calculations.
7) CU or control unit is a logical unit of the computer that makes logical decisions.
8) High level languages are most convenient to the programmer for writing programs
quickly and easily.
9) CPU is a logical unit of the computer that coordinates the activities of all the other
logical units.
10) The only language a computer can directly understand is that computer’s machine
language.
2. 1.5 Fill in the blanks in each of the following statements:
1. The java programming language is now used to develop large-scale enterprise
applications, to enhance the functionality of web servers, to provide applications for
consumer devices and for many other purposes.
2. C language initially became widely known as the development language of the UNIX
operating system.
3. The TCP/IP protocol ensures that messages, consisting of sequentially numbered pieces
called bytes, were properly routed from sender to receiver, arrived intact and were
assembled in the correct order.
4. The C++ programming language was developed by Bjarne Stroustrup in the early 1980s
at Bell Laboratories.
3. 1.6 Fill in the blanks in each of the following statements:
1. Java programs normally go through five phases: edit, compile, load, verify, and execute.
2. A(n) integrated development environment (IDE) provides many tools that support the
software development process, such as editors for writing and editing programs,
debuggers for locating logic errors in programs, and many other features.
3. The command "java" invokes the Java Virtual Machine (JVM), which executes Java
programs.
4. A(n) "virtual machine" is a software application that simulates a computer but hides the
underlying operating system and hardware from the programs that interact with it.
5. The "Java Virtual Machine (JVM)" takes the .class files containing the program's
bytecodes and transfers them to primary memory.
6. The "Java Virtual Machine (JVM)" examines bytecodes to ensure that they're valid.
1.7 Explain the two compilation phases of Java programs.
The compilation of Java programs involves two distinct phases: the "compile-time" phase and
the "runtime" phase.
Compile time phase:
During the compile time phase java source code files are processed by java compiler. The
following tasks are performed:
a) Syntax check: The compiler verifies the syntax of code to make sure it follows javas rule
and conventions. It also checks for errors such as missing colons, parentheses or
incorrect keywords.
b) Type checking: The compiler do type checking to make sure that variable, expressions
and method invocations is consistent and valid according to the program.
c) Byte code generation: At the end of compile-time phase, if there are no compilation
errors, the .class files containing the bytecode is generated.
Runtime phase:
Runtime phase Starts when a Java program is executed. It involves the implementation of
bytecode through the Java Virtual Machine (JVM). During runtime, the JVM performs the
following tasks:
a) Loading: The JVM loads bytecode files (.class files) into memory, including classes and
their associated resources.
b) Validation: The JVM evaluates bytecode instructions to ensure that they adhere to Java
language specifications and security constraints. It checks for illegal or unsafe bytecode
instructions that could potentially damage or violate the security of the JVM.
c) Interpretation and execution: The JVM interprets and executes bytecode instructions
sequentially or may use just-in-time (JIT) compilation techniques to improve execution
efficiency.
Exercise chapter 2
2.7 Fill in the blanks in each of the following statements:
1. Comments are used to document a program and improve its readability.
2. A decision can be made in a Java program with a(n) if statement.
3. The arithmetic operators with the same precedence as multiplication are division and
modulus operators.
4. When parentheses in an arithmetic expression are nested, the Inner set of parentheses
is evaluated first.
5. A location in the computer’s memory that may contain different values at various times
throughout the execution of a program is called a(n) Variable.
2.8 Write Java statements that accomplish each of the following tasks:
1.
2.
3.
4.
5.
Display the message "Enter an integer: ", leaving the cursor on the same line.
sol: System.out.print("Enter an integer: ");
Assign the product of variables b and c to the int variable a.
Sol: a = b * c;
Use a comment to state that a program performs a sample payroll calculation.
Sol: // Program performs a sample payroll calculation.
3. 2.9 State whether each of the following is true or false. If false, explain why.
1. Java operators are evaluated from left to right.
False: Java operators have a specific order of precedence that determines their evaluation.
2. The following are all valid variable names: _under_bar_, m928134, t5, j7, her_sales$,
his_$account_total, a, b$, c, z and z2.
True: All the listed variable names follow the valid naming rules in Jav
3. A valid Java arithmetic expression with no parentheses is evaluated from left to right.
False: A valid Java arithmetic expression without parentheses follows operator precedence
rules, not strict left-to-right evaluation.
4. The following are all invalid variable names: 3g, 87, 67h2, h22 and 2h.
True: The listed variable names violate the Java naming conventions by starting with a digit.
4. 2.10 Assuming that x = 2 and y = 3, what does each of the following statements
display?
1. System.out.printf("x = %d%n", x);

Output: "x = 2" (displays the value of x)
2. System.out.printf("Value of %d + %d is %d%n", x, x, (x + x));

Output: "Value of 2 + 2 is 4" (displays the value of x, x, and their sum)
3. System.out.printf("x =");

Output: "x =" (displays the string "x =")
4. System.out.printf("%d = %d%n", (x + y), (y + x));

Output: "5 = 5" (displays the sum of x and y, and then y and x, which are both
equal)
5. 2.11 Which of the following Java statements contain variables whose values are
modified?
1. int p = i + j + k + 7;
 This statement contains variables (i, j, and k) whose values are used in the
expression, but it does not modify their values.
2. System.out.println("variables whose values are modified");
 This statement is a print statement that displays a message but does not modify
any variable values.
3. System.out.println("a = 5");
 This statement is a print statement that displays a message but does not modify
any variable values.
4. int value = input.nextInt();
 This statement declares a new variable "value" and assigns it the value obtained
from the user input. It modifies the value of the "value" variable.
6. 2.12 Given that which of the following are correct Java statements for this
equation?
1. int y = a * x * x * x + 7;
2. int y = a * x * x * (x + 7);
3. int y = (a * x) * x * (x + 7);
4. int y = (a * x) * x * x + 7;
5. int y = a * (x * x * x) + 7;
6. int y = a * x * (x * x + 7);
The correct Java statements for the given equation are: 1, 3, 4, and 5.
7. 2.13 State the order of evaluation of the operators in each of the following Java
statements, and show the value of x after each statement is performed:
1. int x = 7 + 3 * 6 / 2 - 1;
2. int x = 2 % 2 + 2 * 2 - 2 / 2;
3. int x = (3 * 9 * (3 + (9 * 3 / (3))));
After each statement is performed, the value of x will be:
1. x = 15
2. x = 3
3. x = 810
Download