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

28 April 2023 07:31: CS2 Page 3

Uploaded by

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

28 April 2023 07:31: CS2 Page 3

Uploaded by

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

OOPs

28 April 2023 07:31

The basic concepts of OOPs (Object-Oriented Programming) are:


1. Objects: Objects are instances of classes that encapsulate data and behavior.
2. Classes: Classes are the blueprints or templates used to create objects.
3. Abstraction: Abstraction refers to the process of simplifying complex systems by breaking them down
into smaller, more manageable components.
4. Encapsulation: Encapsulation refers to the process of hiding the internal details of an object from the
outside world.
5. Inheritance: Inheritance allows one class to inherit the properties and methods of another class.
6. Polymorphism: Polymorphism allows objects of different types to be treated as if they are of the same
type.
7. Message passing: Objects communicate with each other by sending and receiving messages.
8. Methods: Methods are functions that are associated with an object and define the behavior of that
object.
9. Properties: Properties are the characteristics of an object that describe its state.
10. Overloading: Overloading allows multiple methods with the same name to be defined in a class, but with
different parameters.

CS2 Page 3
CS2 Page 4
CS2 Page 5
CS2 Page 6
CS2 Page 7
Java
28 April 2023 07:33

CS2 Page 8
CS2 Page 9
CS2 Page 10
CS2 Page 11
CS2 Page 12
CS2 Page 13
CS2 Page 14
CS2 Page 15
CS2 Page 16
CS2 Page 17
CS2 Page 18
CS2 Page 19
Java Program Structure
28 April 2023 07:34

CS2 Page 20
CS2 Page 21
CS2 Page 22
CS2 Page 23
CS2 Page 24
CS2 Page 25
CS2 Page 26
CS2 Page 27
CS2 Page 28
CS2 Page 29
CS2 Page 30
CS2 Page 31
CS2 Page 32
CS2 Page 33
CS2 Page 34
CS2 Page 35
Java Basics
28 April 2023 07:34

CS2 Page 36
CS2 Page 37
CS2 Page 38
CS2 Page 39
CS2 Page 40
CS2 Page 41
CS2 Page 42
CS2 Page 43
CS2 Page 44
CS2 Page 45
CS2 Page 46
CS2 Page 47
CS2 Page 48
CS2 Page 49
CS2 Page 50
Operators and Arithmetic Expressions
28 April 2023 07:34

CS2 Page 51
CS2 Page 52
CS2 Page 53
CS2 Page 54
CS2 Page 55
CS2 Page 56
CS2 Page 57
CS2 Page 58
CS2 Page 59
CS2 Page 60
CS2 Page 61
CS2 Page 62
CS2 Page 63
CS2 Page 64
CS2 Page 65
CS2 Page 66
CS2 Page 67
Decision Making
28 April 2023 07:35

CS2 Page 68
CS2 Page 69
CS2 Page 70
CS2 Page 71
CS2 Page 72
CS2 Page 73
CS2 Page 74
CS2 Page 75
CS2 Page 76
CS2 Page 77
CS2 Page 78
CS2 Page 79
CS2 Page 80
CS2 Page 81
CS2 Page 82
CS2 Page 83
CS2 Page 84
CS2 Page 85
Loops
28 April 2023 07:35

CS2 Page 86
CS2 Page 87
CS2 Page 88
CS2 Page 89
CS2 Page 90
CS2 Page 91
CS2 Page 92
CS2 Page 93
CS2 Page 94
CS2 Page 95
CS2 Page 96
CS2 Page 97
CS2 Page 98
CS2 Page 99
CS2 Page 100
CS2 Page 101
CS2 Page 102
Class
28 April 2023 07:35

CS2 Page 103


CS2 Page 104
CS2 Page 105
CS2 Page 106
CS2 Page 107
CS2 Page 108
CS2 Page 109
CS2 Page 110
CS2 Page 111
Constructors
28 April 2023 07:35

