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

Object Oriented Programming IJSE (GDSE)

Uploaded by

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

Object Oriented Programming IJSE (GDSE)

Uploaded by

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

Introduction to Object Oriented Programming

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q01

class Student{
String studentId;
String name;
String address;
int sub1;
int sub2;
}

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

Student s1 = new Student();


System.out.println("s1 Id: " + s1.studentId);
System.out.println("s1 Name: " + s1.name);
System.out.println("s1 Address: " + s1.address);
System.out.println("s1 Sub1: " + s1.sub1);
System.out.println("s1 Sub2: " + s1.sub2);

}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q02

class Student{
String studentId;
String name;
String address;
int sub1;
int sub2;
}

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

Student s1; // Create Reference Veriable


s1 = new Student(); // Create Object "student" and assign to s1
s1.studentId = "S001";
s1.name = "Student 1";
s1.address = "Panadura";
s1.sub1 = 50;
s1.sub2 = 75;

System.out.println("s1 Id: " + s1.studentId);


System.out.println("s1 Name: " + s1.name);
System.out.println("s1 Address: " + s1.address);
System.out.println("s1 Sub1: " + s1.sub1);
System.out.println("s1 Sub2: " + s1.sub2);

}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q03

class Student{
String studentId;
String name;
String address;
int sub1;
int sub2;
}

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

Student s1; // Create Reference Variable


s1 = new Student(); // Create Object "student" and assign to s1

s1.studentId = "S001";
s1.name = "Student 1";
s1.address = "Panadura";
s1.sub1 = 50;
s1.sub2 = 75;

System.out.println("s1 Id: " + s1.studentId);


System.out.println("s1 Name: " + s1.name);
System.out.println("s1 Address: " + s1.address);
System.out.println("s1 Sub1: " + s1.sub1);
System.out.println("s1 Sub2: " + s1.sub2);

Student s2 = new Student();

s2.studentId = "S002";
s2.name = "Student 2";
s2.address = "Galle";
s2.sub1 = 34;
s2.sub2 = 56;

System.out.println("s2 Id: " + s2.studentId);


System.out.println("s2 Name: " + s2.name);
System.out.println("s2 Address: " + s2.address);
System.out.println("s2 Sub1: " + s2.sub1);
System.out.println("s2 Sub2: " + s2.sub2);
}
}

State and Behavior of an Object


● Real world objects can be described by two components.
○ State
○ Behavior

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q04 State as Attributes
==================

class Student{
// State as Attributes
// Start Attribute Declaration
String studentId;
String name;
String address;
int sub1;
int sub2;
// End Attribute Declaration
}

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

Student s1; // Create Reference Variable


s1 = new Student(); // Create Object "student" and assign to s1

s1.studentId = "S001";
s1.name = "Student 1";
s1.address = "Panadura";
s1.sub1 = 50;
s1.sub2 = 75;

System.out.println("s1 Id: " + s1.studentId);


System.out.println("s1 Name: " + s1.name);
System.out.println("s1 Address: " + s1.address);
System.out.println("s1 Sub1: " + s1.sub1);
System.out.println("s1 Sub2: " + s1.sub2);
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q05 Behavior as Instance Method
==========================

class Student{
// Start Attribute Declaration
String studentId;
String name;
String address;
int sub1;
int sub2;
// End Attribute Declaration

// Start Method Declaration


public void print(){
System.out.println(studentId + " " + name + " " + address + " " + sub1 + " " + sub2);
}
// End Method Declaration
}

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

Student s1; // Create Reference Variable


s1 = new Student(); // Create Object "student" and assign to s1
s1.studentId = "S001";
s1.name = "Student 1";
s1.address = "Panadura";
s1.sub1 = 50;
s1.sub2 = 75;

// System.out.println("s1 Id: " + s1.studentId);


// System.out.println("s1 Name: " + s1.name);
// System.out.println("s1 Address: " + s1.address);
// System.out.println("s1 Sub1: " + s1.sub1);
// System.out.println("s1 Sub2: " + s1.sub2);

s1.print();
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q06 Exercise
===========

class Student{
// Start Attribute Declaration
String studentId;
String name;
String address;
int sub1;
int sub2;
// End Attribute Declaration

// Start Method Declaration


public void print(){
System.out.println(studentId + " " + name + " " + address + " " + sub1 + " " + sub2);
}
// End Method Declaration
}

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

Student s1; // Create Reference Variable


s1 = new Student(); // Create Object "student" and assign to s1

// s1.studentId = "S001";
// s1.name = "Student 1";
// s1.address = "Panadura";
// s1.sub1 = 50;
// s1.sub2 = 75;

s1.setValue("S001", "Student 1", "Panadura",50, 75);

// System.out.println("s1 Id: " + s1.studentId);


// System.out.println("s1 Name: " + s1.name);
// System.out.println("s1 Address: " + s1.address);
// System.out.println("s1 Sub1: " + s1.sub1);
// System.out.println("s1 Sub2: " + s1.sub2);

s1.print();
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q07 from Q06
===========

class Student{
// Start Attribute Declaration
String studentId;
String name;
String address;
int sub1;
int sub2;
// End Attribute Declaration

// Start Method Declaration


public void print(){
System.out.println(studentId + " " + name + " " + address + " " + sub1 + " " + sub2);
}

public void setValue(String stuId, String stuName, String stuAddress, int stuSub1, int stuSub2
){
studentId = stuId;
name = stuName;
address = stuAddress;
sub1 = stuSub1;
sub2 = stuSub2;
}
// End Method Declaration
}

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

Student s1; // Create Reference Variable


s1 = new Student(); // Create Object "student" and assign to s1

// s1.studentId = "S001";
// s1.name = "Student 1";
// s1.address = "Panadura";
// s1.sub1 = 50;
// s1.sub2 = 75;

s1.setValue("S001", "Student 1", "Panadura",50, 75);

// System.out.println("s1 Id: " + s1.studentId);


// System.out.println("s1 Name: " + s1.name);
// System.out.println("s1 Address: " + s1.address);
// System.out.println("s1 Sub1: " + s1.sub1);
// System.out.println("s1 Sub2: " + s1.sub2);

s1.print();
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q08 Exercise
============

class Student{
// Start Attribute Declaration
String studentId;
String name;
String address;
int sub1;
int sub2;
// End Attribute Declaration

// Start Method Declaration


public void print(){
System.out.println(studentId + " " + name + " " + address + " " + sub1 + " " + sub2);
}
public void setValue(String stuId, String stuName, String stuAddress, int stuSub1, int stuSub2
){
studentId = stuId;
name = stuName;
address = stuAddress;
sub1 = stuSub1;
sub2 = stuSub2;
}
// End Method Declaration
}

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

Student s1 = new Student();

s1.setValue("S001", "Student 1", "Panadura",50, 75);


s1.print();
System.out.println("Total : " + s1.total());
System.out.println("Average : " + s1.average());

Student s2 = new Student();

s2.setValue("S002", "Student 2", "Galle",45, 65);


s2.print();
System.out.println("Total : " + s2.total());
System.out.println("Average : " + s2.average());
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q09 from Q08
===========

class Student{
// Start Attribute Declaration
String studentId;
String name;
String address;
int sub1;
int sub2;
// End Attribute Declaration
// Start Method Declaration
public void print(){
System.out.println(studentId + " " + name + " " + address + " " + sub1 + " " + sub2);
}

public void setValue(String stuId, String stuName, String stuAddress, int stuSub1, int stuSub2
){
studentId = stuId;
name = stuName;
address = stuAddress;
sub1 = stuSub1;
sub2 = stuSub2;
}

public int total(){


int total = sub1+ sub2;
return total;
}

public double average(){


double avg;
//avg = (sub1 + sub1) / 2.0;
//avg = (sub1 + sub1) / (double) 2;
//avg = (double)(sub1 + sub1) / (double) 2;
avg = total() / (double) 2;
return avg;
}
// End Method Declaration
}

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

Student s1 = new Student();

s1.setValue("S001", "Student 1", "Panadura",50, 75);


s1.print();
System.out.println("Total : " + s1.total());
System.out.println("Average : " + s1.average());

Student s2 = new Student();

s2.setValue("S002", "Student 2", "Galle",45, 65);


s2.print();
System.out.println("Total : " + s2.total());
System.out.println("Average : " + s2.average());
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q10 Case 1
==========