Types of Constructors in Java Constructors are a crucial part of the Java programming language, and they are used
Now is the correct time to discuss the types of the constructor, so primarily there are three types of to initialize objects of a class. Here is a brief note on constructors in Java, with
constructors in Java are mentioned below: subheadings:
1. Definition: A constructor in Java is a special type of method that is used to initialize
• No-Argument Constructor
the object's state. It is called when an object of a class is created.
• Parameterized Constructor
2. Naming Convention: The constructor method should have the same name as the
• Default Constructor
class, and it must not have any return type. Java supports overloading of constructors
with different arguments lists.
1. No-Argument Constructor in Java 3. Role in Initialization: The primary role of a constructor is to initialize the instance
variables of an object. The constructor is executed only once when the object is
A constructor that has no parameter is known as the No-argument or Zero argument constructor. If we created, and it is automatically called by the JVM.
don’t define a constructor in a class, then the compiler creates aconstructor(with no arguments) for
the class. And if we write a constructor with no arguments, the compiler does not create a default
constructor.
Example:
• Java

// Java Program to illustrate calling a


// no-argument constructor

import java.io.*;

class Geek {
int num;
String name;

// this would be invoked while an object


// of that class is created.
Geek() { System.out.println("Constructor called"); }
}

class GFG {
public static void main(String[] args)
{
// this would invoke default constructor.
Geek geek1 = new Geek();

// Default constructor provides the default


// values to the object like 0, null
System.out.println(geek1.name);
System.out.println(geek1.num);
}
}
Output
Constructor called
null
0
Note: Default constructor provides the default values to the object like 0, null, etc. depending on the
type.

2. Parameterized Constructor in Java

A constructor that has parameters is known as parameterized constructor. If we want to initialize fields
of the class with our own values, then use a parameterized constructor.
Example:
• Java

// Java Program for Parameterized Constructor


import java.io.*;
class Geek {
// data members of the class.
String name;
int id;
Geek(String name, int id)
{
this.name = name;
this.id = id;
}
}
class GFG {
public static void main(String[] args)
{
// This would invoke the parameterized constructor.
Geek geek1 = new Geek("avinash", 68);
System.out.println("GeekName :" + geek1.name + " and GeekId :" + geek1.id);
}
}
Output
GeekName :avinash and GeekId :68
Remember: Does constructor return any value?
There are no “return value” statements in the constructor, but the constructor returns the current class
instance. We can write ‘return’ inside a constructor.
Now the most important topic that comes into play is the strong incorporation of OOPS with
constructors known as constructor overloading. Just like methods, we can overload constructors for
creating objects in different ways. The compiler differentiates constructors on the basis of the number
of parameters, types of parameters, and order of the parameters.
Example:
• Java

// Java Program to illustrate constructor overloading


// using same task (addition operation ) for different
// types of arguments.

import java.io.*;

class Geek {
// constructor with one argument
Geek(String name)
{
System.out.println("Constructor with one "
+ "argument - String : " + name);
}

// constructor with two arguments


Geek(String name, int age)
{

System.out.println(
"Constructor with two arguments : "
+ " String and Integer : " + name + " " + age);
}

// Constructor with one argument but with different


// type than previous..
Geek(long id)
{
System.out.println(
"Constructor with one argument : "
+ "Long : " + id);
}
}

class GFG {
public static void main(String[] args)
{
// Creating the objects of the class named 'Geek'
// by passing different arguments

// Invoke the constructor with one argument of


// type 'String'.
Geek geek2 = new Geek("Shikhar");

// Invoke the constructor with two arguments


Geek geek3 = new Geek("Dharmesh", 26);

// Invoke the constructor with one argument of


// type 'Long'.
Geek geek4 = new Geek(325614567);
}
}
Output
Constructor with one argument - String : Shikhar
Constructor with two arguments : String and Integer : Dharmesh 26
Constructor with one argument : Long : 325614567

3. Default Constructor in Java

A constructor that has no parameters is known as default the constructor. A default constructor is
invisible. And if we write a constructor with no arguments, the compiler does not create a default
constructor. It is taken out. It is being overloaded and called a parameterized constructor. The default
constructor changed into the parameterized constructor. But Parameterized constructor can’t change
the default constructor.
Example:
• Java

// Java Program to demonstrate


// Default Constructor
import java.io.*;

// Driver class
class GFG {

// Default Constructor
GFG() { System.out.println("Default constructor"); }

// Driver function
public static void main(String[] args)
{
GFG hello = new GFG();
}
}
Output
Default constructor

From <https://www.geeksforgeeks.org/constructors-in-java/>

CS2 Page 112


Default constructor

From <https://www.geeksforgeeks.org/constructors-in-java/>

CS2 Page 113


Inheritance
28 April 2023 07:35

CS2 Page 114


CS2 Page 115
CS2 Page 116
CS2 Page 117
CS2 Page 118
CS2 Page 119
CS2 Page 120
CS2 Page 121
CS2 Page 122
CS2 Page 123
CS2 Page 124
CS2 Page 125
Array,String,Vector
28 April 2023 08:03

CS2 Page 126


CS2 Page 127
CS2 Page 128
CS2 Page 129
CS2 Page 130
CS2 Page 131
CS2 Page 132
CS2 Page 133
CS2 Page 134
CS2 Page 135
CS2 Page 136
CS2 Page 137
CS2 Page 138
CS2 Page 139
CS2 Page 140
CS2 Page 141
CS2 Page 142
CS2 Page 143
CS2 Page 144
CS2 Page 145
CS2 Page 146
CS2 Page 147
CS2 Page 148
Interface
28 April 2023 08:03

CS2 Page 149


CS2 Page 150
CS2 Page 151
CS2 Page 152
CS2 Page 153
CS2 Page 154
CS2 Page 155
CS2 Page 156
Java API Packages
28 April 2023 07:35

CS2 Page 157


CS2 Page 158
CS2 Page 159
CS2 Page 160
CS2 Page 161
CS2 Page 162
CS2 Page 163
CS2 Page 164
CS2 Page 165
CS2 Page 166
CS2 Page 167
CS2 Page 168
CS2 Page 169
Threads
28 April 2023 07:36

CS2 Page 170


CS2 Page 171
CS2 Page 172
CS2 Page 173
CS2 Page 174
CS2 Page 175
CS2 Page 176
CS2 Page 177
CS2 Page 178
CS2 Page 179
CS2 Page 180
CS2 Page 181
CS2 Page 182
CS2 Page 183
CS2 Page 184
CS2 Page 185
CS2 Page 186
CS2 Page 187
CS2 Page 188
CS2 Page 189
Types of errors
28 April 2023 07:41

CS2 Page 190


CS2 Page 191
CS2 Page 192
CS2 Page 193
Here are some guidelines for handling code while applying try -catch, as presented in the book:

Only wrap the code that may throw an exception inside the try block. Wrapping too much code can
make it difficult to locate the source of the exception.

Catch only the exceptions that you can handle. Catching all exceptions using the Exception class is not a
good practice as it can mask other issues in the code.

Handle the exception appropriately. This may include logging the exception, providing a meaningful
error message to the user, or retrying the operation.

Use finally block if you want to execute some code regardless of whether an exception was thrown or
not. This block executes even if an exception is thrown, and it is used to release resources that were
acquired in the try block.

Here's an example of how to use a try-catch block in Java, as presented in the book:

try {
// code that may throw an exception
}
catch(Exception e) {
// code to handle the exception
}
finally {
// code to release resources
}
In this example, the code inside the try block is the code that may throw an exception. The catch block is
executed if an exception occurs, and the type of the exception is specified in the parentheses after the
catch keyword. The code inside the finally block is executed regardless of whether an exception was
thrown or not, and it is used to release resources that were acquired in the try block.

CS2 Page 194


In Java, multiple catch statements are used to handle different types of exceptions that may occur in a
program. This allows the program to gracefully handle errors and continue execution instead of
crashing.

Syntax:

try {
// code that may throw an exception
}
catch(ExceptionType1 e1) {
// code to handle ExceptionType1
}
catch(ExceptionType2 e2) {
// code to handle ExceptionType2
}
...
catch(ExceptionTypeN eN) {
// code to handle ExceptionTypeN
}
finally {
// optional code to be executed regardless of whether an exception is thrown or not
}