class Box{
int length;
int width;
int height;
}
class Example{
public static void main(String[] args) {
Box b1 = new Box();
System.out.println(b1);

b1.height = 5;
b1.width = 6;
b1.length = 10;
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q11 Case 2
=========

class Box{
int length; // Global Variables
int width; // Global Variables
int height; // Global Variables

public void printVolume(){


int volume; // Local Variables
volume = length * width * height;
System.out.println("Volume : " + volume);
}
}
class Example{
public static void main(String[] args) {
Box b1 = new Box();
System.out.println(b1);

b1.height = 5;
b1.width = 6;
b1.length = 10;

b1.printVolume();
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q12 Case 3
==========

class Box{
int length; // Global Variables
int width; // Global Variables
int height; // Global Variables

public void setValue(int l, int w, int h){


length = l;
height = h;
width = w;
}

public void printVolume(){


int volume; // Local Variables
volume = length * width * height;
System.out.println("Volume : " + volume);
}
}
class Example{
public static void main(String[] args) {
Box b1 = new Box();
System.out.println(b1);

// b1.height = 5;
// b1.width = 6;
// b1.length = 10;

b1.setValue(10, 6, 5);
b1.printVolume();
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q13 Case 4
=========

class Box{
int length; // Global Variables
int width; // Global Variables
int height; // Global Variables

public void setValue(int l, int w, int h){


length = l;
height = h;
width = w;
}

public void printVolume(){


int volume; // Local Variables
volume = length * width * height;
System.out.println("Volume : " + volume);
}

public int getVolume(){


int volume = length * width* height;
return volume;
}
}
class Example{
public static void main(String[] args) {
Box b1 = new Box();
System.out.println(b1);

b1.setValue(10, 6, 5);
int volume = b1.getVolume();
System.out.println("Volume : " + volume);
}
}
Case 5 Keyword ‘this’
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q14

class Box{
int length;
int width;
int height;

public void setValue(int length, int width, int height){


length = length;
height = height;
width = width;
}

public void printVolume(){


int volume;
volume = length * width * height;
System.out.println("Volume : " + volume);
}

public int getVolume(){


int volume = length * width* height;
return volume;
}
}
class Example{
public static void main(String[] args) {
Box b1 = new Box();
System.out.println(b1);

b1.setValue(10, 6, 5);
int volume = b1.getVolume();
System.out.println("Volume : " + volume);
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q15

class Box{
int length;
int width;
int height;

public void setValue(int length, int width, int height){


this.length = length;
this.height = height;
this.width = width;
}

public void printVolume(){


int volume;
volume = length * width * height;
System.out.println("Volume : " + volume);
}

public int getVolume(){


int volume = length * width* height;
return volume;
}
}
class Example{
public static void main(String[] args) {
Box b1 = new Box();
System.out.println(b1);

b1.setValue(10, 6, 5);
int volume = b1.getVolume();
System.out.println("Volume : " + volume);
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q16
class A{
public void print(){
System.out.println(this);
}
}
class Example{
public static void main(String[] args) {
A a1 = new A();
System.out.println(a1);
a1.print();
}
}
Case 6 Constructors
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q17

class Box{
int length;
int width;
int height;

// ---- Compiler Inserts


/*Box(){
length = 0;
width = 0;
height = 0;
}*/

public void setValue(int length, int width, int height){


this.length = length;
this.height = height;
this.width = width;
}

public void printVolume(){


int volume;
volume = length * width * height;
System.out.println("Volume : " + volume);
}

public int getVolume(){


int volume = length * width* height;
return volume;
}
}
class Example{
public static void main(String[] args) {
Box b1 = new Box();
System.out.println(b1);

System.out.println("Length : " + b1.length);


System.out.println("Height : " + b1.height);
System.out.println("Width : " + b1.width);
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q18 Default Constructor
===================

class Box{
int length;
int width;
int height;

// ---- Compiler Inserts | Default Constructor


Box(){ // No Return type | Must be class name
length = 10;
width = 5;
height = 6;
}

public void setValue(int length, int width, int height){


this.length = length;
this.height = height;
this.width = width;
}

public void printVolume(){


int volume;
volume = length * width * height;
System.out.println("Volume : " + volume);
}

public int getVolume(){


int volume = length * width* height;
return volume;
}
}
class Example{
public static void main(String[] args) {
Box b1 = new Box();
System.out.println(b1);

System.out.println("Length : " + b1.length);


System.out.println("Height : " + b1.height);
System.out.println("Width : " + b1.width);
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q19 Parameterized Constructor
=========================

class Box{
int length;
int width;
int height;

Box(int length, int width, int height){


this.length = length;
this.width = width;
this.height = height;
}

public void setValue(int length, int width, int height){


this.length = length;
this.height = height;
this.width = width;
}

public void printVolume(){


int volume;
volume = length * width * height;
System.out.println("Volume : " + volume);
}

public int getVolume(){


int volume = length * width* height;
return volume;
}
}
class Example{
public static void main(String[] args) {
Box b1 = new Box(10,6,5);
System.out.println(b1);

System.out.println("Length : " + b1.length);


System.out.println("Height : " + b1.height);
System.out.println("Width : " + b1.width);
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q20

class Box{
int length;
int width;
int height;

Box(int length, int width, int height){


this.length = length;
this.width = width;
this.height = height;
}

public void setValue(int length, int width, int height){


this.length = length;
this.height = height;
this.width = width;
}

public void printVolume(){


int volume;
volume = length * width * height;
System.out.println("Volume : " + volume);
}

public int getVolume(){


int volume = length * width* height;
return volume;
}
}
class Example{
public static void main(String[] args) {
Box b1 = new Box(10,6,5);
System.out.println(b1);
b1.printVolume();

Box b2 = new Box(); // Illegal

}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q21 Constructor Overloading
=======================

class Box{
int length;
int width;
int height;

Box(){
this.length = 5;
this.width =5;
this.height = 5;
}

Box(int length){
this.width = length;
this.height = length;
this.length = length;
}

Box(int length, int width, int height){


this.length = length;
this.width = width;
this.height = height;
}

public void setValue(int length, int width, int height){


this.length = length;
this.height = height;
this.width = width;
}

public void printVolume(){


int volume;
volume = length * width * height;
System.out.println("Volume : " + volume);
}

public int getVolume(){


int volume = length * width* height;
return volume;
}
}
class Example{
public static void main(String[] args) {
Box b1 = new Box(10,6,5);
System.out.println(b1);
b1.printVolume();

Box b2 = new Box(); //


b2.printVolume();

Box b3 = new Box(10);


b3.printVolume();

}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q21

class Box{
int length;
int width;
int height;

Box(){
this.length = 5;
this.width =5;
this.height = 5;
}

Box(int length){
this.width = length;
this.height = length;
this.length = length;
}

Box(int length, int width, int height){


this.length = length;
this.width = width;
this.height = height;
}

public void setValue(int length, int width, int height){


this.length = length;
this.height = height;
this.width = width;
}

public void printVolume(){


int volume;
volume = length * width * height;
System.out.println("Volume : " + volume);
}

public int getVolume(){


int volume = length * width* height;
return volume;
}
}
class Example{
public static void main(String[] args) {
Box b1 = new Box();
b1.printVolume();

b1.Box(10,20,30); // Illegal
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q22

class Box{
int length;
int width;
int height;

Box(){
this.length = 5;
this.width =5;
this.height = 5;
}

Box(int length){
this.width = length;
this.height = length;
this.length = length;
}

void Box(int length, int width, int height){ // Method


this.length = length;
this.width = width;
this.height = height;
}

public void setValue(int length, int width, int height){


this.length = length;
this.height = height;
this.width = width;
}

public void printVolume(){


int volume;
volume = length * width * height;
System.out.println("Volume : " + volume);
}

public int getVolume(){


int volume = length * width* height;
return volume;
}
}
class Example{
public static void main(String[] args) {
Box b1 = new Box();
b1.printVolume();

b1.Box(10,20,30);
b1.printVolume();
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q23 Attribute Declaration Values
=========================

class Box{
int length = 10;
int width = 6;
int height = 5;

public void printVolume(){


int volume;
volume = length * width * height;
System.out.println("Volume : " + volume);
}
}
class Example{
public static void main(String[] args) {
Box b1 = new Box();
b1.printVolume();
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q24

class MyClass{
int a = 100;

MyClass(){
a = 200;
}

MyClass(int a){
this.a = a;
}
}
class Example{
public static void main(String[] args) {
MyClass m1 = new MyClass();
System.out.println(m1.a);

MyClass m2 = new MyClass(300);


System.out.println(m2.a);
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q25

class Box{
int length = 10;
int width = 6;
int height;
height = 5; // Illegal

public void printVolume(){


int volume;
volume = length * width * height;
System.out.println("Volume : " + volume);
}
}
class Example{
public static void main(String[] args) {
Box b1 = new Box();
b1.printVolume();
}
}

Case 7 Passing Object to Method


/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q26

class Account{
double balance;

Account(double balance){
this.balance = balance;
}

public void printBalance(){


System.out.println("Balance : " + balance);
}
}

class Operation{
public void deposit(double amount, Account account){
account.balance+= amount;
}

public void withdraw(double amount, Account account){


account.balance -= amount;
}
}
class Example{
public static void main(String[] args) {
Account a1 = new Account(10000);
a1.printBalance();

Operation operation = new Operation();


operation.withdraw(3000, a1);
a1.printBalance();

operation.deposit(5000, a1);
a1.printBalance();
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q27

class Account{
double balance;

Account(double balance){
this.balance = balance;
}

public void printBalance(){


System.out.println("Balance : " + balance);
}
}

class Operation{
public void deposit(double amount, Account account){
account.balance+= amount;
}

public void withdraw(double amount, Account account){


account.balance -= amount;
}
}

class Example{
public static void main(String[] args) {
Account a1 = new Account(10000);
a1.printBalance();
Operation operation = new Operation();
operation.withdraw(3000, a1);
a1.printBalance();

operation.deposit(5000, a1);
a1.printBalance();
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q28 Exercise
===========

class MyClass{
int x = 100;
}

class Example{
public static void increment(int x){
x++;
}
public static void main(String[] args) {
MyClass myClass = new MyClass();
System.out.println(myClass.x);
increment(myClass.x);
System.out.println(myClass.x);
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q29 Exercise
==========

class MyClass{
int x = 100;
}

class Example{
public static void increment(MyClass myClass){
myClass.x++;
}
public static void main(String[] args) {
MyClass myClass = new MyClass();
System.out.println(myClass.x);
increment(myClass);
System.out.println(myClass.x);
}
}

Case 8 Returning an Object


/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q30 Exercise
==========

class Box{
int length;
int width;
int height;

Box(int length, int width, int height){


this.length = length;
this.height = height;
this.width = width;
}

public void printVolume(){


int volume;
volume = length * width * height;
System.out.println("Volume : " + volume);
}
}

class Example{
public static void main(String[] args) {
Box b1 = new Box(10, 6, 5);
b1.printVolume(); //Volume : 300

Box b2 = b1.getCopy();
b2.printVolume(); //Volume : 300

System.out.println(b1 == b2); // false


}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q31 from Q30
===========

class Box{
int length;
int width;
int height;

Box(int length, int width, int height){


this.length = length;
this.height = height;
this.width = width;
}

public void printVolume(){


int volume;
volume = length * width * height;
System.out.println("Volume : " + volume);
}

public Box getCopy(){


Box temp = new Box(length, width, height);
return temp;
}
}

class Example{
public static void main(String[] args) {
Box b1 = new Box(10, 6, 5);
b1.printVolume(); //Volume : 300

Box b2 = b1.getCopy();
b2.printVolume(); //Volume : 300

System.out.println(b1 == b2); // false


}
}

Case 9 Static attributes and methods


/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q32
class MyClass{
int x;
static int y;
}

class Example{
public static void main(String[] args) {
MyClass m1 = new MyClass();
m1.x = 100;
m1.y = 10;

MyClass m2 = new MyClass();


m2.x = 200;
m2.y = 20;

MyClass m3 = new MyClass();


m3.x = 300;
m3.y = 30;

System.out.println(m1.x + " " + m1.y); // 100 30


System.out.println(m2.x + " " + m2.y); // 200 30
System.out.println(m3.x + " " + m3.y); // 300 30
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q33

class MyClass{
int x;
static int y;
}

class Example{
public static void main(String[] args) {
MyClass.y = 30;
//MyClass.x = 10; // Illegal

MyClass m1 = new MyClass();


m1.y = 30;
m1.x = 10;
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q34

class MyClass{
public void instanceMethod(){
System.out.println("instanceMethod");
}

public static void staticMethod(){


System.out.println("staticMethod");
}
}

class Example{
public static void main(String[] args) {
MyClass.staticMethod();
// MyClass.instanceMethod(); // Illegal

MyClass m1 = new MyClass();


m1.staticMethod();
m1.instanceMethod();
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q35 Exercise 1
============

class Example{
public static void main(String[] args) {
Date d1 = new Date();
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q36 from Q35
===========

class Date{
int year;
int month;
int day;
}
class Example{
public static void main(String[] args) {
Date d1 = new Date();
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q37 Exercise
===========

class Date{
int year;
int month;
int day;
}
class Example{
public static void main(String[] args) {
Date d1 = new Date();
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q38 from Q37 Option 1
==================

class Date{
int year = 1980;
int month = 11;
int day = 15;
}
class Example{
public static void main(String[] args) {
Date d1 = new Date();
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q39 from Q37 Option 2
===================

class Date{
int year;
int month;
int day;

Date(){
this.year = 1980;
this.month = 11;
this.day = 15;
}
}
class Example{
public static void main(String[] args) {
Date d1 = new Date();
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q40 from Q37 Option 3
==================

class Date{
int year;
int month;
int day;

{ // Instance Block
this.year = 1980;
this.month = 11;
this.day = 15;
}
}
class Example{
public static void main(String[] args) {
Date d1 = new Date();
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q41 Exercise 3
============

class Date{
int year;
int month;
int day;
}
class Example{
public static void main(String[] args) {
Date d1 = new Date(1980, 11, 15);
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q42 from Q41
===========

class Date{
int year;
int month;
int day;

Date(int year, int month, int day){


this.year = year;
this.month = month;
this.day = day;
}
}
class Example{
public static void main(String[] args) {
Date d1 = new Date(1980, 11, 15);
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q43 Exercise 4
============

class Date{
int year;
int month;
int day;

Date(int year, int month, int day){


this.year = year;
this.month = month;
this.day = day;
}
}
class Example{
public static void main(String[] args) {
Date d1 = new Date(1980, 11, 15);
d1.printDate(); // 1980-11-15
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q44 from Q43
===========

class Date{
int year;
int month;
int day;

Date(int year, int month, int day){


this.year = year;
this.month = month;
this.day = day;
}

public void printDate(){


System.out.println(this.year + "-" + this.month + "-" + this.day);
}
}

class Example{
public static void main(String[] args) {
Date d1 = new Date(1980, 11, 15);
d1.printDate(); // 1980-11-15
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q45 Exercise 5
===========

class Date{
int year;
int month;
int day;

Date(int year, int month, int day){


this.year = year;
this.month = month;
this.day = day;
}

public void printDate(){


System.out.println(this.year + "-" + this.month + "-" + this.day);
}
}

class Example{
public static void main(String[] args) {
Date d1 = new Date(1980, 11, 15);
d1.printDate(); // 1980-11-15

Date d2 = new Date();


d2.printDate(); // 2000-12-17
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q46 from Q45
===========

class Date{
int year;
int month;
int day;

Date(){
this.year = 2000;
this.month = 12;
this.day = 17;
}
Date(int year, int month, int day){
this.year = year;
this.month = month;
this.day = day;
}

public void printDate(){


System.out.println(this.year + "-" + this.month + "-" + this.day);
}
}

class Example{
public static void main(String[] args) {
Date d1 = new Date(1980, 11, 15);
d1.printDate(); // 1980-11-15

Date d2 = new Date();


d2.printDate(); // 2000-12-17
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q47 Exercise 6
============

class Date{
int year;
int month;
int day;

Date(){
this.year = 2000;
this.month = 12;
this.day = 17;
}

Date(int year, int month, int day){


this.year = year;
this.month = month;
this.day = day;
}
public void printDate(){
System.out.println(this.year + "-" + this.month + "-" + this.day);
}
}

class Example{
public static void main(String[] args) {
Date d1 = new Date(1980, 11, 15);
d1.printDate(); // 1980-11-15

Date d2 = new Date();


d2.printDate(); // 2000-12-17

d2.setDate(1991,12,14);
d2.printDate(); // 1991-12-14
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q48 from Q47
============

class Date{
int year;
int month;
int day;

Date(){
this.year = 2000;
this.month = 12;
this.day = 17;
}

Date(int year, int month, int day){


this.year = year;
this.month = month;
this.day = day;
}

public void printDate(){


System.out.println(this.year + "-" + this.month + "-" + this.day);
}
public void setDate(int year, int month, int day){
this.year = year;
this.month = month;
this.day = day;
}
}

class Example{
public static void main(String[] args) {
Date d1 = new Date(1980, 11, 15);
d1.printDate(); // 1980-11-15

Date d2 = new Date();


d2.printDate(); // 2000-12-17

d2.setDate(1991,12,14);
d2.printDate(); // 1991-12-14
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q49 Exercise 7
============

class Date{
int year;
int month;
int day;

Date(){
this.year = 2000;
this.month = 12;
this.day = 17;
}

Date(int year, int month, int day){


this.year = year;
this.month = month;
this.day = day;
}

public void printDate(){


System.out.println(this.year + "-" + this.month + "-" + this.day);
}
public void setDate(int year, int month, int day){
this.year = year;
this.month = month;
this.day = day;
}
}

class Example{
public static void main(String[] args) {
Date d1 = new Date(1980, 11, 15);
d1.printDate(); // 1980-11-15

Date d2 = new Date();


d2.printDate(); // 2000-12-17

d2.setDate(1991,12,14);
d2.printDate(); // 1991-12-14

d2.setDate(d1);
d2.printDate(); // 1980-11-15
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q50 from Q49
===========

class Date{
int year;
int month;
int day;

Date(){
this.year = 2000;
this.month = 12;
this.day = 17;
}

Date(int year, int month, int day){


this.year = year;
this.month = month;
this.day = day;
}
public void printDate(){
System.out.println(this.year + "-" + this.month + "-" + this.day);
}

public void setDate(int year, int month, int day){


this.year = year;
this.month = month;
this.day = day;
}

public void setDate(Date date){


this.year = date.year;
this.month = date.month;
this.day = date.day;
}
}

class Example{
public static void main(String[] args) {
Date d1 = new Date(1980, 11, 15);
d1.printDate(); // 1980-11-15

Date d2 = new Date();


d2.printDate(); // 2000-12-17

d2.setDate(1991,12,14);
d2.printDate(); // 1991-12-14

d2.setDate(d1);
d2.printDate(); // 1980-11-15
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q51 Exercise 8
============

class Date{
int year;
int month;
int day;
Date(){
this.year = 2000;
this.month = 12;
this.day = 17;
}

Date(int year, int month, int day){


this.year = year;
this.month = month;
this.day = day;
}

public void printDate(){


System.out.println(this.year + "-" + this.month + "-" + this.day);
}

public void setDate(int year, int month, int day){


this.year = year;
this.month = month;
this.day = day;
}

public void setDate(Date date){


this.year = date.year;
this.month = date.month;
this.day = date.day;
}
}

class Example{
public static void main(String[] args) {
Date d1 = Date.getInstance();
d1.printDate(); // 2000-12-17

}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q52 from Q51
============

class Date{
int year;
int month;
int day;

Date(){
this.year = 2000;
this.month = 12;
this.day = 17;
}

Date(int year, int month, int day){


this.year = year;
this.month = month;
this.day = day;
}

public void printDate(){


System.out.println(this.year + "-" + this.month + "-" + this.day);
}

public void setDate(int year, int month, int day){


this.year = year;
this.month = month;
this.day = day;
}

public void setDate(Date date){


this.year = date.year;
this.month = date.month;
this.day = date.day;
}

public static Date getInstance(){


Date d1 = new Date();
return d1;
}
}

class Example{
public static void main(String[] args) {
Date d1 = Date.getInstance();
d1.printDate(); // 2000-12-17

}
}
Access Privileges | Access Levels

Access Modifier In class In the package In the sub class In other


packages

public Access Allowed Access Allowed Access Allowed Access Allowed

protected Access Allowed Access Allowed Access Allowed Access Denied

default Access Allowed Access Allowed Access Denied Access Denied

private Access Allowed Access Denied Access Denied Access Denied

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q53
////////////////////////////////////////////////////

package package1;

import package2.Car;

class Example{
public static void main(String[] args) {
Car c1 = new Car();
c1.printCar();
System.out.println(c1.name);
//System.out.println(c1.model); // Illegal
//System.out.println(c1.isStart);// Illegal
//System.out.println(c1.speed);// Illegal
}
}

////////////////////////////////////////////////////

package package2;

public class Car {


public String name = "Nissan";
protected String model = "FB15";
boolean isStart = true;
private int speed = 60;

public void printCar(){


System.out.println(this.name + " " + this.model+ " " + this.isStart + " " + this.speed);
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q54

////////////////////////////////////////////////////
package package1;

class Example{
public static void main(String[] args) {
Car c1 = new Car();
c1.printCar();
System.out.println(c1.name);
System.out.println(c1.model);
System.out.println(c1.isStart);
//System.out.println(c1.speed);// Illegal
}
}
////////////////////////////////////////////////////
package package1;

public class Car {


public String name = "Nissan";
protected String model = "FB15";
boolean isStart = true;
private int speed = 60;

public void printCar(){


System.out.println(this.name + " " + this.model+ " " + this.isStart + " " + this.speed);
}
}

Encapsulation
● Wrapping attributes and methods together into a single unit.
● Control over the data by hiding fields and adding methods with public access to access
fields.
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q55 Step 1
========
class Car{
boolean isStart;
int speed;
}

class Example{
public static void main(String[] args) {
Car c1 = new Car();
System.out.println("Is Start : " + c1.isStart);
System.out.println("Speed : " + c1.speed);
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q56 Step 2
=========

class Car{
boolean isStart;
int speed;
}

class Example{
public static void main(String[] args) {
Car c1 = new Car();
System.out.println("Is Start : " + c1.isStart);
System.out.println("Speed : " + c1.speed);

c1.speed = 100;
System.out.println("Is Start : " + c1.isStart);
System.out.println("Speed : " + c1.speed);
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q57 Step 3
=========

class Car{
boolean isStart;
int speed;
}

class Example{
public static void main(String[] args) {
Car c1 = new Car();
System.out.println("Is Start : " + c1.isStart);
System.out.println("Speed : " + c1.speed);

c1.isStart = true;
c1.speed = 100;
System.out.println("Is Start : " + c1.isStart);
System.out.println("Speed : " + c1.speed);

c1.isStart = false;
System.out.println("Is Start : " + c1.isStart);
System.out.println("Speed : " + c1.speed);
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q58 Step 4
=========

class Car{
private boolean isStart;
private int speed;
}

class Example{
public static void main(String[] args) {
Car c1 = new Car();
System.out.println("Is Start : " + c1.isStart);
System.out.println("Speed : " + c1.speed);

c1.isStart = true;
c1.speed = 100;
System.out.println("Is Start : " + c1.isStart);
System.out.println("Speed : " + c1.speed);

c1.isStart = false;
System.out.println("Is Start : " + c1.isStart);
System.out.println("Speed : " + c1.speed);
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q59 Step 5
=========

class Car{
private boolean isStart;
private int speed;

public void setIsStart(boolean isStart){


if(!isStart){
this.speed = 0;
}
this.isStart = isStart;
}

public void incrementSpeed(){


if(this.isStart){
this.speed+= 10;
}
}

public boolean getIsStart(){


return this.isStart;
}

public int getSpeed(){


return this.speed;
}
}

class Example{
public static void main(String[] args) {
Car c1 = new Car();
System.out.println("Is Start : " + c1.isStart);
System.out.println("Speed : " + c1.speed);

c1.isStart = true;
c1.speed = 100;
System.out.println("Is Start : " + c1.isStart);
System.out.println("Speed : " + c1.speed);

c1.isStart = false;
System.out.println("Is Start : " + c1.isStart);
System.out.println("Speed : " + c1.speed);
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q60 Step 6
=========

class Car{
private boolean isStart;
private int speed;

public void setIsStart(boolean isStart){


if(!isStart){
this.speed = 0;
}
this.isStart = isStart;
}

public void incrementSpeed(){


if(this.isStart){
this.speed+= 10;
}
}

public boolean getIsStart(){


return this.isStart;
}

public int getSpeed(){


return this.speed;
}
}

class Example{
public static void main(String[] args) {
Car c1 = new Car();
System.out.println("Is Start : " + c1.getIsStart());
System.out.println("Speed : " + c1.getSpeed());

c1.setIsStart(true);
c1.incrementSpeed();
System.out.println("Is Start : " + c1.getIsStart());
System.out.println("Speed : " + c1.getSpeed());

c1.setIsStart(false);
System.out.println("Is Start : " + c1.getIsStart());
System.out.println("Speed : " + c1.getSpeed());

}
}

Java Swing Application


/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q61

import javax.swing.*;

class Example{
public static void main(String[] args) {
JFrame f1 = new JFrame();
f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f1.setSize(500, 400);
f1.setTitle("Test Title");
f1.setLocationRelativeTo(null);

f1.setVisible(true);
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q62

import javax.swing.*;

class Example{
public static void main(String[] args) {
JFrame f1 = new JFrame();
f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f1.setSize(500, 400);
f1.setTitle("Test Title");
f1.setLocationRelativeTo(null);
f1.setVisible(true);

JFrame f2 = new JFrame();


f2.setSize(600, 300);
f2.setTitle("Frame 2");
f2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

f2.setVisible(true);
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q63

import javax.swing.*;

class Example{
public static void main(String[] args) {
JFrame f1 = new JFrame();
f1.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
f1.setSize(500, 400);
f1.setTitle("Test Title");
f1.setLocationRelativeTo(null);

f1.setVisible(true);
}
}

// JFrame.EXIT_ON_CLOSE = 3
// JFrame.DISPOSE_ON_CLOSE = 2
// JFrame.HIDE_ON_CLOSE = 1
// JFrame.DO_NOTHING_ON_CLOSE = 0

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q64

import javax.swing.*;

class Example{
public static void main(String[] args) {
JFrame f1 = new JFrame();
f1.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f1.setSize(500, 400);
f1.setTitle("Frame 1");
f1.setLocationRelativeTo(null);

f1.setVisible(true);

JFrame f2 = new JFrame();


f2.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f2.setSize(700, 500);
f2.setTitle("Frame 2");
f2.setLocationRelativeTo(null);

f2.setVisible(true);
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q65

import javax.swing.*;
import java.awt.*;

class Example{
public static void main(String[] args) {
JFrame f1 = new JFrame();
f1.setSize(500,500);
f1.setTitle("Frame 1");
f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f1.setLocationRelativeTo(null);

Font font = new Font("", 1, 25);

JButton button = new JButton();


button.setFont(font);
button.setText("Button");

f1.add(button);

f1.setVisible(true);
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q66

import javax.swing.*;

class Example{
public static void main(String[] args) {
Calculator c1 = new Calculator();
c1.setSize(500,400);
c1.setTitle("Calculator");
c1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
c1.setLocationRelativeTo(null);

c1.setVisible(true);
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q67

import javax.swing.*;

class Calculator extends JFrame{

class Example{
public static void main(String[] args) {
Calculator c1 = new Calculator();
c1.setSize(500,400);
c1.setTitle("Calculator");
c1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
c1.setLocationRelativeTo(null);

c1.setVisible(true);
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q68

import javax.swing.*;

class Calculator extends JFrame{

class Example{
public static void main(String[] args) {
Calculator c1 = new Calculator();
c1.setSize(500,400);
c1.setTitle("Calculator");
c1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
c1.setLocationRelativeTo(null);

c1.setVisible(true);
}
}

// JFrame -> Super Class


// Calculator -> Sub Class
// Calculator IS-A JFrame

// Inheritance -> Code reusability

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q69

import javax.swing.*;

class Calculator extends JFrame{

Calculator(){
setSize(500,400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("Calculator");
setLocationRelativeTo(null);

setVisible(true);
}
}
class Example{
public static void main(String[] args) {
Calculator c1 = new Calculator();
Calculator c2 = new Calculator();
new Calculator();
new Calculator();
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q70

import javax.swing.*;
import java.awt.*;

class Calculator extends JFrame{

JButton button;

Calculator(){
setSize(500,400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("Calculator");
setLocationRelativeTo(null);

button = new JButton();


button.setText("Button");
button.setFont(new Font("", 1, 25));
add(button);

setVisible(true);
}
}

class Example{
public static void main(String[] args) {
Calculator c1 = new Calculator();
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q71

import javax.swing.*;
import java.awt.*;

class Calculator extends JFrame{

JButton button;
JLabel label;

Calculator(){
setSize(500,400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("Calculator");
setLocationRelativeTo(null);

button = new JButton();


button.setText("Button");
button.setFont(new Font("", 1, 25));
add(button);

label = new JLabel();


label.setText("This is a Label");
label.setFont(new Font("", 1, 25));
add(label);

setVisible(true);
}
}

class Example{
public static void main(String[] args) {
Calculator c1 = new Calculator();
}
}
Swing Layouts

Border Layout
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q72

import javax.swing.*;
import java.awt.*;

class Calculator extends JFrame{

JButton button;
JLabel label;

Calculator(){
setSize(500,400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("Calculator");
setLocationRelativeTo(null);
setLayout(new BorderLayout());

button = new JButton();


button.setText("Button");
button.setFont(new Font("", 1, 25));
add("North", button);

label = new JLabel();


label.setText("This is a Label");
label.setFont(new Font("", 1, 25));
add("South", label);

setVisible(true);
}
}

class Example{
public static void main(String[] args) {
Calculator c1 = new Calculator();
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q73

import javax.swing.*;
import java.awt.*;

class Calculator extends JFrame{

JButton northButton, eastButton, southButton, westButton, centerButton;

Calculator(){
setSize(500,400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("Calculator");
setLocationRelativeTo(null);
setLayout(new BorderLayout());

Font font = new Font("", 1, 25);

northButton = new JButton();


northButton.setText("North");
northButton.setFont(font);
add("North", northButton);

southButton = new JButton();


southButton.setText("South");
southButton.setFont(font);
add("South", southButton);

eastButton = new JButton();


eastButton.setText("East");
eastButton.setFont(font);
add("East", eastButton);

westButton = new JButton();


westButton.setText("West");
westButton.setFont(font);
add("West", westButton);

centerButton = new JButton();


centerButton.setText("Center");
centerButton.setFont(font);
add("Center", centerButton);
setVisible(true);
}
}

class Example{
public static void main(String[] args) {
Calculator c1 = new Calculator();
}
}

Flow Layout
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q74

import javax.swing.*;
import java.awt.*;

class Calculator extends JFrame{

JButton northButton, eastButton, southButton, westButton, centerButton;

Calculator(){
setSize(500,400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("Calculator");
setLocationRelativeTo(null);
setLayout(new FlowLayout());

Font font = new Font("", 1, 25);

northButton = new JButton();


northButton.setText("North");
northButton.setFont(font);
add( northButton);

southButton = new JButton();


southButton.setText("South");
southButton.setFont(font);
add( southButton);

eastButton = new JButton();


eastButton.setText("East");
eastButton.setFont(font);
add(eastButton);

westButton = new JButton();


westButton.setText("West");
westButton.setFont(font);
add( westButton);

centerButton = new JButton();


centerButton.setText("Center");
centerButton.setFont(font);
add( centerButton);

setVisible(true);
}
}

class Example{
public static void main(String[] args) {
Calculator c1 = new Calculator();
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q75 Align Right
=============

import javax.swing.*;
import java.awt.*;

class Calculator extends JFrame{

JButton northButton, eastButton, southButton, westButton, centerButton;

Calculator(){
setSize(500,400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("Calculator");
setLocationRelativeTo(null);
setLayout(new FlowLayout(FlowLayout.RIGHT));

Font font = new Font("", 1, 25);

northButton = new JButton();


northButton.setText("North");
northButton.setFont(font);
add( northButton);

southButton = new JButton();


southButton.setText("South");
southButton.setFont(font);
add( southButton);

eastButton = new JButton();


eastButton.setText("East");
eastButton.setFont(font);
add(eastButton);

westButton = new JButton();


westButton.setText("West");
westButton.setFont(font);
add( westButton);

centerButton = new JButton();


centerButton.setText("Center");
centerButton.setFont(font);
add( centerButton);

setVisible(true);
}
}

class Example{
public static void main(String[] args) {
Calculator c1 = new Calculator();
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q76 Align Right

import javax.swing.*;
import java.awt.*;

class Calculator extends JFrame{

JButton northButton, eastButton, southButton, westButton, centerButton;


Calculator(){
setSize(500,400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("Calculator");
setLocationRelativeTo(null);
setLayout(new FlowLayout(FlowLayout.LEFT));

Font font = new Font("", 1, 25);

northButton = new JButton();


northButton.setText("North");
northButton.setFont(font);
add( northButton);

southButton = new JButton();


southButton.setText("South");
southButton.setFont(font);
add( southButton);

eastButton = new JButton();


eastButton.setText("East");
eastButton.setFont(font);
add(eastButton);

westButton = new JButton();


westButton.setText("West");
westButton.setFont(font);
add( westButton);

centerButton = new JButton();


centerButton.setText("Center");
centerButton.setFont(font);
add( centerButton);

setVisible(true);
}
}

class Example{
public static void main(String[] args) {
Calculator c1 = new Calculator();
}
}
Grid Layout
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q77

import javax.swing.*;
import java.awt.*;

class Calculator extends JFrame{

JButton button1, button2, button3, button4;

Calculator(){
setSize(500,400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("Calculator");
setLocationRelativeTo(null);
setLayout(new GridLayout(2, 2));

Font font = new Font("", 1, 25);

button1 = new JButton();


button1.setText("1");
button1.setFont(font);
add(button1);

button2 = new JButton();


button2.setText("2");
button2.setFont(font);
add(button2);

button3 = new JButton();


button3.setText("3");
button3.setFont(font);
add(button3);

button4 = new JButton();


button4.setText("4");
button4.setFont(font);
add(button4);

setVisible(true);
}
}

class Example{
public static void main(String[] args) {
Calculator c1 = new Calculator();
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q78 Exercise
===========

import javax.swing.*;
import java.awt.*;

class Calculator extends JFrame{

JButton[] buttons = new JButton[16];


String arr[] = {"7", "8", "9", "/", "4", "5","6", "*", "1", "2", "3", "+", "0", ".", "=", "-"};

Calculator(){
setSize(500,400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("Calculator");
setLocationRelativeTo(null);
setLayout(new GridLayout(4,4));

Font font = new Font("", 1, 25);

for(int i = 0; i < 16; i++){


buttons[i] = new JButton();
buttons[i].setText(arr[i]);
buttons[i].setFont(font);
add(buttons[i]);
}
setVisible(true);
}
}

class Example{
public static void main(String[] args) {
Calculator c1 = new Calculator();
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q79 Exercise
==========

import javax.swing.*;
import java.awt.*;

class Calculator extends JFrame{


JButton headerButton, footerButton, rSideNavButton, lSideNavButton,
button1, button2, button3, button4;
Calculator(){
setSize(500,400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("Calculator");
setLocationRelativeTo(null);

Font font = new Font("", 1, 25);

headerButton = new JButton("Header");


headerButton.setFont(font);
add("North", headerButton);

footerButton = new JButton("Footer");


footerButton.setFont(font);
add("South", footerButton);

rSideNavButton = new JButton("Side Nav");


rSideNavButton.setFont(font);
add("East", rSideNavButton);

lSideNavButton = new JButton("Side Nav");


lSideNavButton.setFont(font);
add("West", lSideNavButton);

JPanel centerPanel = new JPanel();


centerPanel.setLayout(new GridLayout(2, 2));

button1 = new JButton("1");


button1.setFont(font);
centerPanel.add(button1);

button2 = new JButton("2");


button2.setFont(font);
centerPanel.add(button2);
button3 = new JButton("3");
button3.setFont(font);
centerPanel.add(button3);

button4 = new JButton("4");


button4.setFont(font);
centerPanel.add(button4);

add("Center", centerPanel);

setVisible(true);
}
}

class Example{
public static void main(String[] args) {
Calculator c1 = new Calculator();
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q80 Exercise
===========

import javax.swing.*;
import java.awt.*;

class Calculator extends JFrame{

JTextField textField;
JButton[] buttons = new JButton[16];
String arr[] = {"7", "8", "9", "/", "4", "5","6", "*", "1", "2", "3", "+", "0", ".", "=", "-"};

Calculator(){
setSize(500,400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("Calculator");
setLocationRelativeTo(null);
setLayout(new BorderLayout());

Font font = new Font("", 1, 25);


textField = new JTextField();
textField.setFont(font);
add("North", textField);

JPanel buttonPanel = new JPanel();


buttonPanel.setLayout(new GridLayout(4, 4));

for(int i = 0; i < 16; i++){


buttons[i] = new JButton();
buttons[i].setText(arr[i]);
buttons[i].setFont(font);
buttonPanel.add(buttons[i]);
}

add("Center",buttonPanel);

setVisible(true);
}
}

class Example{
public static void main(String[] args) {
Calculator c1 = new Calculator();
}
}

JMenuBar, JMenu, JMenuItem


/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q81 Step1
========

import javax.swing.*;
import java.awt.*;

class Notepad extends JFrame{


Notepad(){
setSize(600,400);
setLocationRelativeTo(null);
setTitle("untitled");
setDefaultCloseOperation(EXIT_ON_CLOSE);

setVisible(true);
}
}

class Example{
public static void main(String[] args) {
new Notepad();
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q82 Step 2
=========

import javax.swing.*;
import java.awt.*;

class Notepad extends JFrame{


private JTextArea textArea;

Notepad(){
setSize(600,400);
setLocationRelativeTo(null);
setTitle("untitled");
setDefaultCloseOperation(EXIT_ON_CLOSE);

textArea = new JTextArea();


textArea.setFont(new Font("", 1, 25));
add("Center", textArea);

setVisible(true);
}
}

class Example{
public static void main(String[] args) {
new Notepad();
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q83 Step 3
=========
import javax.swing.*;
import java.awt.*;

class Notepad extends JFrame{


private JTextArea textArea;

Notepad(){
setSize(600,400);
setLocationRelativeTo(null);
setTitle("untitled");
setDefaultCloseOperation(EXIT_ON_CLOSE);

textArea = new JTextArea();


textArea.setFont(new Font("", 1, 25));

JScrollPane scrollPane = new JScrollPane(textArea);

add("Center", scrollPane);

setVisible(true);
}
}

class Example{
public static void main(String[] args) {
new Notepad();
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q84 Step 4
=========

import javax.swing.*;
import java.awt.*;

class Notepad extends JFrame{


private JTextArea textArea;

private JMenuBar menuBar;


private JMenu fileMenu, editMenu, viewMenu;
private JMenuItem item1, item2, item3, item4, item5, item6;

Notepad(){
setSize(600,400);
setLocationRelativeTo(null);
setTitle("untitled");
setDefaultCloseOperation(EXIT_ON_CLOSE);

textArea = new JTextArea();


textArea.setFont(new Font("", 1, 25));

JScrollPane scrollPane = new JScrollPane(textArea);

add("Center", scrollPane);

menuBar = new JMenuBar();

fileMenu = new JMenu("File");


item1 = new JMenuItem("New");
item2 = new JMenuItem("Open");
fileMenu.add(item1);
fileMenu.add(item2);

editMenu = new JMenu("Edit");


item3 = new JMenuItem("Undo");
item4 = new JMenuItem("Redo");
editMenu.add(item3);
editMenu.add(item4);

menuBar.add(fileMenu);
menuBar.add(editMenu);

setJMenuBar(menuBar);

setVisible(true);
}
}

class Example{
public static void main(String[] args) {
new Notepad();
}
}
Working with JTable
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q85

import javax.swing.*;
import javax.swing.table.DefaultTableModel;

import java.awt.*;

class ViewStudent extends JFrame{

private JTable table;


private DefaultTableModel defaultTableModel;

ViewStudent(){
setSize(600,400);
setLocationRelativeTo(null);
setTitle("View Student");
setDefaultCloseOperation(EXIT_ON_CLOSE);

String columns[] = {"Id", "Name", "Address", "Mobile"};


defaultTableModel = new DefaultTableModel(columns, 0);

String[] rowData = {"S001", "Student 1", "Panadura", "0778987765"};


defaultTableModel.addRow(rowData);

table = new JTable(defaultTableModel);

JScrollPane scrollPane = new JScrollPane(table);


add(scrollPane);

setVisible(true);
}
}

class Example{
public static void main(String[] args) {
new ViewStudent();
}
}
Event Handling
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q86 Action Event vs. Action Listener
============================

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

class Calculator extends JFrame{

JButton button;

Calculator(){
setSize(500,400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("Calculator");
setLocationRelativeTo(null);
setLayout(new FlowLayout());

button = new JButton();


button.setText("Button");
button.setFont(new Font("", 1, 25));

button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("You pressed the button...!");
}
});

add(button);

setVisible(true);
}
}

class Example{
public static void main(String[] args) {
Calculator c1 = new Calculator();
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q87

import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

class Calculator extends JFrame{

JTextField textField;
JSlider slider;

Calculator(){
setSize(350,500);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("Calculator");
setLocationRelativeTo(null);
setLayout(new FlowLayout());

textField = new JTextField(20);


textField.setFont(new Font("", 1, 18));
add(textField);

slider = new JSlider(JSlider.VERTICAL, 0, 100, 50);


slider.setMajorTickSpacing(10);
slider.setPaintLabels(true);

slider.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
int value = slider.getValue();
textField.setText(value+"");// Integer.toString(value)
}
});

add(slider);
setVisible(true);
}
}

class Example{
public static void main(String[] args) {
Calculator c1 = new Calculator();
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q88 Runtime Error
===============

import javax.swing.*;
import javax.swing.event.*;

import java.awt.*;
import java.awt.event.*;

class SliderFrame extends JFrame{


private JSlider slider;
private DisplayFrame displayFrame;

SliderFrame(){
setSize(350,500);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("Slider Frame");
setLocationRelativeTo(null);
setLayout(new FlowLayout());

slider = new JSlider(JSlider.VERTICAL, 0, 100, 50);


slider.setMajorTickSpacing(10);
slider.setPaintLabels(true);

slider.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
int value = slider.getValue();
displayFrame.textField.setText(Integer.toString(value));
}
});

add(slider);
setVisible(true);
}
}

class DisplayFrame extends JFrame{


JTextField textField;

DisplayFrame(){
setSize(350,300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("Display Frame");
setLocationRelativeTo(null);
setLayout(new FlowLayout());

textField = new JTextField(20);


textField.setFont(new Font("", 1, 18));
add(textField);

setVisible(true);
}
}

class Example{
public static void main(String[] args) {
SliderFrame c1 = new SliderFrame();
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q89 FRom Q88
=============

import javax.swing.*;
import javax.swing.event.*;

import java.awt.*;
import java.awt.event.*;

class SliderFrame extends JFrame{


private JSlider slider;
private DisplayFrame displayFrame;

SliderFrame(DisplayFrame displayFrame){
this.displayFrame = displayFrame;
setSize(350,500);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("Slider Frame");
setLocationRelativeTo(null);
setLayout(new FlowLayout());

slider = new JSlider(JSlider.VERTICAL, 0, 100, 50);


slider.setMajorTickSpacing(10);
slider.setPaintLabels(true);

slider.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
int value = slider.getValue();
displayFrame.textField.setText(Integer.toString(value));
}
});

add(slider);
setVisible(true);
}
}

class DisplayFrame extends JFrame{


JTextField textField;

DisplayFrame(){
setSize(350,300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("Display Frame");
setLocationRelativeTo(null);
setLayout(new FlowLayout());

textField = new JTextField(20);


textField.setFont(new Font("", 1, 18));
add(textField);

setVisible(true);
}
}

class Example{
public static void main(String[] args) {
DisplayFrame d1 = new DisplayFrame();
SliderFrame c1 = new SliderFrame(d1);
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q90 Compile Error
===============

import javax.swing.*;
import javax.swing.event.*;

import java.awt.*;
import java.awt.event.*;

class SliderFrame extends JFrame{


private JSlider slider;
private DisplayFrame displayFrame;

SliderFrame(DisplayFrame displayFrame){
this.displayFrame = displayFrame;
setSize(350,500);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("Slider Frame");
setLocationRelativeTo(null);
setLayout(new FlowLayout());

slider = new JSlider(JSlider.VERTICAL, 0, 100, 50);


slider.setMajorTickSpacing(10);
slider.setPaintLabels(true);

slider.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
int value = slider.getValue();
displayFrame.textField.setText(Integer.toString(value));
}
});

add(slider);
setVisible(true);
}
}

class DisplayFrame extends JFrame{


private JTextField textField;

DisplayFrame(){
setSize(350,300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("Display Frame");
setLocationRelativeTo(null);
setLayout(new FlowLayout());

textField = new JTextField(20);


textField.setFont(new Font("", 1, 18));
add(textField);

setVisible(true);
}
}

class Example{
public static void main(String[] args) {
DisplayFrame d1 = new DisplayFrame();
SliderFrame c1 = new SliderFrame(d1);
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q91 from Q90
===========

import javax.swing.*;
import javax.swing.event.*;

import java.awt.*;
import java.awt.event.*;

class SliderFrame extends JFrame{


private JSlider slider;
private DisplayFrame displayFrame;
SliderFrame(DisplayFrame displayFrame){
this.displayFrame = displayFrame;
setSize(350,500);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("Slider Frame");
setLocationRelativeTo(null);
setLayout(new FlowLayout());

slider = new JSlider(JSlider.VERTICAL, 0, 100, 50);


slider.setMajorTickSpacing(10);
slider.setPaintLabels(true);

slider.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
int value = slider.getValue();
displayFrame.setTextFieldValue(Integer.toString(value));
}
});

add(slider);
setVisible(true);
}
}

class DisplayFrame extends JFrame{


private JTextField textField;

DisplayFrame(){
setSize(350,300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("Display Frame");
setLocationRelativeTo(null);
setLayout(new FlowLayout());

textField = new JTextField(20);


textField.setFont(new Font("", 1, 18));
add(textField);

setVisible(true);
}

public void setTextFieldValue(String value){


this.textField.setText(value);
}
}

class Example{
public static void main(String[] args) {
DisplayFrame d1 = new DisplayFrame();
SliderFrame c1 = new SliderFrame(d1);
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q92

class A{
public void mA(){
System.out.println("mA of A");
}
}

class B{
public void mB(){
a1.mA();
}
}

class Example{
public static void main(String[] args) {
B b = new B();
b.mB();
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q93 from Q92 (Runtime Error)
========================

class A{
public void mA(){
System.out.println("mA of A");
}
}

class B{
A a1;
public void mB(){
a1.mA();
}
}

class Example{
public static void main(String[] args) {
B b = new B();
b.mB();
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q94 from Q93 Option 1
==================

class A{
public void mA(){
System.out.println("mA of A");
}
}

class B{
A a1 = new A();
public void mB(){
a1.mA();
}
}

class Example{
public static void main(String[] args) {
B b = new B();
b.mB();
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q95 from Q93 Option 2
==================

class A{
public void mA(){
System.out.println("mA of A");
}
}

class B{
A a1;

B(){
this.a1 = new A();
}

public void mB(){


a1.mA();
}
}

class Example{
public static void main(String[] args) {
B b = new B();
b.mB();
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q96 from Q93 Option 3
==================

class A{
public void mA(){
System.out.println("mA of A");
}
}

class B{
A a1;

B(A a1){
this.a1 = a1;
}
public void mB(){
a1.mA();
}
}

class Example{
public static void main(String[] args) {
A a1 = new A();
B b = new B(a1);
b.mB();
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q97 from Q93 Option 4
===================

class A{
public void mA(){
System.out.println("mA of A");
}
}

class B{
A a1;

public void setA(A a1){


this.a1 = a1;
}

public void mB(){


a1.mA();
}
}

class Example{
public static void main(String[] args) {
A a1 = new A();
B b = new B();
b.setA(a1);
b.mB();
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q98 from Q93 Option 5
===================

class A{
public void mA(){
System.out.println("mA of A");
}
}

class B{

public void mB(A a1){


a1.mA();
}
}

class Example{
public static void main(String[] args) {
A a1 = new A();
B b = new B();
b.mB(a1);
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q99

import javax.swing.*;
import javax.swing.event.*;

import java.awt.*;
import java.awt.event.*;

class DisplayFrame extends JFrame{


private JLabel displayLabel;

DisplayFrame(){
setSize(300, 300);
setLocationRelativeTo(null);
setTitle("Display");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());
this.displayLabel = new JLabel("50");
this.displayLabel.setFont(new Font("", 1, 30));
add(displayLabel);
setVisible(true);
}

public void setDisplayLabelValue(int waterLavel){


this.displayLabel.setText(Integer.toString(waterLavel));
}
}

class AlarmFrame extends JFrame{


private JLabel alarmLabel;
AlarmFrame(){
setSize(300, 300);
setLocationRelativeTo(null);
setTitle("Alarm");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());

this.alarmLabel = new JLabel("Off");


this.alarmLabel.setFont(new Font("", 1, 30));
add(alarmLabel);

setVisible(true);
}

public void setAlarmLabelValue(int waterLavel){


this.alarmLabel.setText(waterLavel >=75? "On" : "Off");
}
}

class SplitterFrame extends JFrame{


private JLabel splitterLabel;

SplitterFrame(){
setSize(300, 300);
setLocationRelativeTo(null);
setTitle("Splitter");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());
this.splitterLabel = new JLabel("Off");
this.splitterLabel.setFont(new Font("", 1, 30));
add(splitterLabel);

setVisible(true);
}

public void setSplitterLabelValue(int waterLavel){


this.splitterLabel.setText(waterLavel >=90 ? "On" : "Off");
}
}

class WaterTankFrame extends JFrame{

private JSlider waterLevelSlider;

WaterTankFrame(){
setSize(300, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("Water Tank");
setLocationRelativeTo(null);

this.waterLevelSlider = new JSlider(JSlider.VERTICAL);


this.waterLevelSlider.setMajorTickSpacing(10);
this.waterLevelSlider.setPaintLabels(true);

add(waterLevelSlider);

setVisible(true);
}

}
class Example{
public static void main(String[] args) {
WaterTankFrame f1 = new WaterTankFrame();
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q100 from Q99
============

import javax.swing.*;
import javax.swing.event.*;

import java.awt.*;
import java.awt.event.*;

class DisplayFrame extends JFrame{


private JLabel displayLabel;

DisplayFrame(){
setSize(300, 300);
setLocationRelativeTo(null);
setTitle("Display");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());
this.displayLabel = new JLabel("50");
this.displayLabel.setFont(new Font("", 1, 30));
add(displayLabel);
setVisible(true);
}

public void setDisplayLabelValue(int waterLavel){


this.displayLabel.setText(Integer.toString(waterLavel));
}
}

class AlarmFrame extends JFrame{


private JLabel alarmLabel;
AlarmFrame(){
setSize(300, 300);
setLocationRelativeTo(null);
setTitle("Alarm");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());

this.alarmLabel = new JLabel("Off");


this.alarmLabel.setFont(new Font("", 1, 30));
add(alarmLabel);

setVisible(true);
}

public void setAlarmLabelValue(int waterLavel){


this.alarmLabel.setText(waterLavel >=75? "On" : "Off");
}
}

class SplitterFrame extends JFrame{


private JLabel splitterLabel;

SplitterFrame(){
setSize(300, 300);
setLocationRelativeTo(null);
setTitle("Splitter");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());

this.splitterLabel = new JLabel("Off");


this.splitterLabel.setFont(new Font("", 1, 30));
add(splitterLabel);

setVisible(true);
}

public void setSplitterLabelValue(int waterLavel){


this.splitterLabel.setText(waterLavel >=90 ? "On" : "Off");
}
}

class WaterTankFrame extends JFrame{

private JSlider waterLevelSlider;

private DisplayFrame displayFrame;


private AlarmFrame alarmFrame;
private SplitterFrame splitterFrame;

private int waterLavel = 0;

WaterTankFrame(){
setSize(300, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("Water Tank");
setLocationRelativeTo(null);

this.waterLevelSlider = new JSlider(JSlider.VERTICAL);


this.waterLevelSlider.setMajorTickSpacing(10);
this.waterLevelSlider.setPaintLabels(true);
this.waterLevelSlider.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
waterLavel = waterLevelSlider.getValue();
displayFrame.setDisplayLabelValue(waterLavel);
splitterFrame.setSplitterLabelValue(waterLavel);
alarmFrame.setAlarmLabelValue(waterLavel);
}
});

add(waterLevelSlider);

setVisible(true);
}

public void setAlarmFrame(AlarmFrame alarmFrame){


this.alarmFrame = alarmFrame;
}

public void setDisplayFrame(DisplayFrame displayFrame){


this.displayFrame = displayFrame;
}

public void setSplitterFrame(SplitterFrame splitterFrame){


this.splitterFrame = splitterFrame;
}

}
class Example{
public static void main(String[] args) {
WaterTankFrame f1 = new WaterTankFrame();
f1.setDisplayFrame(new DisplayFrame());
f1.setAlarmFrame(new AlarmFrame());
f1.setSplitterFrame(new SplitterFrame());
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q101 from Q100
=============

import javax.swing.*;
import javax.swing.event.*;

import java.awt.*;
import java.awt.event.*;

class DisplayFrame extends JFrame{


private JLabel displayLabel;

DisplayFrame(){
setSize(300, 300);
setLocationRelativeTo(null);
setTitle("Display");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());
this.displayLabel = new JLabel("50");
this.displayLabel.setFont(new Font("", 1, 30));
add(displayLabel);
setVisible(true);
}

public void setDisplayLabelValue(int waterLavel){


this.displayLabel.setText(Integer.toString(waterLavel));
}
}

class AlarmFrame extends JFrame{


private JLabel alarmLabel;
AlarmFrame(){
setSize(300, 300);
setLocationRelativeTo(null);
setTitle("Alarm");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());

this.alarmLabel = new JLabel("Off");


this.alarmLabel.setFont(new Font("", 1, 30));
add(alarmLabel);

setVisible(true);
}

public void setAlarmLabelValue(int waterLavel){


this.alarmLabel.setText(waterLavel >=75? "On" : "Off");
}
}

class SplitterFrame extends JFrame{


private JLabel splitterLabel;

SplitterFrame(){
setSize(300, 300);
setLocationRelativeTo(null);
setTitle("Splitter");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());

this.splitterLabel = new JLabel("Off");


this.splitterLabel.setFont(new Font("", 1, 30));
add(splitterLabel);

setVisible(true);
}

public void setSplitterLabelValue(int waterLavel){


this.splitterLabel.setText(waterLavel >=90 ? "On" : "Off");
}
}

class WaterTankController{
private DisplayFrame displayFrame;
private AlarmFrame alarmFrame;
private SplitterFrame splitterFrame;

private int waterLavel;

public void setAlarmFrame(AlarmFrame alarmFrame){


this.alarmFrame = alarmFrame;
}

public void setDisplayFrame(DisplayFrame displayFrame){


this.displayFrame = displayFrame;
}
public void setSplitterFrame(SplitterFrame splitterFrame){
this.splitterFrame = splitterFrame;
}

public void setWaterLevel(int waterLavel){


if(this.waterLavel != waterLavel){
this.waterLavel = waterLavel;
notifyObject();
}
}

public void notifyObject(){


this.alarmFrame.setAlarmLabelValue(waterLavel);
this.displayFrame.setDisplayLabelValue(waterLavel);
this.splitterFrame.setSplitterLabelValue(waterLavel);
}
}

class WaterTankFrame extends JFrame{

private JSlider waterLevelSlider;


private int waterLavel = 0;
private WaterTankController waterTankController;

WaterTankFrame(WaterTankController waterTankController){
this.waterTankController = waterTankController;
setSize(300, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("Water Tank");
setLocationRelativeTo(null);

this.waterLevelSlider = new JSlider(JSlider.VERTICAL);


this.waterLevelSlider.setMajorTickSpacing(10);
this.waterLevelSlider.setPaintLabels(true);
this.waterLevelSlider.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
waterLavel = waterLevelSlider.getValue();
waterTankController.setWaterLevel(waterLavel);
}
});

add(waterLevelSlider);
setVisible(true);
}

}
class Example{
public static void main(String[] args) {
WaterTankController controller = new WaterTankController();
controller.setAlarmFrame(new AlarmFrame());
controller.setDisplayFrame(new DisplayFrame());
controller.setSplitterFrame(new SplitterFrame());
WaterTankFrame f1 = new WaterTankFrame(controller);
}
}

Inheritance
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q102 Case 1
==========

import javax.swing.*;

class Calculator extends JFrame{

}
class Example {
public static void main(String[] args) {
JFrame f1 = new JFrame();
f1.setSize(1000, 300);
f1.setLocationRelativeTo(null);
f1.setTitle("Frame");
f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f1.setVisible(true);

Calculator c1 = new Calculator();


c1.setSize(500, 200);
c1.setLocationRelativeTo(null);
c1.setTitle("Calculator");
c1.setDefaultCloseOperation(Calculator.EXIT_ON_CLOSE);
c1.setVisible(true);
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q103 Case 2
===========

import javax.swing.*;

class Calculator extends JFrame{

Calculator(){
setSize(100,100);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("Calculator");
setVisible(true);
}
}
class Example {
public static void main(String[] args) {
new Calculator();
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q104 exercise
===========

class A{
int a;
public void mA(){
System.out.println("mA of A");
}
}

class B extends A{
int b;
public void mB(){
System.out.println("mB of B");
}

public void printAB(){


System.out.println("b : " + b );
System.out.println("a : " + a ); // print from A
}

public void print(){


mA(); // call from A
mB();
}
}

class Example {
public static void main(String[] args) {
B b = new B();
b.print();
b.printAB();
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q105 Case 3
==========

class A{
int a;
static {
System.out.println("static block of A");
}
public void mA(){
System.out.println("mA of A");
}
}

class B extends A{
int b;
static {
System.out.println("static block of B");
}
public void mB(){
System.out.println("mB of B");
}
}

class Example {
public static void main(String[] args) {
new B();
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q106 Exercise
============

class A{
int a;
A(){
System.out.println("constructor of A");
}
{
System.out.println("instance block of A");
}
static {
System.out.println("static block of A");
}
public void mA(){
System.out.println("mA of A");
}
}

class B extends A{
int b;
B(){
System.out.println("constructor of B");
}
{
System.out.println("instance block of B");
}
static {
System.out.println("static block of B");
}
public void mB(){
System.out.println("mB of B");
}
}

class Example {
public static void main(String[] args) {
new B();
new B();
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q107 Exercise
============

class A{
int a;
static{
System.out.println("static block of A");
}
}

class B extends A{
int b;
static{
System.out.println("static block of B");
}
}

class C extends B{
int c;
static{
System.out.println("static block of C");
}
}

class D extends B{
int d;
static{
System.out.println("static block of D");
}
}

class Example {
public static void main(String[] args) {
new D();
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q108 Case 4
===========

class A{
int a;
A(){
System.out.println("A()");
}
A(int i){
System.out.println("A(int)");
}
A(int i, int j){
System.out.println("A(int,int)");
}
}

class B extends A{
B(){
System.out.println("B()");
}
B(int i){
System.out.println("B(int)");
}
B(int i, int j){
System.out.println("B(int,int)");
}
int b;
}

class Example {
public static void main(String[] args) {
B b1 = new B();
System.out.println("=================");
B b2 = new B(10);
System.out.println("=================");
B b3 = new B(10, 20);
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q109
class A{
int a;
A(){
System.out.println("A()");
}
A(int i){
System.out.println("A(int)");
}
A(int i, int j){
System.out.println("A(int,int)");
}
}

class B extends A{
B(){
// compiler inserts super();
System.out.println("B()");
}
B(int i){
// compiler inserts super();
System.out.println("B(int)");
}
B(int i, int j){
// compiler inserts super();
System.out.println("B(int,int)");
}
int b;
}

class Example {
public static void main(String[] args) {
B b1 = new B();
System.out.println("=================");
B b2 = new B(10);
System.out.println("=================");
B b3 = new B(10, 20);
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q110 from Q109
=============

class A{
int a;
A(){
System.out.println("A()");
}
A(int i){
System.out.println("A(int)");
}
A(int i, int j){
System.out.println("A(int,int)");
}
}

class B extends A{
B(){
super();
System.out.println("B()");
}
B(int i){
super(i);
System.out.println("B(int)");
}
B(int i, int j){
super(i, j);
System.out.println("B(int,int)");
}
int b;
}

class Example {
public static void main(String[] args) {
B b1 = new B();
System.out.println("=================");
B b2 = new B(10);
System.out.println("=================");
B b3 = new B(10, 20);
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q111 Example
===========

class A{
int a;
A(int i){
System.out.println("A(int)");
}
}

class B extends A{
int b;
B(){
// "super()"
super(10);
}
}

class Example {
public static void main(String[] args) {
new B();
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q112 Case 5
===========

class A{
int a;
}

class B{
int b;
}

class C extends A,B{ // Illegal

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

}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q113 Case 6
==========

class A{
int a;
public void printA(){
System.out.println("a : " + this.a);
}
}

class B extends A{
int b;
public void printB(){
System.out.println("b : " + b);
}
}
class Example {
public static void main(String[] args) {
B b1 = new B();
b1.a = 100;
b1.b = 200;

b1.printA();
b1.printB();
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q114 Case 7
==========

class A{
int a;
public void printA(){
System.out.println("a : " + this.a);
}
}

class B extends A{
int b;
public void printB(){
System.out.println("b : " + b);
}
}
class Example {
public static void main(String[] args) {
B b1 = new B();
b1.a = 100; // legal
b1.b = 200;
b1.printA(); // legal
b1.printB();

A a1 = new B(); // legal


a1.a = 200; // Legal
//a1.b = 300; // Illegal

a1.printA(); // Legal
//a1.printB(); // Illegal
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q115 Case 8 Method Overriding
=========================

class Vehicle{
public void park(){
System.out.println("Vehicle Parking");
}
}

class Car extends Vehicle{


public void park(){ // Same name, same Parameters, Same Signatures
System.out.println("Car Parking");
}
}

class Example {
public static void main(String[] args) {
Car c1 = new Car();
c1.park();
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q116 Method overloading vs overriding
==============================

class Vehicle{
public void park(){
System.out.println("Vehicle Parking");
}
}

class Car extends Vehicle{


public void park(){ // Same name, same Parameters, Same Signatures
System.out.println("Car Parking");
}

public void park(int Location){ // Method Overload => Same name, Different Parameters,
Different Signatures
System.out.println("Car Parking");
}
}

class Example {
public static void main(String[] args) {
Car c1 = new Car();
c1.park();
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q117 Case 9 (Dynamic method dispatch)
================================

class Vehicle{
public void park(){
System.out.println("Vehicle Parking");
}
}

class Car extends Vehicle{


public void park(){
System.out.println("Car Parking");
}
}

class Example {
public static void main(String[] args) {
Vehicle v1 = new Car();
v1.park();
}
}

Polymorphism
(Single Interface, Many Forms)
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q118

class Vehicle{
public void park(){
System.out.println("Vehicle Park");
}
}

class Car extends Vehicle{


public void park(){
System.out.println("Car Park");
}
}
class Van extends Vehicle{
public void park(){
System.out.println("Van Park");
}
}
class Bus extends Vehicle{
public void park(){
System.out.println("Bus Park");
}
}
class Example {
public static void main(String[] args) {
Vehicle[] vehicles = {new Car(), new Van(), new Bus()};
for (Vehicle vehicle : vehicles) {
vehicle.park();
}
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q119 from Q101 Add SMS sender step 1
===============================

import javax.swing.*;
import javax.swing.event.*;

import java.awt.*;
import java.awt.event.*;

class DisplayFrame extends JFrame{


private JLabel displayLabel;

DisplayFrame(){
setSize(300, 300);
setLocationRelativeTo(null);
setTitle("Display");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());
this.displayLabel = new JLabel("50");
this.displayLabel.setFont(new Font("", 1, 30));
add(displayLabel);
setVisible(true);
}

public void setDisplayLabelValue(int waterLavel){


this.displayLabel.setText(Integer.toString(waterLavel));
}
}

class AlarmFrame extends JFrame{


private JLabel alarmLabel;
AlarmFrame(){
setSize(300, 300);
setLocationRelativeTo(null);
setTitle("Alarm");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());

this.alarmLabel = new JLabel("Off");


this.alarmLabel.setFont(new Font("", 1, 30));
add(alarmLabel);

setVisible(true);
}

public void setAlarmLabelValue(int waterLavel){


this.alarmLabel.setText(waterLavel >=75? "On" : "Off");
}
}

class SplitterFrame extends JFrame{


private JLabel splitterLabel;

SplitterFrame(){
setSize(300, 300);
setLocationRelativeTo(null);
setTitle("Splitter");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());

this.splitterLabel = new JLabel("Off");


this.splitterLabel.setFont(new Font("", 1, 30));
add(splitterLabel);

setVisible(true);
}

public void setSplitterLabelValue(int waterLavel){


this.splitterLabel.setText(waterLavel >=90 ? "On" : "Off");
}
}

class SMSSenderFrame extends JFrame{


private JLabel smsLabel;
SMSSenderFrame(){
setSize(300, 300);
setLocationRelativeTo(null);
setTitle("SMS Sender");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());

this.smsLabel = new JLabel("");


this.smsLabel.setFont(new Font("", 1, 30));
add(smsLabel);

setVisible(true);
}

public void setSmsLableValue(int waterLavel){


this.smsLabel.setText("SMS Sending : " + waterLavel);
}

class WaterTankController{
private DisplayFrame displayFrame;
private AlarmFrame alarmFrame;
private SplitterFrame splitterFrame;

private int waterLavel;

public void setAlarmFrame(AlarmFrame alarmFrame){


this.alarmFrame = alarmFrame;
}

public void setDisplayFrame(DisplayFrame displayFrame){


this.displayFrame = displayFrame;
}

public void setSplitterFrame(SplitterFrame splitterFrame){


this.splitterFrame = splitterFrame;
}

public void setWaterLevel(int waterLavel){


if(this.waterLavel != waterLavel){
this.waterLavel = waterLavel;
notifyObject();
}
}

public void notifyObject(){


this.alarmFrame.setAlarmLabelValue(waterLavel);
this.displayFrame.setDisplayLabelValue(waterLavel);
this.splitterFrame.setSplitterLabelValue(waterLavel);
}
}

class WaterTankFrame extends JFrame{

private JSlider waterLevelSlider;


private int waterLavel = 0;
private WaterTankController waterTankController;

WaterTankFrame(WaterTankController waterTankController){
this.waterTankController = waterTankController;
setSize(300, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("Water Tank");
setLocationRelativeTo(null);

this.waterLevelSlider = new JSlider(JSlider.VERTICAL);


this.waterLevelSlider.setMajorTickSpacing(10);
this.waterLevelSlider.setPaintLabels(true);
this.waterLevelSlider.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
waterLavel = waterLevelSlider.getValue();
waterTankController.setWaterLevel(waterLavel);
}
});

add(waterLevelSlider);

setVisible(true);
}

}
class Example{
public static void main(String[] args) {
WaterTankController controller = new WaterTankController();
controller.setAlarmFrame(new AlarmFrame());
controller.setDisplayFrame(new DisplayFrame());
controller.setSplitterFrame(new SplitterFrame());
WaterTankFrame f1 = new WaterTankFrame(controller);
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q120 from Q119
=============

import javax.swing.*;
import javax.swing.event.*;

import java.awt.*;
import java.awt.event.*;

class DisplayFrame extends JFrame{


private JLabel displayLabel;

DisplayFrame(){
setSize(300, 300);
setLocationRelativeTo(null);
setTitle("Display");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());
this.displayLabel = new JLabel("50");
this.displayLabel.setFont(new Font("", 1, 30));
add(displayLabel);
setVisible(true);
}

public void setDisplayLabelValue(int waterLavel){


this.displayLabel.setText(Integer.toString(waterLavel));
}
}

class AlarmFrame extends JFrame{


private JLabel alarmLabel;
AlarmFrame(){
setSize(300, 300);
setLocationRelativeTo(null);
setTitle("Alarm");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());

this.alarmLabel = new JLabel("Off");


this.alarmLabel.setFont(new Font("", 1, 30));
add(alarmLabel);

setVisible(true);
}

public void setAlarmLabelValue(int waterLavel){


this.alarmLabel.setText(waterLavel >=75? "On" : "Off");
}
}

class SplitterFrame extends JFrame{


private JLabel splitterLabel;

SplitterFrame(){
setSize(300, 300);
setLocationRelativeTo(null);
setTitle("Splitter");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());

this.splitterLabel = new JLabel("Off");


this.splitterLabel.setFont(new Font("", 1, 30));
add(splitterLabel);

setVisible(true);
}

public void setSplitterLabelValue(int waterLavel){


this.splitterLabel.setText(waterLavel >=90 ? "On" : "Off");
}
}

class SMSSenderFrame extends JFrame{


private JLabel smsLabel;

SMSSenderFrame(){
setSize(300, 300);
setLocationRelativeTo(null);
setTitle("SMS Sender");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());

this.smsLabel = new JLabel("");


this.smsLabel.setFont(new Font("", 1, 30));
add(smsLabel);

setVisible(true);
}

public void setSmsLableValue(int waterLavel){


this.smsLabel.setText("SMS Sending : " + waterLavel);
}
}

class WaterTankController{
private DisplayFrame displayFrame;
private AlarmFrame alarmFrame;
private SplitterFrame splitterFrame;
private SMSSenderFrame smsSenderFrame;

private int waterLavel;

public void setAlarmFrame(AlarmFrame alarmFrame){


this.alarmFrame = alarmFrame;
}

public void setDisplayFrame(DisplayFrame displayFrame){


this.displayFrame = displayFrame;
}

public void setSplitterFrame(SplitterFrame splitterFrame){


this.splitterFrame = splitterFrame;
}

public void setSMSSenderFrame(SMSSenderFrame smsSenderFrame){


this.smsSenderFrame = smsSenderFrame;
}
public void setWaterLevel(int waterLavel){
if(this.waterLavel != waterLavel){
this.waterLavel = waterLavel;
notifyObject();
}
}
public void notifyObject(){
this.alarmFrame.setAlarmLabelValue(waterLavel);
this.displayFrame.setDisplayLabelValue(waterLavel);
this.splitterFrame.setSplitterLabelValue(waterLavel);
this.smsSenderFrame.setSmsLableValue(waterLavel);
}
}

class WaterTankFrame extends JFrame{

private JSlider waterLevelSlider;


private int waterLavel = 0;
private WaterTankController waterTankController;

WaterTankFrame(WaterTankController waterTankController){
this.waterTankController = waterTankController;
setSize(300, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("Water Tank");
setLocationRelativeTo(null);

this.waterLevelSlider = new JSlider(JSlider.VERTICAL);


this.waterLevelSlider.setMajorTickSpacing(10);
this.waterLevelSlider.setPaintLabels(true);
this.waterLevelSlider.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
waterLavel = waterLevelSlider.getValue();
waterTankController.setWaterLevel(waterLavel);
}
});

add(waterLevelSlider);

setVisible(true);
}

}
class Example{
public static void main(String[] args) {
WaterTankController controller = new WaterTankController();
controller.setAlarmFrame(new AlarmFrame());
controller.setDisplayFrame(new DisplayFrame());
controller.setSplitterFrame(new SplitterFrame());
controller.setSMSSenderFrame(new SMSSenderFrame());
WaterTankFrame f1 = new WaterTankFrame(controller);
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q121 Adding Polymorphism
=====================

import javax.swing.*;
import javax.swing.event.*;

import java.awt.*;
import java.awt.event.*;

class WaterLevelObserver extends JFrame{


public void update(int waterLevel){
//
}
}

class DisplayFrame extends WaterLevelObserver{


private JLabel displayLabel;

DisplayFrame(){
setSize(300, 300);
setLocationRelativeTo(null);
setTitle("Display");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());
this.displayLabel = new JLabel("50");
this.displayLabel.setFont(new Font("", 1, 30));
add(displayLabel);
setVisible(true);
}

public void update(int waterLevel){


this.displayLabel.setText(Integer.toString(waterLevel));
}
}

class AlarmFrame extends WaterLevelObserver{


private JLabel alarmLabel;
AlarmFrame(){
setSize(300, 300);
setLocationRelativeTo(null);
setTitle("Alarm");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());

this.alarmLabel = new JLabel("Off");


this.alarmLabel.setFont(new Font("", 1, 30));
add(alarmLabel);

setVisible(true);
}

public void update(int waterLevel){


this.alarmLabel.setText(waterLevel >=75? "On" : "Off");
}
}

class SplitterFrame extends WaterLevelObserver{


private JLabel splitterLabel;

SplitterFrame(){
setSize(300, 300);
setLocationRelativeTo(null);
setTitle("Splitter");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());

this.splitterLabel = new JLabel("Off");


this.splitterLabel.setFont(new Font("", 1, 30));
add(splitterLabel);

setVisible(true);
}

public void update(int waterLevel){


this.splitterLabel.setText(waterLevel >=90 ? "On" : "Off");
}
}

class WaterTankController{
private WaterLevelObserver[] observers = new WaterLevelObserver[0];
private int waterLevel;

public void addWaterLevelObserver(WaterLevelObserver levelObserver){


WaterLevelObserver[] temp = new WaterLevelObserver[observers.length + 1];
for(int i = 0; i < observers.length; i++){
temp[i] = observers[i];
}
temp[temp.length-1] = levelObserver;
observers = temp;
}

public void setWaterLevel(int waterLevel){


if(this.waterLevel != waterLevel){
this.waterLevel = waterLevel;
notifyObject();
}
}

public void notifyObject(){


for(WaterLevelObserver waterLevelObserver : observers){
waterLevelObserver.update(waterLevel);
}
}
}

class WaterTankFrame extends JFrame{

private JSlider waterLevelSlider;


private int waterLevel = 0;
private WaterTankController waterTankController;

WaterTankFrame(WaterTankController waterTankController){
this.waterTankController = waterTankController;
setSize(300, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("Water Tank");
setLocationRelativeTo(null);

this.waterLevelSlider = new JSlider(JSlider.VERTICAL);


this.waterLevelSlider.setMajorTickSpacing(10);
this.waterLevelSlider.setPaintLabels(true);
this.waterLevelSlider.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
waterLevel = waterLevelSlider.getValue();
waterTankController.setWaterLevel(waterLevel);
}
});

add(waterLevelSlider);

setVisible(true);
}

}
class Example{
public static void main(String[] args) {
WaterTankController controller = new WaterTankController();
controller.addWaterLevelObserver(new AlarmFrame());
controller.addWaterLevelObserver(new SplitterFrame());
controller.addWaterLevelObserver(new DisplayFrame());
WaterTankFrame f1 = new WaterTankFrame(controller);
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q122 Adding SMS Window
======================

import javax.swing.*;
import javax.swing.event.*;

import java.awt.*;
import java.awt.event.*;

class WaterLevelObserver extends JFrame{


public void update(int waterLevel){
//
}
}

class DisplayFrame extends WaterLevelObserver{


private JLabel displayLabel;

DisplayFrame(){
setSize(300, 300);
setLocationRelativeTo(null);
setTitle("Display");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());
this.displayLabel = new JLabel("50");
this.displayLabel.setFont(new Font("", 1, 30));
add(displayLabel);
setVisible(true);
}

public void update(int waterLevel){


this.displayLabel.setText(Integer.toString(waterLevel));
}
}

class AlarmFrame extends WaterLevelObserver{


private JLabel alarmLabel;
AlarmFrame(){
setSize(300, 300);
setLocationRelativeTo(null);
setTitle("Alarm");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());

this.alarmLabel = new JLabel("Off");


this.alarmLabel.setFont(new Font("", 1, 30));
add(alarmLabel);

setVisible(true);
}

public void update(int waterLevel){


this.alarmLabel.setText(waterLevel >=75? "On" : "Off");
}
}

class SplitterFrame extends WaterLevelObserver{


private JLabel splitterLabel;

SplitterFrame(){
setSize(300, 300);
setLocationRelativeTo(null);
setTitle("Splitter");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());
this.splitterLabel = new JLabel("Off");
this.splitterLabel.setFont(new Font("", 1, 30));
add(splitterLabel);

setVisible(true);
}

public void update(int waterLevel){


this.splitterLabel.setText(waterLevel >=90 ? "On" : "Off");
}
}

class SMSSenderFrame extends WaterLevelObserver{


private JLabel smsLabel;

SMSSenderFrame(){
setSize(300, 300);
setLocationRelativeTo(null);
setTitle("SMS Sender");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());

this.smsLabel = new JLabel("");


this.smsLabel.setFont(new Font("", 1, 30));
add(smsLabel);

setVisible(true);
}

public void update(int waterLevel){


this.smsLabel.setText("SMS Sending : " + waterLevel);
}
}

class WaterTankController{
private WaterLevelObserver[] observers = new WaterLevelObserver[0];

private int waterLevel;

public void addWaterLevelObserver(WaterLevelObserver levelObserver){


WaterLevelObserver[] temp = new WaterLevelObserver[observers.length + 1];
for(int i = 0; i < observers.length; i++){
temp[i] = observers[i];
}
temp[temp.length-1] = levelObserver;
observers = temp;
}

public void setWaterLevel(int waterLevel){


if(this.waterLevel != waterLevel){
this.waterLevel = waterLevel;
notifyObject();
}
}

public void notifyObject(){


for(WaterLevelObserver waterLevelObserver : observers){
waterLevelObserver.update(waterLevel);
}
}
}

class WaterTankFrame extends JFrame{

private JSlider waterLevelSlider;


private int waterLevel = 0;
private WaterTankController waterTankController;

WaterTankFrame(WaterTankController waterTankController){
this.waterTankController = waterTankController;
setSize(300, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("Water Tank");
setLocationRelativeTo(null);

this.waterLevelSlider = new JSlider(JSlider.VERTICAL);


this.waterLevelSlider.setMajorTickSpacing(10);
this.waterLevelSlider.setPaintLabels(true);
this.waterLevelSlider.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
waterLevel = waterLevelSlider.getValue();
waterTankController.setWaterLevel(waterLevel);
}
});

add(waterLevelSlider);
setVisible(true);
}

}
class Example{
public static void main(String[] args) {
WaterTankController controller = new WaterTankController();
controller.addWaterLevelObserver(new AlarmFrame());
controller.addWaterLevelObserver(new SplitterFrame());
controller.addWaterLevelObserver(new DisplayFrame());
controller.addWaterLevelObserver(new SMSSenderFrame());
WaterTankFrame f1 = new WaterTankFrame(controller);
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q123

class Vehicle{
public void park(){
System.out.println("Vehicle Parking");
}
}

class Car extends Vehicle{


public void park(){
System.out.println("Car Parking");
}

public void callPark(){


super.park(); // call from Vehicle
park(); // call from Car
}
}

class Example{
public static void main(String[] args) {
Car c1 = new Car();
c1.callPark();
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q124

class Vehicle{
int year = 2000;
public void park(){
System.out.println("Vehicle Parking");
}
}

class Car extends Vehicle{


int year = 2001;
public void park(){
System.out.println("Car Parking");
}
}

class Example{
public static void main(String[] args) {
Vehicle v1 = new Car();
v1.park(); // compile from Vehicle, run from Car
System.out.println("year : " + v1.year); // compile from Vehicle, run from Vehicle
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q125

class Vehicle{
int year = 2000;
public void park(){
System.out.println("Vehicle Parking");
}
}

class Car extends Vehicle{


int year = 2001;
public void park(){
System.out.println("Car Parking");
}

public void printYear(){


int year = 2002;
System.out.println("Local : " + year);
System.out.println("This : " + this.year);
System.out.println("Super : " + super.year);
}
}

class Example{
public static void main(String[] args) {
Car c1 = new Car();
c1.printYear();
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q126

class Vehicle{
public void park(){
System.out.println("Vehicle Parking");
}

public void callPark(){


park();
}
}

class Car extends Vehicle{


public void park(){
System.out.println("Car Parking");
}
}

class Example{
public static void main(String[] args) {
Car c1 = new Car();
c1.callPark();
}
}
Class “Object”
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q127

class Customer /* compiler inserts 'extends Object'*/{

class Example {
public static void main(String[] args) {
Customer c1 = new Customer();

c1.hashCode(); // Legal
c1.toString();
c1.equals(c1);
c1.getClass();
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q128

class Customer /* compiler inserts 'extends Object'*/{

Customer(){
super(); // Legal
}

class Example {
public static void main(String[] args) {
Customer c1 = new Customer();
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q129

class Customer{
}

class Example {
public static void main(String[] args) {
int[] ar = new int[10];
ar.toString();
ar.equals(ar);
ar.getClass();
ar.hashCode();

String s1 = "ABC";

s1.toString();
s1.equals(s1);
s1.getClass();
s1.hashCode();
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q130

import java.util.Random;

import javax.swing.JFrame;

class Customer{

class Example {
public static void main(String[] args) {
Object obj;

obj = new String("ABC");


obj = new Customer();
obj = new Int[5];
obj = new JFrame();
obj = new Random();
}
}
Method ‘public int hashCode()’
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q131

class Customer{
private int code;
private String name;

public Customer(int code, String name){


this.code = code;
this.name = name;
}
}

class Example {
public static void main(String[] args) {
Customer c1 = new Customer(1001, "Customer 1");
System.out.println(c1.hashCode());

Customer c2 = new Customer(1002, "Customer 2");


System.out.println(c2.hashCode());
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q132

class Customer{
private int code;
private String name;

public Customer(int code, String name){


this.code = code;
this.name = name;
}
}

class Example {
public static void main(String[] args) {
Customer c1 = new Customer(1001, "Customer 1");
System.out.println(c1);
int hashCode = c1.hashCode();
System.out.println(hashCode);
System.out.println(Integer.toHexString(hashCode));
}
}

Method “public Class getClass()”


/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q133

class Customer{
private int code;
private String name;

public Customer(int code, String name){


this.code = code;
this.name = name;
}
}

class Example {
public static void main(String[] args) {
Customer c1 = new Customer(1001, "Customer 1");

Class templateObject = c1.getClass();


System.out.println(templateObject.getName());

}
}

Method “Public String toString()”


/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q134

class Customer{
private int code;
private String name;

public Customer(int code, String name){


this.code = code;
this.name = name;
}
// public String toString(){
// String className = getClass().getName();
// String hexString = Integer.toHexString(this.code);
// return className + "@" + hexString;
// }
}

class Example {
public static void main(String[] args) {
Customer c1 = new Customer(1001, "Customer 1");

System.out.println(c1.toString());
System.out.println(c1); // compiler inserts "toString()"
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q135

class Customer{
private int code;
private String name;

public Customer(int code, String name){


this.code = code;
this.name = name;
}

// public String toString(){


// String className = getClass().getName();
// String hexString = Integer.toHexString(this.code);
// return className + "@" + hexString;
// }
}

class Example {
public static void main(String[] args) {
String s1 = "ABC";
System.out.println(s1.toString());
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q136 Exercise
============

class Customer{
private int code;
private String name;

public Customer(int code, String name){


this.code = code;
this.name = name;
}

// public String toString(){


// String className = getClass().getName();
// String hexString = Integer.toHexString(this.code);
// return className + "@" + hexString;
// }
}

class Example {
public static void main(String[] args) {
Customer c1 = new Customer(1001, "Customer 1");

System.out.println(c1); // 1001 - Customer 1


}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q137 form Q136
==============

class Customer{
private int code;
private String name;

public Customer(int code, String name){


this.code = code;
this.name = name;
}

// public String toString(){


// String className = getClass().getName();
// String hexString = Integer.toHexString(this.code);
// return className + "@" + hexString;
// }

public String toString(){


return this.code + " - " + this.name;
}
}

class Example {
public static void main(String[] args) {
Customer c1 = new Customer(1001, "Customer 1");

System.out.println(c1); // 1001 - Customer 1


}
}

Method “public boolean equals(Object obj)”


/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q138

class Customer{
private int code;
private String name;

public Customer(int code, String name){


this.code = code;
this.name = name;
}

public String toString(){


return this.code + " - " + this.name;
}

public boolean equals(Object object){


return this.hashCode() == object.hashCode();
}
}

class Example {
public static void main(String[] args) {
Customer c1 = new Customer(1001, "Customer 1");
Customer c2 = new Customer(1001, "Customer 1");

System.out.println("c1 == c2 : " + (c1 == c2)); // false


System.out.println("c1 == c2 : " + c1.equals(c2)); // false
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q139

class Customer{
private int code;
private String name;

public Customer(int code, String name){


this.code = code;
this.name = name;
}

public String toString(){


return this.code + " - " + this.name;
}

public boolean equals(Object object){


return this.hashCode() == object.hashCode();
}
}

class Example {
public static void main(String[] args) {
Customer c1 = new Customer(1001, "Customer 1");
Customer c2 = new Customer(1001, "Customer 1");
Customer c3 = new Customer(1002, "Customer 2");
Customer c4 = c1;

System.out.println("c1 == c2 : " + c1.equals(c2)); // false


System.out.println("c1 == c3 : " + c1.equals(c3)); // false
System.out.println("c1 == c4 : " + c1.equals(c4)); // true
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q140

class Customer{
private int code;
private String name;

public Customer(int code, String name){


this.code = code;
this.name = name;
}

public String toString(){


return this.code + " - " + this.name;
}

public boolean equals(Object object){


Customer customer = (Customer)object;
return this.code == customer.code;
}
}

class Example {
public static void main(String[] args) {
Customer c1 = new Customer(1001, "Customer 1");
Customer c2 = new Customer(1001, "Customer 1");
Customer c3 = new Customer(1002, "Customer 2");
Customer c4 = c1;

System.out.println("c1 == c2 : " + c1.equals(c2)); // true


System.out.println("c1 == c3 : " + c1.equals(c3)); // false
System.out.println("c1 == c4 : " + c1.equals(c4)); // true
}
}

Method Overriding Rules


/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q141

class Vehicle{
public void park(){
System.out.println("Vehicle Parking");
}
}

class Car extends Vehicle{


public void park(){
System.out.println("Car Parking");
}
}
class Example {
public static void main(String[] args) {
Vehicle v1 = new Car();
v1.park();
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q142 Rule 1 (Static Methods)
=======================
Case 1
=====

class Vehicle{
public static void park(){
System.out.println("Vehicle Parking");
}
}

class Car extends Vehicle{


public void park(){ // Illegal
System.out.println("Car Parking");
}
}
class Example {
public static void main(String[] args) {
Vehicle v1 = new Car();
v1.park();
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q143 Case 2
===========
class Vehicle{
public void park(){
System.out.println("Vehicle Parking");
}
}

class Car extends Vehicle{


public static void park(){ // Illegal
System.out.println("Car Parking");
}
}
class Example {
public static void main(String[] args) {
Vehicle v1 = new Car();
v1.park();
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q144 Case 3
==========

class Vehicle{
public static void park(){
System.out.println("Vehicle Parking");
}
}

class Car extends Vehicle{


public static void park(){
System.out.println("Car Parking");
}
}
class Example {
public static void main(String[] args) {
Vehicle v1 = new Car();
v1.park();
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q145 Rule 2 (private methods)
========================

class Vehicle{
private void park(){
System.out.println("Vehicle Parking");
}

public void callPark(){


park();
}
}

class Car extends Vehicle{


public void park(){
System.out.println("Car Parking");
}
}
class Example {
public static void main(String[] args) {
Vehicle v1 = new Car();
v1.callPark();
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q146 Rule 3 “final”
==============

class Vehicle{
public final void park(){
System.out.println("Vehicle Parking");
}
}

class Car extends Vehicle{


public void park(){ // Illegal
System.out.println("Car Parking");
}
}
class Example {
public static void main(String[] args) {
Vehicle v1 = new Car();
v1.callPark();
}
}

Abstract Classes and Abstract Methods


/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q147

class Vehicle{
public void park(){
System.out.println("Vehicle Parking");
}
}

class Car extends Vehicle{


public void park(){
System.out.println("Car Parking");
}
}

class Bus extends Vehicle{


public void park(){
System.out.println("Bus Parking");
}
}

class Van extends Vehicle{


public void park(){
System.out.println("Van Parking");
}
}
class Example {
public static void main(String[] args) {
Vehicle[] vehicles = {new Car(), new Van(), new Bus()};
for (Vehicle vehicle : vehicles) {
vehicle.park();
}
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q148

class Vehicle{
public void park(){ // Logical Issue

}
}

class Car extends Vehicle{


public void park(){
System.out.println("Car Parking");
}
}

class Bus extends Vehicle{


public void park(){
System.out.println("Bus Parking");
}
}

class Van extends Vehicle{


public void park(){
System.out.println("Van Parking");
}
}
class Example {
public static void main(String[] args) {
Vehicle[] vehicles = {new Car(), new Van(), new Bus()};
for (Vehicle vehicle : vehicles) {
vehicle.park();
}
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q149 from Q148
=============

class Vehicle{
public void park(); // Illegal
}
class Car extends Vehicle{
public void park(){
System.out.println("Car Parking");
}
}

class Bus extends Vehicle{


public void park(){
System.out.println("Bus Parking");
}
}

class Van extends Vehicle{


public void park(){
System.out.println("Van Parking");
}
}
class Example {
public static void main(String[] args) {
Vehicle[] vehicles = {new Car(), new Van(), new Bus()};
for (Vehicle vehicle : vehicles) {
vehicle.park();
}
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q150

abstract class Vehicle{


abstract public void park();
}

class Car extends Vehicle{


public void park(){
System.out.println("Car Parking");
}
}

class Bus extends Vehicle{


public void park(){
System.out.println("Bus Parking");
}
}

class Van extends Vehicle{


public void park(){
System.out.println("Van Parking");
}
}
class Example {
public static void main(String[] args) {
Vehicle[] vehicles = {new Car(), new Van(), new Bus()};
for (Vehicle vehicle : vehicles) {
vehicle.park();
}
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q151 From Q122
=========

import javax.swing.*;
import javax.swing.event.*;

import java.awt.*;
import java.awt.event.*;

abstract class WaterLevelObserver extends JFrame{


abstract public void update(int waterLevel);
}

class DisplayFrame extends WaterLevelObserver{


private JLabel displayLabel;

DisplayFrame(){
setSize(300, 300);
setLocationRelativeTo(null);
setTitle("Display");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());
this.displayLabel = new JLabel("50");
this.displayLabel.setFont(new Font("", 1, 30));
add(displayLabel);
setVisible(true);
}

public void update(int waterLevel){


this.displayLabel.setText(Integer.toString(waterLevel));
}
}

class AlarmFrame extends WaterLevelObserver{


private JLabel alarmLabel;
AlarmFrame(){
setSize(300, 300);
setLocationRelativeTo(null);
setTitle("Alarm");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());

this.alarmLabel = new JLabel("Off");


this.alarmLabel.setFont(new Font("", 1, 30));
add(alarmLabel);

setVisible(true);
}

public void update(int waterLevel){


this.alarmLabel.setText(waterLevel >=75? "On" : "Off");
}
}

class SplitterFrame extends WaterLevelObserver{


private JLabel splitterLabel;

SplitterFrame(){
setSize(300, 300);
setLocationRelativeTo(null);
setTitle("Splitter");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());

this.splitterLabel = new JLabel("Off");


this.splitterLabel.setFont(new Font("", 1, 30));
add(splitterLabel);

setVisible(true);
}

public void update(int waterLevel){


this.splitterLabel.setText(waterLevel >=90 ? "On" : "Off");
}
}

class SMSSenderFrame extends WaterLevelObserver{


private JLabel smsLabel;

SMSSenderFrame(){
setSize(300, 300);
setLocationRelativeTo(null);
setTitle("SMS Sender");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());

this.smsLabel = new JLabel("");


this.smsLabel.setFont(new Font("", 1, 30));
add(smsLabel);

setVisible(true);
}

public void update(int waterLevel){


this.smsLabel.setText("SMS Sending : " + waterLevel);
}
}

class WaterTankController{
private WaterLevelObserver[] observers = new WaterLevelObserver[0];

private int waterLevel;

public void addWaterLevelObserver(WaterLevelObserver levelObserver){


WaterLevelObserver[] temp = new WaterLevelObserver[observers.length + 1];
for(int i = 0; i < observers.length; i++){
temp[i] = observers[i];
}
temp[temp.length-1] = levelObserver;
observers = temp;
}

public void setWaterLevel(int waterLevel){


if(this.waterLevel != waterLevel){
this.waterLevel = waterLevel;
notifyObject();
}
}

public void notifyObject(){


for(WaterLevelObserver waterLevelObserver : observers){
waterLevelObserver.update(waterLevel);
}
}
}

class WaterTankFrame extends JFrame{

private JSlider waterLevelSlider;


private int waterLevel = 0;
private WaterTankController waterTankController;

WaterTankFrame(WaterTankController waterTankController){
this.waterTankController = waterTankController;
setSize(300, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("Water Tank");
setLocationRelativeTo(null);

this.waterLevelSlider = new JSlider(JSlider.VERTICAL);


this.waterLevelSlider.setMajorTickSpacing(10);
this.waterLevelSlider.setPaintLabels(true);
this.waterLevelSlider.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
waterLevel = waterLevelSlider.getValue();
waterTankController.setWaterLevel(waterLevel);
}
});

add(waterLevelSlider);

setVisible(true);
}

}
class Example{
public static void main(String[] args) {
WaterTankController controller = new WaterTankController();
controller.addWaterLevelObserver(new AlarmFrame());
controller.addWaterLevelObserver(new SplitterFrame());
controller.addWaterLevelObserver(new DisplayFrame());
controller.addWaterLevelObserver(new SMSSenderFrame());
WaterTankFrame f1 = new WaterTankFrame(controller);
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q152 Case 1
==========

class Vehicle{
public void park(); // Illegal
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q153 Case 2
==========

abstract class Vehicle{


abstract public void park(){ // Illegal

}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q154 Case 3
===========

class Vehicle{
abstract public void park(); //Illegal
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q155 Case 4
==========

abstract class Vehicle{


abstract public void park();
public void start(){
// body
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q156 Case 5
==========

abstract class Vehicle{


public void park(){
// body
}

public void start(){


// body
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q157 Case 6
==========

abstract class Vehicle{


abstract public void park();
abstract public void start();
public void stop(){
//
}
}

class Car extends Vehicle{}

class Jeep extends Vehicle{


public void park(){
//
}
}

class Van extends Vehicle{


public void start(){
//
}
}

class Bus extends Vehicle{


public void park(){
//
}

public void start(){


//
}
}

abstract class Ship extends Vehicle{}

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

}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q158 Case 7
==========

abstract class Vehicle{


abstract public void park();
}

class Example{
public static void main(String[] args) {
Vehicle v1; // Legal

v1 = new Vehicle(); // Illegal


}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q159 Case 8
===========

abstract class Vehicle{


abstract public void park();
}

class Car extends Vehicle{


public void park() {
System.out.println("Car parking");
}
}

class Example{
public static void main(String[] args) {
Vehicle v1; // Legal

v1 = new Car(); // Legal


}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q160 Case 9
==========

abstract class Vehicle{

int year;

abstract public void park();


abstract public void start();
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q161 Case 10
===========

abstract class Vehicle{

int year;

Vehicle(){
//
}

abstract public void park();


abstract public void start();
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q161 Case 11
===========

abstract class Vehicle{


abstract public static void park(); // Illegal
abstract public final void start(); // Illegal
abstract private void stop(); // Illegal
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q162 Case 12
============

class Animal{
public void eat(){

}
}

class Dog extends Animal{} // Legal

abstract class Lion extends Animal{


abstract public void eat(); // legal
}

class Cat extends Lion{} // Illegal

Java interfaces
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q163

/* abstract class Vehicle{


abstract public void park();
abstract public void start();
abstract public void stop();
}*/
interface Vehicle{
void park();
void start();
void stop();
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q164

interface Vehicle{
void park();
}

//class Car extends Vehicle{}// Illegal

class Car implements Vehicle{


public void park(){
System.out.println("Car Parking");
}
}

class Example{
public static void main(String[] args) {
Vehicle v1 = new Car();
v1.park();
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q165 Case 1
==========

interface Vehicle{

//class Car extends Vehicle{}// Wrong


class Car implements Vehicle{} // Correct
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q166 Case 2
==========

abstract interface Vehicle{ // Implicitly Abstract

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q167 Case 3
==========

abstract interface Vehicle{ // Implicitly Abstract


void park(); // Implicitly Abstract
abstract void start(); // Implicitly Abstract
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q168 Case 4
==========

interface Vehicle{
void park(); // Implicitly public
public void start(); // Implicitly public
protected void stop(); // Illegal
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q169 Case 5
==========

interface Vehicle{
void park(){ // Illegal
// body
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q170 Case 6
==========

interface Vehicle{
void park();
void start();
}

class Car implements Vehicle{}

class Van implements Vehicle{


public void park(){
System.out.println("Van Parking");
}
}

class Bus implements Vehicle{


public void start(){
System.out.println("Bus Starting");
}
}

class Jeep implements Vehicle{


public void park(){
System.out.println("Jeep Parking");
}
public void start(){
System.out.println("Jeep Starting");
}
}

abstract class Ship implements Vehicle{}

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

}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q171 Case 7
==========

interface Vehicle{
void park();
}

class Example{
public static void main(String[] args) {
Vehicle v1; // Legal
v1 = new Vehicle(); // Illegal
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q172 Case 8
==========

interface Vehicle{
void park();
}

class Car implements Vehicle{


public void park(){
System.out.println("Car Parking");
}
}

class Example{
public static void main(String[] args) {
Vehicle v1; // Legal
v1 = new Car(); // Legal
v1.park();
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q173 Case 9
===========

interface Vehicle{
int year = 2000; // implicitly public, final, static
void park();
}
class Example{
public static void main(String[] args) {
Vehicle.year = 2005; // Illegal
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q174 Case 10
==============

interface Vehicle{
int year = 2000;

Vehicle(){ // Illegal

void park();

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q175 Exercise from Q150
====================

interface Vehicle{
void park();
}

class Car implements Vehicle{


public void park(){
System.out.println("Car Park");
}
}
class Van implements Vehicle{
public void park(){
System.out.println("Van Park");
}
}
class Bus implements Vehicle{
public void park(){
System.out.println("Bus Park");
}
}

class Example {
public static void main(String[] args) {
Vehicle[] vehicles = {new Car(), new Van(), new Bus()};
for (Vehicle vehicle : vehicles) {
vehicle.park();
}
}
}

Blueprint of a Class
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q176

interface Date{
void setDate(int year, int month, int day);
void setYear(int year);
void setMonth(int month);
void setDay(int day);
void printDate();
int getYear();
int getMonth();
int getDay();
}

class DateImpl implements Date{


private int year;
private int month;
private int day;

public void setDate(int year, int month, int day){


this.year = year;
this.month = month;
this.day = day;
}

public void setYear(int year){


this.year = year;
}

public void setMonth(int month){


this.month = month;
}

public void setDay(int day){


this.day = day;
}
public void printDate(){
System.out.println(this.year + " - " + this.month + " - " + this.day);
}

public int getYear(){


return this.year;
}

public int getMonth(){


return this.month;
}

public int getDay(){


return this.day;
}
}

class Example {
public static void main(String[] args) {
Date date = new DateImpl();
date.setDate(2024, 7, 31);
date.printDate();
}
}

Multiple inheritance with Interfaces


/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q177 Case 11
===========

class Animal{

interface Lion{

class Dog extends Animal implements Lion{ // Legal


}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q178 from Q151
=============

import javax.swing.*;
import javax.swing.event.*;

import java.awt.*;
import java.awt.event.*;

interface WaterLevelObserver{
void update(int waterLevel);
}

class DisplayFrame extends JFrame implements WaterLevelObserver{


private JLabel displayLabel;

DisplayFrame(){
setSize(300, 300);
setLocationRelativeTo(null);
setTitle("Display");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());
this.displayLabel = new JLabel("50");
this.displayLabel.setFont(new Font("", 1, 30));
add(displayLabel);
setVisible(true);
}

public void update(int waterLevel){


this.displayLabel.setText(Integer.toString(waterLevel));
}
}

class AlarmFrame extends JFrame implements WaterLevelObserver{


private JLabel alarmLabel;
AlarmFrame(){
setSize(300, 300);
setLocationRelativeTo(null);
setTitle("Alarm");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());

this.alarmLabel = new JLabel("Off");


this.alarmLabel.setFont(new Font("", 1, 30));
add(alarmLabel);

setVisible(true);
}

public void update(int waterLevel){


this.alarmLabel.setText(waterLevel >=75? "On" : "Off");
}
}

class SplitterFrame extends JFrame implements WaterLevelObserver{


private JLabel splitterLabel;

SplitterFrame(){
setSize(300, 300);
setLocationRelativeTo(null);
setTitle("Splitter");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());

this.splitterLabel = new JLabel("Off");


this.splitterLabel.setFont(new Font("", 1, 30));
add(splitterLabel);

setVisible(true);
}

public void update(int waterLevel){


this.splitterLabel.setText(waterLevel >=90 ? "On" : "Off");
}
}

class SMSSenderFrame extends JFrame implements WaterLevelObserver{


private JLabel smsLabel;

SMSSenderFrame(){
setSize(300, 300);
setLocationRelativeTo(null);
setTitle("SMS Sender");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());

this.smsLabel = new JLabel("");


this.smsLabel.setFont(new Font("", 1, 30));
add(smsLabel);

setVisible(true);
}

public void update(int waterLevel){


this.smsLabel.setText("SMS Sending : " + waterLevel);
}
}

class WaterTankController{
private WaterLevelObserver[] observers = new WaterLevelObserver[0];

private int waterLevel;

public void addWaterLevelObserver(WaterLevelObserver levelObserver){


WaterLevelObserver[] temp = new WaterLevelObserver[observers.length + 1];
for(int i = 0; i < observers.length; i++){
temp[i] = observers[i];
}
temp[temp.length-1] = levelObserver;
observers = temp;
}

public void setWaterLevel(int waterLevel){


if(this.waterLevel != waterLevel){
this.waterLevel = waterLevel;
notifyObject();
}
}

public void notifyObject(){


for(WaterLevelObserver waterLevelObserver : observers){
waterLevelObserver.update(waterLevel);
}
}
}

class WaterTankFrame extends JFrame{


private JSlider waterLevelSlider;
private int waterLevel = 0;
private WaterTankController waterTankController;

WaterTankFrame(WaterTankController waterTankController){
this.waterTankController = waterTankController;
setSize(300, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("Water Tank");
setLocationRelativeTo(null);

this.waterLevelSlider = new JSlider(JSlider.VERTICAL);


this.waterLevelSlider.setMajorTickSpacing(10);
this.waterLevelSlider.setPaintLabels(true);
this.waterLevelSlider.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
waterLevel = waterLevelSlider.getValue();
waterTankController.setWaterLevel(waterLevel);
}
});

add(waterLevelSlider);

setVisible(true);
}

}
class Example{
public static void main(String[] args) {
WaterTankController controller = new WaterTankController();
controller.addWaterLevelObserver(new AlarmFrame());
controller.addWaterLevelObserver(new SplitterFrame());
controller.addWaterLevelObserver(new DisplayFrame());
controller.addWaterLevelObserver(new SMSSenderFrame());
WaterTankFrame f1 = new WaterTankFrame(controller);
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q179 Case 12
===========
interface Lion{}
interface Fox extends Lion{}
interface Cat{}
interface Dog extends Lion, Cat{}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q180 Case 13
===========

class Lion{}
interface Cat extends Lion{} // Illegal
interface Fox implements Lion{} // Illegal

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q181 Case 14
===========

class Dog{}
interface Lion{}
interface Cat{}

class Fox extends Dog implements Lion, Cat{}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q182 Case 15
===========

interface Vehicle{
void park();

default void start(){


System.out.println("Vehicle Start");
}
}

class Car implements Vehicle{ // Legal, Since JDK 1.8


public void park(){
System.out.println("Car Parking");
}
}

class Example{
public static void main(String[] args) {
Vehicle v1 = new Car();
v1.park();
v1.start();
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q183 Case 16
============

interface Vehicle{
void park();

default void start(){


System.out.println("Vehicle Start");
}

static void stop(){


System.out.println("Vehicle stop");
}
}

class Car implements Vehicle{ // Legal, Since JDK 1.8


public void park(){
System.out.println("Car Parking");
}
}

class Example{
public static void main(String[] args) {
Vehicle v1 = new Car();
v1.park();
v1.start();
Vehicle.stop();
}
}
Interface as Contract
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q184

import java.awt.FlowLayout;

import javax.swing.*;

class Calculator extends JFrame{


private JButton button;

Calculator(){
setSize(400,400);
setLocationRelativeTo(null);
setTitle("Calculator");
setLayout(new FlowLayout());
setDefaultCloseOperation(EXIT_ON_CLOSE);

button = new JButton("Button");


button.addActionListener(new MyClass()); // Illegal
add(button);

setVisible(true);
}
}

class MyClass{
public void myMethod(){
System.out.println("You pressed the Button");
}
}

class Example{
public static void main(String[] args) {
new Calculator();
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q185 ActionListener & ActionEvent
===========================

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

class Calculator extends JFrame{


private JButton button;

Calculator(){
setSize(400,400);
setLocationRelativeTo(null);
setTitle("Calculator");
setLayout(new FlowLayout());
setDefaultCloseOperation(EXIT_ON_CLOSE);

button = new JButton("Button");


button.addActionListener(new MyClass());
add(button);

setVisible(true);
}
}

// interface ActionListener{
// void actionPerformed(ActionEvent e);
// }

class MyClass implements ActionListener{


public void actionPerformed(ActionEvent e) {
System.out.println("You pressed the Button");
}
}

class Example{
public static void main(String[] args) {
new Calculator();
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q186 Exercise
===========

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

class Calculator extends JFrame {


private JButton button;

Calculator() {
setSize(400, 400);
setLocationRelativeTo(null);
setTitle("Calculator");
setLayout(new FlowLayout());
setDefaultCloseOperation(EXIT_ON_CLOSE);

button = new JButton("Button");


button.addMouseListener(new MyClass());
add(button);

setVisible(true);
}
}

// interface MouseListener {
// public void mouseClicked(MouseEvent e);
// public void mouseEntered(MouseEvent e);
// public void mouseExited(MouseEvent e);
// public void mousePressed(MouseEvent e);
// public void mouseReleased(MouseEvent e);
// }

class MyClass {

class Example {
public static void main(String[] args) {
new Calculator();
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q187 from Q186 MouseListener vs MouseEvent
=====================================

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.*;

class Calculator extends JFrame {


private JButton button;

Calculator() {
setSize(400, 400);
setLocationRelativeTo(null);
setTitle("Calculator");
setLayout(new FlowLayout());
setDefaultCloseOperation(EXIT_ON_CLOSE);

button = new JButton("Button");


button.addMouseListener(new MyClass());
add(button);

setVisible(true);
}
}

// interface MouseListener {
// public void mouseClicked(MouseEvent e);
// public void mouseEntered(MouseEvent e);
// public void mouseExited(MouseEvent e);
// public void mousePressed(MouseEvent e);
// public void mouseReleased(MouseEvent e);
// }

class MyClass implements MouseListener{


public void mouseClicked(MouseEvent e) {
System.out.println("Clicked");
}

public void mouseEntered(MouseEvent e) {


System.out.println("Entered");
}

public void mouseExited(MouseEvent e) {


System.out.println("Exited");
}

public void mousePressed(MouseEvent e) {


System.out.println("Pressed");
}

public void mouseReleased(MouseEvent e) {


System.out.println("Released");
}
}

class Example {
public static void main(String[] args) {
new Calculator();
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q188

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

class Calculator extends JFrame {


JTextField textField;
JButton button;

Calculator() {
setSize(400, 400);
setLocationRelativeTo(null);
setLayout(new FlowLayout());
setDefaultCloseOperation(EXIT_ON_CLOSE);
textField = new JTextField(15);
textField.setFont(new Font("", 1, 25));
add(textField);

button = new JButton("Set Title");


button.setFont(new Font("", 1, 25));
button.addActionListener(new MyClass());
add(button);

setVisible(true);
}
}

class MyClass implements ActionListener{


public void actionPerformed(ActionEvent e) {
String title = textField.getText();
setTitle(title);
}
}

class Example {
public static void main(String[] args) {
new Calculator();
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q189 Option 1
============

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

class Calculator extends JFrame {


JTextField textField;
JButton button;

Calculator() {
setSize(400, 400);
setLocationRelativeTo(null);
setLayout(new FlowLayout());
setDefaultCloseOperation(EXIT_ON_CLOSE);

textField = new JTextField(15);


textField.setFont(new Font("", 1, 25));
add(textField);

button = new JButton("Set Title");


button.setFont(new Font("", 1, 25));
button.addActionListener(new MyClass(this));
add(button);

setVisible(true);
}
}

class MyClass implements ActionListener{

private Calculator calculator;

MyClass(Calculator calculator) {
this.calculator = calculator;
}
public void actionPerformed(ActionEvent e) {
String title = calculator.textField.getText();
calculator.setTitle(title);
}
}

class Example {
public static void main(String[] args) {
new Calculator();
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q190 Option 2
============

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
class Calculator extends JFrame implements ActionListener{
JTextField textField;
JButton button;

Calculator() {
setSize(400, 400);
setLocationRelativeTo(null);
setLayout(new FlowLayout());
setDefaultCloseOperation(EXIT_ON_CLOSE);

textField = new JTextField(15);


textField.setFont(new Font("", 1, 25));
add(textField);

button = new JButton("Set Title");


button.setFont(new Font("", 1, 25));
button.addActionListener(this);
add(button);

setVisible(true);
}

public void actionPerformed(ActionEvent e) {


String title = textField.getText();
setTitle(title);
}
}

class Example {
public static void main(String[] args) {
new Calculator();
}
}
Inner Class

Regular Inner Class


/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q191 Option 3

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

class Calculator extends JFrame {


JTextField textField;
JButton button;

Calculator() {
setSize(400, 400);
setLocationRelativeTo(null);
setLayout(new FlowLayout());
setDefaultCloseOperation(EXIT_ON_CLOSE);

textField = new JTextField(15);


textField.setFont(new Font("", 1, 25));
add(textField);

button = new JButton("Set Title");


button.setFont(new Font("", 1, 25));
button.addActionListener(new MyClass());
add(button);

setVisible(true);
}

class MyClass implements ActionListener{


public void actionPerformed(ActionEvent e) {
String title = textField.getText();
setTitle(title);
}
}
}

class Example {
public static void main(String[] args) {
new Calculator();
}
}

Local Inner Class


/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q192 Option 4

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

class Calculator extends JFrame {


JTextField textField;
JButton button;

Calculator() {
setSize(400, 400);
setLocationRelativeTo(null);
setLayout(new FlowLayout());
setDefaultCloseOperation(EXIT_ON_CLOSE);

textField = new JTextField(15);


textField.setFont(new Font("", 1, 25));
add(textField);

button = new JButton("Set Title");


button.setFont(new Font("", 1, 25));

class MyClass implements ActionListener{


public void actionPerformed(ActionEvent e) {
String title = textField.getText();
setTitle(title);
}
}

button.addActionListener(new MyClass());
add(button);

setVisible(true);
}
}

class Example {
public static void main(String[] args) {
new Calculator();
}
}

Anonymous Inner Class


/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q193 Option 5

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

class Calculator extends JFrame {


JTextField textField;
JButton button;

Calculator() {
setSize(400, 400);
setLocationRelativeTo(null);
setLayout(new FlowLayout());
setDefaultCloseOperation(EXIT_ON_CLOSE);

textField = new JTextField(15);


textField.setFont(new Font("", 1, 25));
add(textField);

button = new JButton("Set Title");


button.setFont(new Font("", 1, 25));

// Anonymous Inner Class


ActionListener ob = new ActionListener() {
public void actionPerformed(ActionEvent e) {
String title = textField.getText();
setTitle(title);
}
};
button.addActionListener(ob);
add(button);

setVisible(true);
}
}

class Example {
public static void main(String[] args) {
new Calculator();
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q194 Option 6 from Option 5
======================

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

class Calculator extends JFrame {


JTextField textField;
JButton button;

Calculator() {
setSize(400, 400);
setLocationRelativeTo(null);
setLayout(new FlowLayout());
setDefaultCloseOperation(EXIT_ON_CLOSE);

textField = new JTextField(15);


textField.setFont(new Font("", 1, 25));
add(textField);

button = new JButton("Set Title");


button.setFont(new Font("", 1, 25));

// Anonymous Inner Class


button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String title = textField.getText();
setTitle(title);
}
});
add(button);

setVisible(true);
}
}

class Example {
public static void main(String[] args) {
new Calculator();
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q195 Exercise
===========

interface Vehicle{
void park();
}

class Example {
public static void main(String[] args) {
Vehicle v1 = new Vehicle(){
public void park(){
System.out.println("Car parking");
}
};

v1.park();
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q196 Exercise
============

interface Vehicle{
void park();
}

class Example {
public static void main(String[] args) {
Vehicle v1 = new Vehicle(){
public void park(){
System.out.println("Car parking");
}
}//; // Illegal

v1.park();
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q197 Option 7
============

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

class Calculator extends JFrame {


JTextField textField;
JButton button;

Calculator() {
setSize(400, 400);
setLocationRelativeTo(null);
setLayout(new FlowLayout());
setDefaultCloseOperation(EXIT_ON_CLOSE);

textField = new JTextField(15);


textField.setFont(new Font("", 1, 25));
add(textField);
button = new JButton("Set Title");
button.setFont(new Font("", 1, 25));

// Anonymous Inner Class


/* ActionListener ob = new ActionListener() {
public void actionPerformed(ActionEvent e) {
String title = textField.getText();
setTitle(title);
}
}; */

ActionListener ob = (e) -> {


String title = textField.getText();
setTitle(title);
};

button.addActionListener(ob);
add(button);

setVisible(true);
}
}

class Example {
public static void main(String[] args) {
new Calculator();
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q198 Option 8
============

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

class Calculator extends JFrame {


JTextField textField;
JButton button;

Calculator() {
setSize(400, 400);
setLocationRelativeTo(null);
setLayout(new FlowLayout());
setDefaultCloseOperation(EXIT_ON_CLOSE);

textField = new JTextField(15);


textField.setFont(new Font("", 1, 25));
add(textField);

button = new JButton("Set Title");


button.setFont(new Font("", 1, 25));

button.addActionListener((e) -> {
String title = textField.getText();
setTitle(title);
});
add(button);

setVisible(true);
}
}

class Example {
public static void main(String[] args) {
new Calculator();
}
}
Lambda Expression
(Since JDK 1.8)
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q199

interface Vehicle{
public void park();
}
class Example {
public static void main(String[] args) {
Vehicle car = new Vehicle(){
public void park(){
System.out.println("Car Parking");
}
};

car.park();

Vehicle jeep = () -> {


System.out.println("Jeep Parking");
};

jeep.park();
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q200 Case 1
==========

interface Vehicle{
public void park();
}
class Example {
public static void main(String[] args) {
Vehicle v1 = () -> System.out.println("Car Parking");
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q201 Case 2
==========
interface Vehicle{
public void park();
}
class Example {
public static void main(String[] args) {
Vehicle v1 = () -> {
System.out.println("Statement 1");
System.out.println("Statement 1");
};
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q202 Case 3
==========

interface Vehicle{
public void park();
}
class Example {
public static void main(String[] args) {
Vehicle v1 = () -> {
System.out.println("Statement 1");
System.out.println("Statement 1");
}//; // Illegal
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q203 Case 4
==========

interface Vehicle{
public void park(int location);
}
class Example {
public static void main(String[] args) {
Vehicle v1 = (int location) -> {
System.out.println("Car parking : " + location);
};

v1.park(1000);

Vehicle v2 = (location) -> {


System.out.println("Car parking : " + location);
};

v2.park(1001);
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q204 Case 5
==========

interface Vehicle{
public boolean park();
}
class Example {
public static void main(String[] args) {
Vehicle v1 = () -> true;
//Vehicle v2 = () -> return true; // Illegal

Vehicle v3 = ()-> {
///
///
return true;
};
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q205 Case 6
==========

interface Vehicle{
public boolean park();
public boolean start();

}
class Example {
public static void main(String[] args) {
Vehicle v1 = ()-> {

};
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q206 Case 7
===========

interface Vehicle{
public void park();
default public void start(){
System.out.println("Default Implementation");
}

}
class Example {
public static void main(String[] args) {
Vehicle v1 = ()-> {
System.out.println("Car Parking");
};

v1.park();
v1.start();
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q207 Exercise
===========

interface Math{
public int operation(int num1, int num2);
}

class Addition implements Math{


public int operation(int num1, int num2){
return num1 + num2;
}
}

class Substraction implements Math{


public int operation(int num1, int num2){
return num1 - num2;
}
}
class Division implements Math{
public int operation(int num1, int num2){
return num1 / num2;
}
}

class Multipication implements Math{


public int operation(int num1, int num2){
return num1 * num2;
}
}

class Example {
public static void main(String[] args) {
int a = 100, b = 50;
Addition addition = new Addition();
Substraction substraction = new Substraction();
Division division = new Division();
Multiplication multiplication = new Multiplication();

System.out.println(a + " + " + b + " = " + addition.operation(a, b));


System.out.println(a + " - " + b + " = " + substraction.operation(a, b));
System.out.println(a + " * " + b + " = " + multiplication.operation(a, b));
System.out.println(a + " / " + b + " = " + division.operation(a, b));
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q208 (Local Inner)
===============

interface Math{
public int operation(int num1, int num2);
}

class Example {
public static void main(String[] args) {
int a = 100, b = 50;

class Addition implements Math{


public int operation(int num1, int num2){
return num1 + num2;
}
}

class Substraction implements Math{


public int operation(int num1, int num2){
return num1 - num2;
}
}

class Division implements Math{


public int operation(int num1, int num2){
return num1 / num2;
}
}

class Multiplication implements Math{


public int operation(int num1, int num2){
return num1 * num2;
}
}

Addition addition = new Addition();


Substraction substraction = new Substraction();
Division division = new Division();
Multiplication multiplication = new Multiplication();

System.out.println(a + " + " + b + " = " + addition.operation(a, b));


System.out.println(a + " - " + b + " = " + substraction.operation(a, b));
System.out.println(a + " * " + b + " = " + multipication.operation(a, b));
System.out.println(a + " / " + b + " = " + division.operation(a, b));
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q209 Anonymous Inner Class
========================

interface Math{
public int operation(int num1, int num2);
}

class Example {
public static void main(String[] args) {
int a = 100, b = 50;

Math addition = new Math(){


public int operation(int num1, int num2){
return num1+ num2;
}
};
Math substraction = new Math(){
public int operation(int num1, int num2){
return num1 - num2;
}
};
Math division = new Math(){
public int operation(int num1, int num2){
return num1 / num2;
}
};
Math multiplication = new Math(){
public int operation(int num1, int num2){
return num1 * num2;
}
};

System.out.println(a + " + " + b + " = " + addition.operation(a, b));


System.out.println(a + " - " + b + " = " + substraction.operation(a, b));
System.out.println(a + " * " + b + " = " + multiplication.operation(a, b));
System.out.println(a + " / " + b + " = " + division.operation(a, b));
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q210 Lambda Expression
====================

interface Math{
public int operation(int num1, int num2);
}

class Example {
public static void main(String[] args) {
int a = 100, b = 50;

Math addition = (num1, num2) -> num1+ num2;


Math substraction = (num1, num2) -> num1 - num2;
Math division = (num1, num2) -> num1 / num2;
Math multiplication = (num1, num2) -> num1 * num2;

System.out.println(a + " + " + b + " = " + addition.operation(a, b));


System.out.println(a + " - " + b + " = " + substraction.operation(a, b));
System.out.println(a + " * " + b + " = " + multiplication.operation(a, b));
System.out.println(a + " / " + b + " = " + division.operation(a, b));
}
}

Garbage Collector
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q211

class MyClass{
long[] ar = new long[1000000];
}
class Example {
public static void main(String[] args) {
System.out.println("Start Main");
for(int i = 0; i < 100000; i++){
System.out.println("i : " + i);
new MyClass();
}
System.out.println("End Main");
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q212

class MyClass{
long[] ar = new long[1000000];
}
class Example {
public static void main(String[] args) {
System.out.println("Start Main");
MyClass[] myClasses = new MyClass[100000];
for(int i = 0; i < 100000; i++){
System.out.println("i : " + i);
myClasses[i] = new MyClass();
}
System.out.println("End Main");
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q213 Case 1
==========

class MyClass{
long[] ar = new long[10000000];

public void finalize(){


System.out.println("Deleted....");
}
}
class Example {
public static void main(String[] args) {
System.out.println("Start Main");
for(int i = 0; i < 10000; i++){
System.out.println("i : " + i);
new MyClass();
}
System.out.println("End Main");
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q214 Case 2
==========

class MyClass{
long[] ar = new long[1000000];

public void finalize(){


System.out.println("Deleted....");
}
}
class Example {
public static void main(String[] args) {
System.out.println("Start Main");
new MyClass();
new MyClass();
new MyClass();

try { Thread.sleep(2000);} catch (Exception e) {}

System.out.println("End Main");
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q215 Case 3
==========

class MyClass{
long[] ar = new long[1000000];

public void finalize(){


System.out.println("Deleted....");
}
}
class Example {
public static void main(String[] args) {
System.out.println("Start Main");
new MyClass();
new MyClass();
new MyClass();

System.gc();

try { Thread.sleep(2000);} catch (Exception e) {}

System.out.println("End Main");
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q216 Case 4 (Null Referencing)
=========================

class MyClass{
long[] ar = new long[1000000];

public void finalize(){


System.out.println("Deleted....");
}
}
class Example {
public static void main(String[] args) {
System.out.println("Start Main");

MyClass c1 = new MyClass();


// c1...
// c1...
// c1...
// c1...

c1 = null;

System.gc();

try { Thread.sleep(2000);} catch (Exception e) {}

System.out.println("End Main");
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q217 Case 5 (Reassigning)
=====================

class MyClass{
long[] ar = new long[1000000];

public void finalize(){


System.out.println("Deleted....");
}
}
class Example {
public static void main(String[] args) {
System.out.println("Start Main");

MyClass c1 = new MyClass();


// c1...
// c1...
// c1...
// c1...
c1 = new MyClass();

System.gc();

try { Thread.sleep(2000);} catch (Exception e) {}

System.out.println("End Main");
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q218 Case 6
==========

class MyClass{
long[] ar = new long[1000000];

public void finalize(){


System.out.println("Deleted....");
}

public void myMethod(){


System.out.println("My Method");
}
}
class Example {
public static void main(String[] args) {
System.out.println("Start Main");

new MyClass().myMethod();

System.gc();

try { Thread.sleep(2000);} catch (Exception e) {}

System.out.println("End Main");
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q219 Case 7 Local Scope
====================

class MyClass{
long[] ar = new long[1000000];

public void finalize(){


System.out.println("Deleted....");
}

public void myMethod(){


System.out.println("My Method");
}
}
class Example {
public static void main(String[] args) {
int x = 10;
if(x > 0){
MyClass c1 = new MyClass();
}

System.gc();

try { Thread.sleep(2000);} catch (Exception e) {}

}
}

Object Reference Casting


/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q220

class A{
int a;
public void mA(){
System.out.println("mA of A");
}
}

class B extends A{
int b;
public void mB(){
System.out.println("mB of B");
}
}
class Example {
public static void main(String[] args) {
A a1 = new B();
a1.a = 100; // Legal
a1.mA(); // Legal

//a1.b = 200; // Illegal


//a1.mB(); // Illegal
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q221

class A{
int a;
public void mA(){
System.out.println("mA of A");
}
}

class B extends A{
int b;
public void mB(){
System.out.println("mB of B");
}
}
class Example {
public static void main(String[] args) {
A a1 = new B();
a1.a = 100; // Legal
a1.mA(); // Legal

// call MB

//a1.b = 200; // Illegal


//a1.mB(); // Illegal
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q222

class A{
int a;
public void mA(){
System.out.println("mA of A");
}
}

class B extends A{
int b;
public void mB(){
System.out.println("mB of B");
}
}
class Example {
public static void main(String[] args) {
A a1 = new B();
a1.a = 100; // Legal
a1.mA(); // Legal

// call MB

//B b1 = a1; // Illegal


}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q223

class A{
int a;
public void mA(){
System.out.println("mA of A");
}
}

class B extends A{
int b;
public void mB(){
System.out.println("mB of B");
}
}
class Example {
public static void main(String[] args) {
A a1 = new B();
a1.a = 100; // Legal
a1.mA(); // Legal

// call MB

B b1 = (B)a1; // Legal
b1.b = 200;
b1.mB();;
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q224 Case 1
==========

class A{
int a;
public void mA(){
System.out.println("mA of A");
}
}

class B extends A{
int b;
public void mB(){
System.out.println("mB of B");
}
}
class Example {
public static void main(String[] args) {
A a1 = new A();
a1.a = 100; // Legal
a1.mA(); // Legal

B b1 = (B) a1; // Legal, Runtime Error -> ClassCastException


b1.b = 200;
b1.mB();
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q225
class A {
int a;

public void mA() {


System.out.println("mA of A");
}
}

class B extends A {
int b;

public void mB() {


System.out.println("mB of B");
}
}

class Example {
public static void main(String[] args) {
A a1 = new A();
a1.a = 100; // Legal
a1.mA(); // Legal

if (a1 instanceof B) {
B b1 = (B) a1;
b1.b = 200;
b1.mB();
} else{
System.out.println("Not a instance of B");
}

}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q226 Exercise
===========

class A {}
class B extends A {}
class C extends B {}

class Example {
public static void main(String[] args) {
A a1 = new A();
A a2 = new B();
A a3 = new C();
B b1 = new B();
B b2 = new C();
C c1 = new C();

System.out.println("a1 instanceof A : " + (a1 instanceof A)); // true


System.out.println("a1 instanceof B : " + (a1 instanceof B)); // false
System.out.println("a1 instanceof C : " + (a1 instanceof C)); // false

System.out.println("a2 instanceof A : " + (a2 instanceof A)); // true


System.out.println("a2 instanceof B : " + (a2 instanceof B)); // true
System.out.println("a2 instanceof C : " + (a2 instanceof C)); // false

System.out.println("a3 instanceof A : " + (a3 instanceof A)); // true


System.out.println("a3 instanceof B : " + (a3 instanceof B)); // true
System.out.println("a3 instanceof C : " + (a3 instanceof C)); // true

System.out.println("b1 instanceof A : " + (b1 instanceof A)); // true


System.out.println("b1 instanceof B : " + (b1 instanceof B)); // true
System.out.println("b1 instanceof C : " + (b1 instanceof C)); // false

System.out.println("b2 instanceof A : " + (b2 instanceof A)); // true


System.out.println("b2 instanceof B : " + (b2 instanceof B)); // true
System.out.println("b2 instanceof C : " + (b2 instanceof C)); // true

System.out.println("c1 instanceof A : " + (c1 instanceof A)); // true


System.out.println("c1 instanceof B : " + (c1 instanceof B)); // true
System.out.println("c1 instanceof C : " + (c1 instanceof C)); // true
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q227 Case 3
==========

class A{}
class B{}

class Example {
public static void main(String[] args) {
A a1 = new A();
B b1 = new B();
a1 = (A) b1;
b1 = (B) a1;
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q228

class A{}
class B{}

class Example {
public static void main(String[] args) {
A a1 = new A();
B b1 = new B();

System.out.println(a1 instanceof A);


System.out.println(b1 instanceof B);

System.out.println(b1 instanceof A); // Compile Error


System.out.println(a1 instanceof B); // Compile Error
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q229 Case 4
==========

interface A{}
class B{}

class Example {
public static void main(String[] args) {
A a1 = null;
B b1 = null;

System.out.println(a1 instanceof A);


System.out.println(b1 instanceof B);

System.out.println(b1 instanceof A);


System.out.println(a1 instanceof B);
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q230 Case 5
===========

interface A{}
final class B{}

class Example {
public static void main(String[] args) {
A a1 = null;
B b1 = null;

System.out.println(a1 instanceof A);


System.out.println(b1 instanceof B);

System.out.println(b1 instanceof A); // Illegal


System.out.println(a1 instanceof B); // Illegal
}
}

Java Database Connectivity


/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q231 Step 1 Load MySql Driver
=========================

public class App {


public static void main(String[] args) {
Class.forName("com.mysql.cj.jdbc.Driver");
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q232 Step 2 Throw Exception
=======================

public class App {


public static void main(String[] args) throws ClassNotFoundException{
Class.forName("com.mysql.cj.jdbc.Driver");
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q233 Step 3 Create Connection
=========================

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class App {


public static void main(String[] args) throws ClassNotFoundException, SQLException{
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection =
DriverManager.getConnection("jdbc:mysql://localhost:3306/Supermarket", "root", "mysql");
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q234 Step 4 Execute Query
=====================

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class App {


public static void main(String[] args) throws ClassNotFoundException, SQLException{
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection =
DriverManager.getConnection("jdbc:mysql://localhost:3306/Supermarket", "root", "mysql");

Statement statement = connection.createStatement();


String sql = "SELECT * FROM Item";

ResultSet resultSet = statement.executeQuery(sql);

while (resultSet.next()) {
System.out.println(resultSet.getString("ItemCode") + " " +
resultSet.getString("Description") + " " +
resultSet.getString("PackSize") + " " +
resultSet.getDouble("UnitPrice") + " " +
resultSet.getInt("QtyOnHand"));
}
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q235 Exercise
============

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class App {


public static void main(String[] args) throws ClassNotFoundException, SQLException{
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection =
DriverManager.getConnection("jdbc:mysql://localhost:3306/Supermarket", "root", "mysql");

String sql = "SELECT * FROM Customer";


Statement statement = connection.createStatement();
ResultSet rst = statement.executeQuery(sql);

while (rst.next()) {
System.out.println(rst.getString(1) + " " + rst.getString(2) + " " + rst.getString(3));
}
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q236 Step 5 (Execute Update)
========================

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class App {


public static void main(String[] args) throws ClassNotFoundException, SQLException{
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection =
DriverManager.getConnection("jdbc:mysql://localhost:3306/Supermarket", "root", "mysql");

String sql = "INSERT INTO Item VALUES ('P048', 'Sunlight', '100g', 100.00, 250)";
Statement statement = connection.createStatement();

int result = statement.executeUpdate(sql);

System.out.println(result > 0 ? "Success" : "Fail");


}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q237

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;

public class App {


public static void main(String[] args) throws ClassNotFoundException, SQLException {
Scanner input = new Scanner(System.in);
System.out.print("Input Code : ");
String code = input.nextLine();

System.out.print("Input Title : ");


String title = input.nextLine();

System.out.print("Input Name : ");


String name = input.nextLine();

System.out.print("Input dob : ");


String dob = input.nextLine();

System.out.print("Input Address : ");


String address = input.nextLine();

System.out.print("Input City : ");


String city = input.nextLine();

System.out.print("Input province : ");


String province = input.nextLine();

System.out.print("Input Zip Code : ");


String zip = input.nextLine();

System.out.print("Input Salary : ");


Double salary = input.nextDouble();

Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection =
DriverManager.getConnection("jdbc:mysql://localhost:3306/Supermarket", "root", "mysql");

String sql = "INSERT INTO Customer VALUES ('" + code + "', '" + title + "' , '" + name + "', '"
+ dob + "', "
+ salary + ", '" + address + "', '" + city + "', '" + province + "', '" + zip + "')";

Statement statement = connection.createStatement();


int result = statement.executeUpdate(sql);
System.out.println(result > 0 ? "Success" : "Fail");
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q238 (Prepared Statement - Insert)
===========================

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;

public class App {


public static void main(String[] args) throws ClassNotFoundException, SQLException {
Scanner input = new Scanner(System.in);
System.out.print("Input Code : ");
String code = input.nextLine();

System.out.print("Input Title : ");


String title = input.nextLine();

System.out.print("Input Name : ");


String name = input.nextLine();

System.out.print("Input dob : ");


String dob = input.nextLine();

System.out.print("Input Address : ");


String address = input.nextLine();

System.out.print("Input City : ");


String city = input.nextLine();

System.out.print("Input province : ");


String province = input.nextLine();

System.out.print("Input Zip Code : ");


String zip = input.nextLine();

System.out.print("Input Salary : ");


Double salary = input.nextDouble();

Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection =
DriverManager.getConnection("jdbc:mysql://localhost:3306/Supermarket", "root", "mysql");

String sql = "INSERT INTO Customer VALUES (?,?,?,?,?,?,?,?,?)";

PreparedStatement statement = connection.prepareStatement(sql);


statement.setString(1, code);
statement.setString(2, title);
statement.setString(3, name);
statement.setString(4, dob);
statement.setDouble(5, salary);
statement.setString(6, address);
statement.setString(7, city);
statement.setString(8, province);
statement.setString(9, zip);
int result = statement.executeUpdate();
System.out.println(result > 0 ? "Success" : "Fail");
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q239 (Prepared Statement - Select)
============================

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;

public class App {


public static void main(String[] args) throws ClassNotFoundException, SQLException {
Scanner input = new Scanner(System.in);
System.out.print("Input Code : ");
String code = input.nextLine();

Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection =
DriverManager.getConnection("jdbc:mysql://localhost:3306/Supermarket", "root", "mysql");

String sql = "SELECT * FROM Customer WHERE CustID = ?";


PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1, code);

ResultSet rst = statement.executeQuery();

while (rst.next()) {
System.out.println(rst.getString(1) + " " + rst.getString(2) + " " + rst.getString(3) );
}

}
}
Singleton Design Pattern
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q240 Step 1
==========

class A{
public A(){}

public void myMethod(){


System.out.println("myMethod() in " + this);
}
}
class Example {
public static void main(String[] args) {
A a1 = new A();
a1.myMethod();

A a2 = new A();
a2.myMethod();
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q241 Step 2
==========

class A{
private static A a;

public A(){}

public static A getInstance(){


if(a == null){
a = new A();
}

return a;
}

public void myMethod(){


System.out.println("myMethod() in " + this);
}
}
class Example {
public static void main(String[] args) {
A a1 = new A();
a1.myMethod();

A a2 = new A();
a2.myMethod();
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q242 Step 3
==========

class A{
private static A a;

private A(){}

public static A getInstance(){


if(a == null){
a = new A();
}

return a;
}

public void myMethod(){


System.out.println("myMethod() in " + this);
}
}
class Example {
public static void main(String[] args) {
A a1 = A.getInstance();
a1.myMethod();

A a2 = A.getInstance();
a2.myMethod();
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q243 Step 7
==========

// App.java

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;

public class App {


public static void main(String[] args) throws ClassNotFoundException, SQLException {
Scanner input = new Scanner(System.in);
System.out.print("Input Code : ");
String code = input.nextLine();

Connection connection = DBConnection.getInstance().getConnection();

String sql = "SELECT * FROM Customer WHERE CustID = ?";


PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1, code);

ResultSet rst = statement.executeQuery();

while (rst.next()) {
System.out.println(rst.getString(1) + " " + rst.getString(2) + " " + rst.getString(3) );
}

}
}

// DBConnection.java

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DBConnection {


private static DBConnection dbConnection;
private Connection connection;

private DBConnection() throws ClassNotFoundException, SQLException{


Class.forName("com.mysql.cj.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/Supermarket",
"root", "mysql");
}

public static DBConnection getInstance() throws ClassNotFoundException, SQLException{


if(dbConnection ==null){
dbConnection = new DBConnection();
}

return dbConnection;
}

public Connection getConnection(){


return connection;
}
}

Enumerations
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q244

// class Color{
// public static final String RED = "RED";
// public static final String GREEN = "GREEN";
// public static final String BLACK = "BLACK";
// public static final String BLUE = "BLUE";
// }

enum Color{
RED, GREEN, BLACK, BLUE; // Enum Objects
}
class Example {
public static void main(String[] args) {
System.out.println(Color.RED);

Color c1 = Color.RED;
System.out.println(c1.toString());
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q245 Case 1
==========

enum Color{
RED, GREEN, BLACK, BLUE; // Enum Objects
}
class Example {
public static void main(String[] args) {
Color c1 = new Color(); // Illegal
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q246 Case 2
==========

enum Color{
RED, GREEN, BLACK, BLUE; // Enum Objects
}
class Example {
public static void main(String[] args) {
Color [] colors = Color.values();
for (Color color : colors) {
System.out.println(color);// color.toString();
}
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q247 Case 3
==========

enum Color {
RED, GREEN, BLACK, BLUE; // Enum Objects
}

class Example {
public static void main(String[] args) {
Color c1 = Color.RED;
switch (c1) {
case RED:
break;
case BLACK:
break;
case BLUE:
break;
case GREEN:
break;

default:
break;
}
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q248 Case 4
==========

enum Color {
RED, GREEN, BLACK, BLUE; // Enum Objects
}

class Example {
public static void main(String[] args) {
Color c1 = Color.valueOf("RED");
System.out.println(c1);
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q249 Case 5
==========

enum Color {
RED, GREEN, BLACK, BLUE; // Enum Objects

Color(){
System.out.println("Color()");
}
}

class Example {
public static void main(String[] args) {
Color c1 = Color.RED;
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q250

enum Color {
RED(1001), GREEN(1002), BLACK(1003), BLUE(1004); // Enum Objects

private int code;

Color(int code){
this.code = code;
}

public void setCode(int code){


this.code = code;
}

public int getCode(){


return this.code;
}
}

class Example {
public static void main(String[] args) {
Color c1 = Color.RED;
System.out.println(c1.getCode());
c1.setCode(2001);
System.out.println(c1.getCode());
}
}
Generics In Java
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q251

class List{
private int[] items = new int[10];
private int count = 0;

public void add(int item){


items[count++] = item;
}

public int get(int index){


return items[index];
}
}
class Example {
public static void main(String[] args) {
List list = new List();
list.add(100);
System.out.println(list.get(0));
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q252

class List{
private int[] items = new int[10];
private int count = 0;

public void add(int item){


items[count++] = item;
}

public int get(int index){


return items[index];
}
}

class Customer{

}
class CustomerList{
private Customer[] items = new Customer[10];
private int count = 0;

public void add(Customer item){


items[count++] = item;
}

public Customer get(int index){


return items[index];
}
}

class Example {
public static void main(String[] args) {
List list = new List();
list.add(100);
System.out.println(list.get(0));

CustomerList customerList = new CustomerList();


customerList.add(new Customer());
System.out.println(customerList.get(0));
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q253 from Q252
=============

class List{
private Object[] items = new Object[10];
private int count = 0;

public void add(Object item){


items[count++] = item;
}

public Object get(int index){


return items[index];
}
}

class Customer{
}

class Example {
public static void main(String[] args) {
List list = new List();
list.add(100); // -> Integer.valueOf(100); Wrapper Class
System.out.println(list.get(0));
list.add(new Customer());
System.out.println(list.get(1));
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q254 from Q253
=============

class List{
private Object[] items = new Object[10];
private int count = 0;

public void add(Object item){


items[count++] = item;
}

public Object get(int index){


return items[index];
}
}

class Customer{

class Example {
public static void main(String[] args) {
List list = new List();
list.add(10);
list.add("ABC");
list.add(new Customer());

int num = (int)list.get(0);


System.out.println(num);
Customer customer = (Customer)list.get(1);
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q255

class List<T>{ // Type Parameter for Class


private T[] items = (T[])new Object[10];
private int count = 0;

public void add(T item){


items[count++] = item;
}

public T get(int index){


return items[index];
}
}

class Customer{

class Example {
public static void main(String[] args) {
List<Integer> intList = new List();
intList.add(100);
intList.add(200);

// intList.add("ABC"); // Illegal

List<Customer> custList = new List();


custList.add(new Customer());
System.out.println(custList.get(0));
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q256

class List<T extends Number>{ // Type Parameter for Class


private T[] items = (T[])new Object[10];
private int count = 0;

public void add(T item){


items[count++] = item;
}

public T get(int index){


return items[index];
}
}

class Customer{

class Example {
public static void main(String[] args) {
List<Integer> intList = new List();
List<Byte> byteList = new List();

//List<Customer> custList = new List();

}
}

Collection Framework

Class ArrayList
As list
Type Safe
Indexing, Fast random Access
Insertion Order
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q257

import java.util.ArrayList;

class Customer {
private int code;
private String name;

Customer(int code, String name){


this.code = code;
this.name = name;
}

public String toString(){


return code + " " + name;
}
}

class Example {
public static void main(String[] args) {
ArrayList<Customer> customers = new ArrayList<>();
customers.add(new Customer(1001, "Customer 1"));
customers.add(new Customer(1002, "Customer 2"));
customers.add(new Customer(1003, "Customer 3"));
customers.add(new Customer(1004, "Customer 4"));
customers.add(new Customer(1005, "Customer 5"));

System.out.println(customers);
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q258

import java.util.ArrayList;

class Customer {
private int code;
private String name;

Customer(int code, String name){


this.code = code;
this.name = name;
}

public String toString(){


return code + " " + name;
}
}
class Example {
public static void main(String[] args) {
ArrayList<Customer> customers = new ArrayList<>();
customers.add(new Customer(1001, "Customer 1"));
customers.add(new Customer(1002, "Customer 2"));
customers.add(new Customer(1003, "Customer 3"));
customers.add(new Customer(1004, "Customer 4"));
customers.add(new Customer(1005, "Customer 5"));

System.out.println(customers);

Customer c1 = customers.get(0); // Indexing, and Fast Random Access


System.out.println(c1);

customers.add(1, new Customer(2002, "Customer new "));


System.out.println(customers);
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q259

import java.util.ArrayList;

class Customer {
private int code;
private String name;

Customer(int code, String name){


this.code = code;
this.name = name;
}

public String toString(){


return code + " " + name;
}
}

class Example {
public static void main(String[] args) {
ArrayList<Customer> customers = new ArrayList<>();
customers.add(new Customer(1001, "Customer 1"));
customers.add(new Customer(1002, "Customer 2"));
customers.add(new Customer(1003, "Customer 3"));
customers.add(new Customer(1004, "Customer 4"));
customers.add(new Customer(1005, "Customer 5"));

for(int i = 0; i < customers.size(); i++){


System.out.println(customers.get(i));
}

for (Customer customer : customers) {


System.out.println(customer);
}

customers.forEach(e->{
System.out.println(e);
} );
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q260

import java.util.ArrayList;

class Customer {
private int code;
private String name;

Customer(int code, String name){


this.code = code;
this.name = name;
}

public String toString(){


return code + " " + name;
}
}

class Example {
public static void main(String[] args) {
ArrayList<String> stringList = new ArrayList<>();
stringList.add("A");
stringList.add("B");
stringList.add("C");
stringList.add("D");
stringList.add("E");

System.out.println(stringList);

boolean b = stringList.contains("B");
System.out.println(b);

b = stringList.contains("X");
System.out.println(b);

stringList.remove(new String("C"));
System.out.println(stringList);
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q261 Exercise
============

import java.util.ArrayList;

class Customer {
private int code;
private String name;

Customer(int code, String name){


this.code = code;
this.name = name;
}

public String toString(){


return code + " " + name;
}
}

class Example {
public static void main(String[] args) {
ArrayList<Customer> customers = new ArrayList<>();
customers.add(new Customer(1001, "Customer 1"));
customers.add(new Customer(1002, "Customer 2"));
customers.add(new Customer(1003, "Customer 3"));
customers.add(new Customer(1004, "Customer 4"));
customers.add(new Customer(1005, "Customer 5"));
System.out.println(customers);

boolean b = customers.contains(new Customer(1002, "Customer 2"));


System.out.println(b);

customers.remove(new Customer(1002, "Customer 2"));


System.out.println(customers);
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q262 from Q261
=============

import java.util.ArrayList;

class Customer {
private int code;
private String name;

Customer(int code, String name){


this.code = code;
this.name = name;
}

public String toString(){


return code + " " + name;
}

public boolean equals(Object obj){


Customer c1 = (Customer) obj;
return this.code == c1.code;
}
}

class Example {
public static void main(String[] args) {
ArrayList<Customer> customers = new ArrayList<>();
customers.add(new Customer(1001, "Customer 1"));
customers.add(new Customer(1002, "Customer 2"));
customers.add(new Customer(1003, "Customer 3"));
customers.add(new Customer(1004, "Customer 4"));
customers.add(new Customer(1005, "Customer 5"));

System.out.println(customers);

boolean b = customers.contains(new Customer(1002, "Customer 2"));


System.out.println(b);

customers.remove(new Customer(1002, "Customer 2"));


System.out.println(customers);
}
}

Class LinkedList
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q263

import java.util.LinkedList;

class Customer {
private int code;
private String name;

Customer(int code, String name){


this.code = code;
this.name = name;
}

public String toString(){


return code + " " + name;
}

public boolean equals(Object obj){


Customer c1 = (Customer) obj;
return this.code == c1.code;
}
}

class Example {
public static void main(String[] args) {
LinkedList<Customer> customers = new LinkedList<>();
customers.add(new Customer(1001, "Customer 1"));
customers.add(new Customer(1002, "Customer 2"));
customers.add(new Customer(1003, "Customer 3"));
customers.add(new Customer(1004, "Customer 4"));
customers.add(new Customer(1005, "Customer 5"));

System.out.println(customers);

boolean b = customers.contains(new Customer(1002, "Customer 2"));


System.out.println(b);

customers.remove(new Customer(1002, "Customer 2"));


System.out.println(customers);

for (Customer customer : customers) {


System.out.println(customer);
}
}
}

LinkedList as Stack
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q264

import java.util.LinkedList;

class Customer {
private int code;
private String name;

Customer(int code, String name){


this.code = code;
this.name = name;
}

public String toString(){


return code + " " + name;
}

public boolean equals(Object obj){


Customer c1 = (Customer) obj;
return this.code == c1.code;
}
}

class Example {
public static void main(String[] args) {
LinkedList<Customer> customers = new LinkedList<>();
customers.add(new Customer(1001, "Customer 1"));
customers.add(new Customer(1002, "Customer 2"));
customers.add(new Customer(1003, "Customer 3"));
customers.add(new Customer(1004, "Customer 4"));
customers.add(new Customer(1005, "Customer 5"));

System.out.println(customers);
Customer topCustomer = customers.removeLast();
System.out.println(topCustomer);
System.out.println(customers);

topCustomer = customers.getLast();
System.out.println(topCustomer);
System.out.println(customers);
}
}

LinkedList as Queue
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q265

import java.util.LinkedList;

class Customer {
private int code;
private String name;

Customer(int code, String name){


this.code = code;
this.name = name;
}

public String toString(){


return code + " " + name;
}

public boolean equals(Object obj){


Customer c1 = (Customer) obj;
return this.code == c1.code;
}
}

class Example {
public static void main(String[] args) {
LinkedList<Customer> customers = new LinkedList<>();
customers.add(new Customer(1001, "Customer 1"));
customers.add(new Customer(1002, "Customer 2"));
customers.add(new Customer(1003, "Customer 3"));
customers.add(new Customer(1004, "Customer 4"));
customers.add(new Customer(1005, "Customer 5"));

System.out.println(customers);
Customer topCustomer = customers.remove();
System.out.println(topCustomer);
System.out.println(customers);

topCustomer = customers.getFirst();
System.out.println(topCustomer);
System.out.println(customers);
}
}

Exception Handling
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q266 ArrayIndexOutOfBoundsException
================================

class Example {
public static void main(String[] args) {
int [] ar = new int[5];
ar[10] = 20;
System.out.println(ar.length);
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q267 NullPointerException
=====================

class A{
public void mA(){
System.out.println("mA of A");
}
}
class Example {
private A a;
public static void main(String[] args) {
new Example().callMethod();
}

public void callMethod(){


a.mA();
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q268 ClassNotFoundException
========================

class Example {
public static void main(String[] args) {
Class.forName("com.mysql.cj.jdbc.Driver");
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q269 OutOfMemoryError
=====================

class MyClass{
long[] arr= new long[1000000];
}
class Example {
public static void main(String[] args) {
MyClass [] myClassAr = new MyClass[1000000];
for(int i = 0; i < myClassAr.length; i++){
myClassAr[i] = new MyClass();
System.out.println(i);
}
}
}

try - catch Block


/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q270

class Example {
public static void main(String[] args) {
int [] ar = new int[5];
try{
ar[10] = 20;
} catch (ArrayIndexOutOfBoundsException e){
System.out.println("Array does not have index");
}

System.out.println(ar.length);
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q271

class A{
public void mA(){
System.out.println("mA of A");
}
}
class Example {
private A a;
public static void main(String[] args) {
new Example().callMethod();
}

public void callMethod(){


try {
a.mA();
} catch (NullPointerException e) {
System.out.println("a is not initialized");
}
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q272

class Example {
public static void main(String[] args) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("JDBC Driver not found");
}

}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q273

class A{
public void mA(){
System.out.println("mA of A");
}
}
class Example {
private A a;
public static void main(String[] args) {
new Example().callMethod();
System.out.println("Final Statement");
}

public void callMethod(){


try {
a.mA();
} catch (Exception e) {
System.out.println("A is not initialized");
}

}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q274 Case 1
==========

class Example {
public static void main(String[] args) {
try{
// Code
} // Illegal
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q275 Case 2
==========

class Example {
public static void main(String[] args) {
try{
// Code
} catch (Exception e){
// handling Exception
}
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q276 Case 3
==========

class Example {
public static void main(String[] args) {
try{
// Code
} catch (NullPointerException e){
// handling Exception
} catch (NumberFormatException e){
// handling Exception
}
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q277 from Q276
=============

class Example {
private String s1;
public static void main(String[] args) {
try{
Example e = new Example();
System.out.println(e.s1.length());
Integer num = Integer.parseInt(e.s1);
} catch (NullPointerException e){
System.out.println("S1 is Null");
} catch (NumberFormatException e){
System.out.println("S1 is not integer");
}
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q278 Case 5
==========

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

} catch (Exception e) {

}
} catch (Exception e){
try {

} catch (Exception ex) {

}
}
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q279

class Example {
private String s1 = "ABC";
public static void main(String[] args) {
try{
Example example = new Example();
System.out.println(example.s1.length());
try {
Integer num = Integer.parseInt(example.s1);
} catch (Exception e) {
System.out.println("S1 is not an Integer");
}
} catch (NullPointerException e){
System.out.println("S1 is null");
}
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q280 Exercise
============

class Example {
private String s1;
public static void main(String[] args) {
try{
Example e = new Example();
System.out.println(e.s1.length());
Integer num = Integer.parseInt(e.s1);
System.out.println(e.s1);
} catch (NullPointerException e){
System.out.println("S1 is Null");
} catch (NumberFormatException e){
System.out.println("S1 is not integer");
}
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q281 from Q380
=============

class Example {
private String s1 = "ABC";
public static void main(String[] args) {
try{
Example e = new Example();
System.out.println(e.s1.length());
try{
Integer num = Integer.parseInt(e.s1);
} catch (NumberFormatException ex){
System.out.println("S1 is not an integer");
}
System.out.println(e.s1);
} catch (NullPointerException e){
System.out.println("S1 is Null");
}
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q282

class A {
public void mA() {
System.out.println("mA of A");
}
}

class Example {
private A a;

public static void main(String[] args) {


try{
new Example().callMethod();
} catch (NullPointerException e) {
System.out.println("A is not initialized");
}

System.out.println("Final Statement");
}

public void callMethod() {


a.mA();
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q283 Case 6
===========

class A {
public void mA() {
System.out.println("mA of A");
}
}

class Example {
private A a;

public static void main(String[] args) {


try{
new Example().callMethod();
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("A is not initialized");
}

System.out.println("Final Statement");
}

public void callMethod() {


a.mA();
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q284 Case 7
==========

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

} finally{
System.out.println("Finally block");
}
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q285

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

} catch(Exception e){

} finally{
System.out.println("Finally block");
}
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q286 Case 8
===========

class Example {

public static Integer convert(String str) throws NumberFormatException{


try {
int num = Integer.parseInt(str);
return num;
} catch (Exception e) {
throw new NumberFormatException(str + " is not a number");
}
}

public static void main(String[] args) {


try {
convert("ABC");
} catch (NumberFormatException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}
Multi-Threading
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q287

class MyClass extends Thread{


public void run(){
for(int i = 0; i < 10; i++){
try{Thread.sleep(500);} catch (Exception e){}
System.out.println("i : " + i);
}
}
}
class Example {
public static void main(String[] args) {
System.out.println("start main");
Thread t1 = new Thread(new MyClass());
t1.start();
System.out.println("end main");
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q288

class MyClass implements Runnable{


public void run(){
for(int i = 0; i < 10; i++){
try{Thread.sleep(500);} catch (Exception e){}
System.out.println("i : " + i);
}
}
}
class Example {
public static void main(String[] args) {
System.out.println("start main");
Thread t1 = new Thread(new MyClass());
t1.start();
System.out.println("end main");
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q289 Thread class vs Runnable Interface
================================

class MyThread1 extends Thread{


public void run(){
System.out.println("Execute From Thread");
}
}

class Car {
public void park(){
System.out.println("Car Parking");
}
}

class MyThread2 extends Car implements Runnable{


public void run(){
System.out.println("Execute From Runnable");
super.park();
}
}

class Example {
public static void main(String[] args) {
Thread t1 = new Thread(new MyThread1());
t1.start();

Thread t2 = new Thread(new MyThread2());


t2.start();
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q290

class MyThread1 extends Thread{


public void run(){
System.out.println("Execute From Thread");
}
}

class Car {
public void park(){
System.out.println("Car Parking");
}
}

class MyThread2 extends Car implements Runnable{


public void run(){
System.out.println("Execute From Runnable");
super.park();
}
}

class Example {
public static void main(String[] args) {
Thread t1 = new Thread(new MyThread1());
t1.start();

MyThread1 myThread1 = new MyThread1();


myThread1.start();

Thread t2 = new Thread(new MyThread2());


t2.start();

MyThread2 myThread2 = new MyThread2();


//myThread2.start(); // Illegal
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q291 Thread Lifecycle
=================

class MyThread extends Thread{


public void run(){
try { Thread.sleep(1500); } catch (Exception e) {}
}
}

class Example {
public static void main(String[] args) {
MyThread myThread = new MyThread();
System.out.println(myThread.getState());
myThread.start();
System.out.println(myThread.getState());
try { Thread.sleep(500); } catch (Exception e) {}
System.out.println(myThread.getState());
try { Thread.sleep(2000); } catch (Exception e) {}
System.out.println(myThread.getState());
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q292 Thread Pool
==============

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

class MyThread extends Thread{


public void run(){
System.out.println("Start : " + Thread.currentThread().getName());
try { Thread.sleep(1500); } catch (Exception e) {}
System.out.println("End : " + Thread.currentThread().getName());
}
}

class Example {
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(5);

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


Thread t = new Thread(new MyThread());
executorService.execute(t);
}

}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q293 Thread Join
==============

class MyThread extends Thread{


public void run(){
System.out.println("Start : " + Thread.currentThread().getName());
try { Thread.sleep(1500); } catch (Exception e) {}
System.out.println("End : " + Thread.currentThread().getName());
}
}

class Example {
public static void main(String[] args) {
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
MyThread t3 = new MyThread();

t1.start();
try {
t1.join();
} catch (Exception e) {}
t2.start();
try {
t2.join();
} catch (Exception e) {}
t3.start();

}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q294 Thread Priority
================

class MyThread1 extends Thread{


public void run(){
for(int i = 0; i < 10; i++){
System.out.println("i : " + i + "from Mythread 1");
}
}
}

class MyThread2 extends Thread{


public void run(){
for(int i = 0; i < 10; i++){
System.out.println("i : " + i + "from Mythread 2");
}
}
}

class MyThread3 extends Thread{


public void run(){
for(int i = 0; i < 10; i++){
System.out.println("i : " + i + "from Mythread 3");
}
}
}

class MyThread4 extends Thread{


public void run(){
for(int i = 0; i < 10; i++){
System.out.println("i : " + i + "from Mythread 4");
}
}
}

class Example {
public static void main(String[] args) {
MyThread1 myThread1 = new MyThread1();
MyThread2 myThread2 = new MyThread2();
MyThread3 myThread3 = new MyThread3();
MyThread4 myThread4 = new MyThread4();

myThread1.setPriority(Thread.MAX_PRIORITY);
myThread2.setPriority(Thread.MIN_PRIORITY);
myThread3.setPriority(Thread.NORM_PRIORITY);
myThread4.setPriority(6);

myThread1.start();
myThread2.start();
myThread3.start();
myThread4.start();
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q295 Daemon Thread
==================

class MyThread extends Thread{


public void run(){
if(Thread.currentThread().isDaemon()){
System.out.println("Daemon Thread");
}else {
System.out.println("User Thread");
}
}
}

class Example {
public static void main(String[] args) {
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();

t1.setDaemon(true);

t1.start();
t2.start();
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q296 Using Lambda Expression
=========================

class Example {
public static void main(String[] args) {
new Thread(() -> {
for(int i = 0; i < 10; i++){
System.out.println("Thread : " + i);
};
}).start();
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q297 Synchronization
==================

class MyClass{
public void printData(String threadName){
for(int i = 0; i < 10; i++){
try {
Thread.sleep(500);
} catch (Exception e) {}
System.out.println(threadName + " + " + i );
}
}
}

class MyThread1 extends Thread{


private MyClass myClass;

MyThread1(MyClass myClass){
this.myClass = myClass;
}

public void run(){


this.myClass.printData(Thread.currentThread().getName());
}
}

class MyThread2 extends Thread{


private MyClass myClass;

MyThread2(MyClass myClass){
this.myClass = myClass;
}

public void run(){


this.myClass.printData(Thread.currentThread().getName());
}
}
class Example {
public static void main(String[] args) {
MyClass myClass = new MyClass();

MyThread1 thread1 = new MyThread1(myClass);


thread1.start();

MyThread2 thread2 = new MyThread2(myClass);


thread2.start();
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q298 from Q297
=============

class MyClass{
synchronized public void printData(String threadName){
for(int i = 0; i < 10; i++){
try {
Thread.sleep(500);
} catch (Exception e) {}
System.out.println(threadName + " + " + i );
}
}
}

class MyThread1 extends Thread{


private MyClass myClass;

MyThread1(MyClass myClass){
this.myClass = myClass;
}

public void run(){


this.myClass.printData(Thread.currentThread().getName());
}
}

class MyThread2 extends Thread{


private MyClass myClass;

MyThread2(MyClass myClass){
this.myClass = myClass;
}

public void run(){


this.myClass.printData(Thread.currentThread().getName());
}
}
class Example {
public static void main(String[] args) {
MyClass myClass = new MyClass();

MyThread1 thread1 = new MyThread1(myClass);


thread1.start();

MyThread2 thread2 = new MyThread2(myClass);


thread2.start();
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q299 Deadlock
============

class MyClass{
synchronized public void myMethod1(MyClass myClass){
System.out.println("myMethod 1 - start");
try {
Thread.sleep(1000);
} catch (Exception e) {}

myClass.myMethod2();

System.out.println("myMethod 1 - end");
}

synchronized public void myMethod2(){


System.out.println("myMethod 2 - start");
System.out.println("myMethod 2 - end");
}
}

class Example {
public static void main(String[] args) {
MyClass myClass1 = new MyClass();
MyClass myClass2 = new MyClass();

Thread t1 = new Thread(){


public void run(){
myClass1.myMethod1(myClass2);
}
};

Thread t2 = new Thread(){


public void run(){
myClass2.myMethod1(myClass1);
}
};

t1.start();
t2.start();
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Q300

class MyClass{
synchronized public void myMethod1(MyClass myClass){
System.out.println("myMethod 1 - start");
try {
Thread.sleep(1000);
} catch (Exception e) {}

myClass.myMethod2();

System.out.println("myMethod 1 - end");
}

synchronized public void myMethod2(){


System.out.println("myMethod 2 - start");
System.out.println("myMethod 2 - end");
}
}

class Example {
public static void main(String[] args) {
MyClass myClass1 = new MyClass();
MyClass myClass2 = new MyClass();

Thread t1 = new Thread(){


public void run(){
myClass1.myMethod1(myClass2);
}
};

Thread t2 = new Thread(){


public void run(){
myClass2.myMethod1(myClass1);
}
};

t1.start();
try {
t1.join();
} catch (Exception e) {}
t2.start();
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
END
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

You might also like