The code within the try block is executed, and if any exception is thrown, it is caught by the
corresponding catch block that matches the type of the exception. Each catch block can handle a specific
type of exception. The finally block is optional and is executed regardless of whether an exception is
thrown or not.

Example:

public class MultipleCatchExample {


public static void main(String[] args) {
int[] arr = {1, 2, 3};
try {
System.out.println(arr[3]); // Accessing 4th element which doesn't exist
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out of bounds exception occurred!");
}
catch(Exception e) {
System.out.println("Exception occurred: " + e);
}
finally {
System.out.println("Finally block executed!");
}
System.out.println("Program continues...");
}
}
In the above example, the try block attempts to access the 4th element of an array, which doesn't exist
and throws an ArrayIndexOutOfBoundsException. This exception is caught by the first catch block that
matches the type of the exception. The finally block is executed regardless of whether an exception is
thrown or not. Finally, the program continues executing after the try -catch block.

CS2 Page 195


CS2 Page 196
CS2 Page 197
CS2 Page 198
Writing Applets
28 April 2023 07:41

CS2 Page 199


Feature Applet Standalone Application
Definition A program designed to run inside A program designed to run
a web browser. independently on a computer.
Execution It runs on the web browser using It runs on the computer's
the Java plugin. operating system without any
browser support.
GUI Limited GUI components are Full GUI components are
Components available. available.
User Applet user interface is designed Standalone application user
Interface using AWT or Swing. interface is designed using AWT
or Swing.
Access to Applet has restricted access to Standalone application has full
Resources resources. access to resources.
Deployment Applet needs to be deployed on a Standalone application needs to
web server. be installed on a computer.
Security Applet runs in a sandboxed Standalone application is less
environment to prevent secure compared to applets.
unauthorized access.
Network Applets can access remote Standalone applications can
Access servers using the internet. access remote servers using the
internet.
Developmen Applets are developed using Java Standalone applications are
t Applet API. developed using Java Application
API.
Examples Online games, calculators, etc. Media players, text editors, etc.
Note: AWT and Swing are two popular GUI libraries in Java.

CS2 Page 200


Applet Life Cycle in Java
In Java, an applet is a special type of program embedded in the web page to generate
dynamic content. Applet is a class in Java.
The applet life cycle can be defined as the process of how the object is created, started,
stopped, and destroyed during the entire execution of its application. It basically has five core
methods namely init(), start(), stop(), paint() and destroy().These methods are invoked by the
browser to execute.
Along with the browser, the applet also works on the client side, thus having less processing
time.
Methods of Applet Life Cycle

There are five methods of an applet life cycle, and they are:

• init(): The init() method is the first method to run that initializes the applet. It can be
invoked only once at the time of initialization. The web browser creates the initialized
objects, i.e., the web browser (after checking the security settings) runs the init() method
within the applet.
• start(): The start() method contains the actual code of the applet and starts the applet. It
is invoked immediately after the init() method is invoked. Every time the browser is
loaded or refreshed, the start() method is invoked. It is also invoked whenever the applet
is maximized, restored, or moving from one tab to another in the browser. It is in an
inactive state until the init() method is invoked.

CS2 Page 201


inactive state until the init() method is invoked.
• stop(): The stop() method stops the execution of the applet. The stop () method is
invoked whenever the applet is stopped, minimized, or moving from one tab to another in
the browser, the stop() method is invoked. When we go back to that page, the start()
method is invoked again.
• destroy(): The destroy() method destroys the applet after its work is done. It is invoked
when the applet window is closed or when the tab containing the webpage is closed. It
removes the applet object from memory and is executed only once. We cannot start the
applet once it is destroyed.
• paint(): The paint() method belongs to the Graphics class in Java. It is used to draw
shapes like circle, square, trapezium, etc., in the applet. It is executed after the start()
method and when the browser or applet windows are resized.
Sequence of method execution when an applet is executed:
1. init()
2. start()
3. paint()
Sequence of method execution when an applet is executed:
1. stop()
2. destroy()
Applet Life Cycle Working
• The Java plug-in software is responsible for managing the life cycle of an applet.
• An applet is a Java application executed in any web browser and works on the client-
side. It doesn't have the main() method because it runs in the browser. It is thus created
to be placed on an HTML page.
• The init(), start(), stop() and destroy() methods belongs to the applet.Applet class.
• The paint() method belongs to the awt.Component class.
• In Java, if we want to make a class an Applet class, we need to extend the Applet
• Whenever we create an applet, we are creating the instance of the existing Applet class.
And thus, we can use all the methods of that class.
Flow of Applet Life Cycle:
These methods are invoked by the browser automatically. There is no need to call them
explicitly.

Syntax of entire Applet Life Cycle in Java


1. class TestAppletLifeCycle extends Applet {
2. public void init() {
3. // initialized objects
4. }
5. public void start() {
6. // code to start the applet
7. }
8. public void paint(Graphics graphics) {
9. // draw the shapes
10. }
11. public void stop() {
12. // code to stop the applet
13. }
14. public void destroy() {
15. // code to destroy the applet
16. }
17. }

From <https://www.javatpoint.com/applet-life-cycle-in-java>

CS2 Page 202


CS2 Page 203
Designing a web page in Java using applet involves the following points:
1. Applet tag: The first step is to create an HTML file and add an applet tag to it. The applet tag is used to
embed the applet in the web page.
2. Importing packages: To design the applet, we need to import the required packages in our Java code.
These packages include java.applet, java.awt, and java.net.
3. Creating the applet class: We need to create a class that extends the Applet class. This class will contain
the code for designing the applet.
4. Overriding the init() method: The init() method is called when the applet is first loaded. We need to
override this method and write the code for initializing the applet.
5. Overriding the paint() method: The paint() method is called whenever the applet needs to be redrawn.
We need to override this method and write the code for drawing the applet.
6. Setting applet parameters: We can set various parameters for the applet using the <param> tag in the
HTML file.
7. Compiling and running the applet: Once the applet code is written, we need to compile it using a Java
compiler. After compiling, we can run the applet in a web browser by opening the HTML file.
By following these steps, we can design a web page in Java using applet. Applets are a powerful way to
add interactivity to web pages and can be used to create animations, games, and other dynamic
content.

From <https://chat.openai.com/c/4153b405-765c-4cd3-8abb-67341d5c77cf>
import java.applet.Applet;
import java.awt.*;

public class MyWebPage extends Applet {


public void paint(Graphics g) {
// Set the background color of the web page
setBackground(Color.WHITE);

// Add a heading to the web page


g.drawString("Welcome to my web page!", 50, 50);

// Add an image to the web page


Image img = getImage(getDocumentBase(), "myImage.jpg");
g.drawImage(img, 50, 80, this);

// Add a paragraph to the web page


String paragraph = "This is a sample paragraph. " +
"It can contain multiple lines and " +
"can be formatted as per the user's " +
"requirement.";
g.drawString(paragraph, 50, 200);

// Add a hyperlink to the web page


g.setColor(Color.BLUE);
Font font = new Font("Arial", Font.BOLD, 12);
g.setFont(font);
g.drawString("Click here to learn more!", 50, 300);
g.drawRect(50, 290, 140, 15);
g.setColor(Color.WHITE);
g.fillRect(51, 291, 139, 14);
}
}

Designing a web page with applet and HTML involves creating an HTML page that embeds the Java
applet. Here is a brief guide on how to design a web page with applet and HTML:
1. Create a Java applet that you want to embed in the HTML page.
2. Compile the Java applet code and generate the applet class file.
3. Write the HTML code that embeds the applet using the <applet> tag.
4. Specify the applet class file name and any required parameters within the <applet> tag.
5. Save the HTML file with the desired file name and extension (.html).
6. Run the HTML file in a web browser to view the applet in action.
Here is an example HTML code to embed a Java applet:

<html>
<head>
<title>My Java Applet Example</title>
</head>
<body>
<h1>My Java Applet Example</h1>
<applet code="MyApplet.class" width="300" height="300">
<param name="message" value="Hello World!">
</applet>
</body>
</html>

In the above code, the <applet> tag specifies the applet class file name (MyApplet.class) and the applet's
width and height. The <param> tag within the <applet> tag is used to pass parameters to the applet. In
this example, the message "Hello World!" is passed as a parameter to the applet.

From <https://chat.openai.com/c/4153b405-765c-4cd3-8abb-67341d5c77cf>

CS2 Page 204


The applet tag in Java is used to embed applets into an HTML document. Some of the key points related
to the applet tag in Java are:
• The applet tag is an HTML tag used to embed Java applets in a web page.
• It has several attributes such as code, width, height, archive, etc. which are used to define the properties
of the applet.
• The code attribute specifies the name of the applet's class file, which contains the applet's code.
• The width and height attributes are used to set the dimensions of the applet display area.
• The archive attribute specifies the name of the archive file (.jar) that contains all the applet's dependent
classes and resources.
• The applet tag is enclosed within the <applet> and </applet> tags.
• The applet tag is now deprecated in HTML5, and the recommended approach is to use the <object> tag
instead.
• Applets are executed inside a web browser using the Java Virtual Machine (JVM), which provides a
secure environment for the applet to run in.
• Applets can be used to create interactive animations, games, multimedia, and other types of dynamic
content on a web page.
• Applets have access to some of the resources of the user's computer, such as local files and network
connections, but their access is restricted for security reasons.
• Applets have been largely replaced by other technologies such as HTML5, JavaScript, and CSS3, which
provide similar features with better performance and security.

From <https://chat.openai.com/c/4153b405-765c-4cd3-8abb-67341d5c77cf>

CS2 Page 205


CS2 Page 206
In Java, you can pass parameters to an applet program using the HTML <applet> tag. Here are the steps
to do this:
1. Define parameters in the HTML code using the <param> tag, for example:

<applet code="MyApplet.class" width="300" height="200">


<param name="username" value="John">
<param name="age" value="30">
</applet>

Retrieve the parameter values in your applet code using the getParameter() method of the Applet
class, for example:

public class MyApplet extends Applet {


private String username;
private int age;

public void init() {


username = getParameter("username");
age = Integer.parseInt(getParameter("age"));
}

// rest of the applet code


}

2. Note that the getParameter() method returns a string, so you may need to convert the parameter value
to the desired data type using methods like Integer.parseInt().
By passing parameters to your applet program, you can make it more dynamic and customizable based
on user inputs.

CS2 Page 207


CS2 Page 208
CS2 Page 209
CS2 Page 210
CS2 Page 211
CS2 Page 212
CS2 Page 213
CS2 Page 214
Graphics Class
28 April 2023 07:41

CS2 Page 215


CS2 Page 216
CS2 Page 217
CS2 Page 218
CS2 Page 219
CS2 Page 220
CS2 Page 221
CS2 Page 222
CS2 Page 223
CS2 Page 224
CS2 Page 225
CS2 Page 226
CS2 Page 227
CS2 Page 228
CS2 Page 229
CS2 Page 230
Concept of Stream
28 April 2023 07:42

CS2 Page 231


CS2 Page 232
CS2 Page 233
CS2 Page 234
CS2 Page 235
CS2 Page 236
CS2 Page 237
CS2 Page 238
CS2 Page 239
CS2 Page 240
CS2 Page 241
Concept of stream and other useful i/o classes
01 May 2023 06:00

CS2 Page 242


CS2 Page 243
CS2 Page 244
CS2 Page 245
CS2 Page 246
CS2 Page 247
CS2 Page 248
CS2 Page 249
CS2 Page 250
CS2 Page 251
CS2 Page 252
CS2 Page 253
CS2 Page 254
CS2 Page 255
CS2 Page 256
CS2 Page 257
CS2 Page 258
CS2 Page 259
CS2 Page 260
CS2 Page 261
CS2 Page 262
CS2 Page 263
CS2 Page 264
CS2 Page 265
CS2 Page 266
CS2 Page 267
CS2 Page 268
CS2 Page 269
CS2 Page 270
CS2 Page 271
CS2 Page 272
CS2 Page 273
CS2 Page 274
CS2 Page 275
CS2 Page 276
CS2 Page 277
CS2 Page 278

You might also like