0% found this document useful (0 votes)
14 views8 pages

Bhagavane Eeshwara Java (2 Files Merged)

Uploaded by

vedicsb89
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)
14 views8 pages

Bhagavane Eeshwara Java (2 Files Merged)

Uploaded by

vedicsb89
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/ 8

<1> MOD 1.1 <2>MOD 2.1 <3>MOD 3.1 <4>MOD 4.1 <5>MOD 5.

1
JAVA BUZZWORDS CONSTRUCTORS WORKING WITH FILES: STRING CONSTRUCTORS • SWING FUNDAMENTAL1) Java Swing is a GUI
Simple• It’s simple and easy to learn if you already A constructor in Java is a special method that is File handling is an important part of any application. • The string class supports several types of Framework that contains a set of classes to provide
know the basic concepts of Object Oriented used to initialize objects. The constructor is called Java has several methods for creating, reading, constructors in Java APIs. more powerful and flexible GUI components than
Programming. when an object of a class is created.It can be used updating, and deleting files. The File class from the The most commonly used constructors of String AWT./ Swing provides the look and feel of modern
Object oriented• Java is true object oriented to set initial values for object attributesTypes of java.io package, allows us to work with files.To use class are as Java GUI./ Swing library is an official Java GUI tool
language. Everything in Java is an object. • All Java constructors the File class, create an object of the class, and follows: kit released by SuN Microsys/It is used to create
program code and data reside within objects and Default constructor (no-argument constructor) specify the filename or directory name 1. String() : To create an empty String, we will call a graphical user interface with Java/. Swing classes
classes. • Java comes with an extensive set of Parameterized constructor default constructor. For example: are defined in javax.swing package and its sub
classes, arranged in packages If there is no constructor in a class, compiler Create a File: String s = new String(); • It will create a string object packages/. Java Swing provides
that can be used in our programs through automatically creates a default constructor. To create a file in Java, you can use the in the heap area with no value platform-independent and Light weight components.
inheritance The purpose of a default constructor • The default createNewFile() method. 2. String(String str) : It will create a string object in SWING FEATURE
Distributed• Java is designed for distributed constructor is used to provide the default values to This method returns a boolean value: true if the file the heap area and stores the given value in it. For Platform Independent:
environment of the Internet. It's Used for creating theobject like 0, null, etc., depending on the type. was example: • It is platform independent, the swing components
applications on networks The constructor name must match the class name, successfully created, and false if the file already String s2 = new String(“Hello Java“); that are used to build the program are not platform
• Java enables multiple programmers at multiple and it cannot have a return type (like void). The exists. Note that the method is enclosed in a Now, the object contains Hello Java. specific.
remote locations to collaborate and work together on constructor is called when the object is created. try...catch block.This is necessary because it throws 3. String(char chars[ ]) : It will create a string object • It can be used at any platform and anywhere.
a single project. All classes have constructors by default an IOException if an error and stores the array of characters in it. For example: Lightweight:
Compiled and Interpreted If you do not create a class constructor occurs char chars[ ] = { ‘a’, ‘b’, ‘c’, ‘d’ }; Swing components are lightweight which helps in
• Usually a computer language is either compiled or yourself,Java creates one for you. However, then String s3 = new String(chars); creating the UI lighter.
Interpreted. Java combines both this approach and you are not able to set initial values for import java.io.File; 4. String(char chars[ ], int startIndex, int count) • It • Swings component allows it to plug into the
makes it a two-stage system. • Compiled : Java object attributes. import java.io.IOException; will create and initializes a string object with a operating system user interface framework that
enables creation of a cross platform programs by Default constructor: public class CreateFileExample1 subrange of a character array. • The argument includes the mappings for screens or device and
compiling into an intermediate representation called class Bike1{ { startIndex specifies the index at which the subrange other user interactions like key press and mouse
Java Byte code. • Interpreted : Byte code is then Bike1(){System.out.println("Bike is created");} public static void main(String[] args) begins and count specifies the number of characters movements.
interpreted, which generates machine code that can public static void main(String args[]){ { to be copied. Plugging:It has a powerful component that can be
be directly executed by the machine that provides a Bike1 b=new Bike1(); File file = new File("C:\\demo\\music.txt"); argument For example: extended to provide the support for the user
Java Virtual machine. } boolean result; char chars[ ] = { ‘w’, ‘i’, ‘n’, ‘d’, ‘o’, ‘w’, ‘s’ }; interface that helps in good look and feel to the
Robust • It provides many features that make the try String str = new String(chars, 2, 3); • application.It refers to the highly modular-based
}
program execute reliably { 5. String(byte byteArr[ ]) : It constructs a new string architecture that allows it to plug into other
in variety of environments. • Java is a strictly typed Parameterized constructor: result = file.createNewFile(); //creates a new file object by decoding the given array of bytes (i.e, by
class Student4{ customized implementations and framework for user
language. It checks code both at compile if(result) decoding ASCII values into the characters) interfaces.
time and runtime. • Java takes care of all memory int id; { according to the system’s default character set. Manageable: It is easy to manage and configure. Its
management problems with String name; System.out.println("file created 6. String(byte byteArr[ ], int startIndex, int count) mechanism and composition pattern allows changing
garbage-collection. • Java, with the help of exception Student4(int i,String n){ "+file.getCanonicalPath()); This constructor also creates a new string object by the settings at run time as well. The uniform changes
handling captures all types of id = i; } decoding the ASCII values using the system’s can be provided to the user interface without doing
serious errors and eliminates any risk of crashing name = n; else default character set. any changes to application code.
the system. } { Java AWT
Secure• Java provides a “firewall” between a void display(){System.out.println(id+" "+name);} System.out.println("File already exist at location: CHARACTER EXTRACTION AWT components are platform-dependent.//
networked application and public static void main(String args[]){ "+file.getCanonicalPath()); String charAt() • The java string charAt() method AWT components are heavyweight.//Java swing
your computer. • When a Java Compatible Web Student4 s1 = new Student4(111,"Karan"); } returns a char value at the given index number. • components are platform independent.//
browser is used, downloading can Student4 s2 = new Student4(222,"Aryan"); } The index number starts from 0 and goes to n-1, AWT provides less components than Swing.//AWT
be done safely without fear of viral infection or s1.display(); catch (IOException e) where n is length of the string. • It returns doesn't follows MVC(Model View Controller) where
malicious intent. • Java achieves this protection by s2.display(); { StringIndexOutOfBoundsException if given index model represents data, view represents presentation
confining a Java program to the } e.printStackTrace(); number is greater than or equal to this string length and controller acts as an interface between model
java execution environment and not allowing it to } } or a negative number. • Signature - The signature of and view.
access other Method overloading: } string charAt() method is given below: JAVA SWING
parts of the computer. With method overloading, multiple methods can } public char charAt(int index)
Java swing components are platform
Architecture Neutral • Java language and Java have the same name with different parameters EG;public class CharAtExample {
independent./Swing components are
Virtual Machine helped in achieving the public static void main(String args[]) {
Method overloading is one of the ways that Java lightweight.//Swing supports pluggable look and
goal of “write once; run anywhere, any time, SERIALIZATION String name="javatpoint";
supports polymorphism.There are two ways to feel.//Swing provides more powerful components
forever.” • Serialization in Java is the process of converting char ch=name.charAt(4);//returns the char value at
overload the method in javaBy changing number of such as tables, lists, scroll panes, colorchooser,
• Changes and upgrades in operating systems, the Java code Object into a Byte Stream, to transfer the 4th index
argumentsBy changing the data typeAdvantage of tabbedpane etc.//Swing follows MVC
processors and system resources will not force any the Object Code from one Java Virtual machine to System.out.println(ch);}}
changes in Java Programs. method overloading:The main advantage of this is another and recreate it using the process of
The Model-View-Controller Architecture
cleanliness of code. • Method overloading • Swing uses the model-view-controller architecture
Portable• Java is portable because it facilitates you Deserialization. •// Most impressive is that the entire
increases the readability of the program. • Flexibility (MVC) as the fundamental design behind each of its
to carry the Java byte code to any platform. It process is JVM independent, meaning an object can
class Adder{ components//• Essentially, MVC breaks GUI
doesn't require any implementation. • Java Provides be serialized on one platform and deserialized on an
static int add(int a, int b){return a+b;} components into three elements. Each of these
a way to download programs dynamically to all the entirely different platform. • For serializing the object,
static double add(double a, double b){return a+b;} elements plays a crucial role in how the
various types of platforms connected to the Internet we call the writeObject() method of
} component//behaves. • The Model-View-Controller is
High Performance Java performance is high ObjectOutputStream, and for deserialization we call
class TestOverloading2{ a well known software architectural//pattern ideal to
because of the use of byte code. • The byte code The readObject() method of ObjectInputStream class
public static void main(String[] args){ implement user interfaces on computers by dividing
can be easily translated into native machine code. We must have to implement the Serializable
an application intro three interconnected parts
Multithreaded• Multithreaded Programs handled System.out.println(Adder.add(11,11)); interface for serializing the object.
multiple tasks simultaneously, which was helpful in System.out.println(Adder.add(12.3,12.6)); Advantages of Java Serialization
creating interactive, networked programs. • Java }} • It is mainly used to travel object's state on the
run-time system comes with tools that support multi network (which is
process synchronization used to construct smoothly known as marshaling).
interactive systems

.
<6>MOD 1.3 <7>MOD 2.3 <8>MOD 3.3 <9>MOD 4.3 <10>MOD 5.3
FINAL KEYWORD THREAD CALCULATOR
import javax.swing.*;
The final keyword in java is used to restrict the • JAVA is a multi-threaded programming language import java.awt.*;
user. The java final keyword can be used in which means we can develop multi-threaded import java.awt.event.ActionEvent;
many context. Final can program using Java. • A multi-threaded program import java.awt.event.ActionListener;
be:variable,method,class.Java final variable:If contains two or more parts that can run class calc extends JFrame implements
you make any variable as final, you cannot concurrently and each part can handle a different ActionListener {
change the value of final variable.A task at the same time making optimal use of the static JFrame f;
constructor cannot be declared as final.Local available resources specially when your computer static JTextField l;
final variable must be initializing during has multiple CPUs. • Each part of such program is String x, y, z;
called a thread. So, threads are light- calc()
declaration.We cannot change the value of a weight processes within a process.
final variable. {
LIFE CYCLE OF THREAD x = y = z = "";
A final method cannot be overridden.A final • A thread can be in one of the five states. • }
class not be inherited.If method parameters According to sun, there is only 4 states in thread life public static void main(String args[])
are declared final then the value of these cycle in java new, runnable, non-runnable and {
parameters cannot be changed.final, finally terminated. • There is no running state. But for better f = new JFrame("calculator");
and finalize are three different terms. finally is understanding the threads, we can explain it in the 5 try {
used in exception handling and finalize is a states. New Runnable Running
method that is called by JVM during garbage Non-Runnable (Blocked) Terminated
New - The thread is in new state if you create an UIManager.setLookAndFeel(UIManager.getSystemL
collection. instance of Thread class but before the invocation of
class Bike{ ookAndFeelClassName());
start() method.// Runnable - The thread is in }
final void run(){System.out.println("running");} runnable state after invocation of start() method, but catch (Exception e) {
}class Honda extends Bike{ the thread scheduler has not selected it to be System.err.println(e.getMessage());
void run(){System.out.println("running safely the running thread. // Running - The thread is in }
with 100kmph");} running state if the thread scheduler has selected it. calc c = new calc();
public static void main(String args[]){ Non-Runnable (Blocked) - This is the state when the l = new JTextField(16);
Honda honda= new Honda(); thread is still alive, but is currently not eligible to l.setEditable(false);
honda.run(); run//. Terminated - A thread is in terminated or dead JButton b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, ba,
state when its run() method exits. bs, bd, bm, be, beq, beq1;
} } CREATING THREAD
SUPER KEYWORD b0 = new JButton("0");
There are two ways to create a thread: • By b1 = new JButton("1");
The super keyword in Java is a reference extending Thread class b2 = new JButton("2");
variable which is used torefer immediate • By implementing Runnable interface. b3 = new JButton("3");
parent class object. Usage of Java super Extending Thread class: • Thread class provide b4 = new JButton("4");
Keyword:super can be used to refer constructors and methods to create and b5 = new JButton("5");
immediate parent class instance perform operations on a thread. • Thread class b6 = new JButton("6");
variable.super can be used to invoke extends Object class and implements Runnable b7 = new JButton("7");
immediate parent class method. super() can interface. b8 = new JButton("8");
: Implementing Runnable interface: • The b9 = new JButton("9");
be used to invoke immediate parent class Runnable interface should be implemented by any
constructor.We can use super keyword to beq1 = new JButton("=");
class whose instances are intended to be executed ba = new JButton("+");
access the data member (attribute)of parent by a thread. • Runnable interface have only one bs = new JButton("-");
class. It is used if parent class and child class method named run(). //public void run(): is used to bd = new JButton("/");
have same Attribute. perform action for a thread. bm = new JButton("*");
class Animal{ Steps to create a new Thread using Runnable : • beq = new JButton("C");
String color="white"; Create a Runnable implementer and implement run() be = new JButton(".");
}class Dog extends Animal{ method. • Instantiate Thread class and pass the JPanel p = new JPanel();
String color="black"; implementer to the Thread, bm.addActionListener(c); bd.addActionListener(c);
Thread has a constructor which accepts Runnable bs.addActionListener(c); ba.addActionListener(c);
void printColor(){ instance. • Invoke start() of Thread instance, start
System.out.println(color); b9.addActionListener(c); b8.addActionListener(c);
internally calls run() of the b7.addActionListener(c); b6.addActionListener(c);
System.out.println(super.color);}}class implementer. Invoking start(), creates a new Thread b5.addActionListener(c); b4.addActionListener(c);
TestSuper1{ which executes b3.addActionListener(c);b2.addActionListener(c);
public static void main(String args[]){ the code written in run(). b1.addActionListener(c); b0.addActionListener(c);
Dog d=new Dog(); be.addActionListener(c);beq.addActionListener(c);
d.printColor(); Advantages of Java Multithreading beq1.addActionListener(c);
}} It doesn't block the user because threads are p.add(l);
independent and you can perform multiple p.add(b1); p.add(b2); p.add(b3);
operations at same time. You can perform many p.add(ba); p.add(b4); p.add(b5);p.add(b6);
operations together so it saves time. p.add(bs); p.add(b7) p.add(b8); p.add(b9)
Threads are independent so it doesn't affect other
threads if exception occur in a single thread.
Note: At a time one thread is executed only.
</5>MOD 5.2 </4>MOD 4.2 </3>MOD 3.2 </2>MOD 2.2 </1>MOD 1.2
COMPONENTS & CONTAINERS EXCEPTION HANDLING If subclass (child class) has the same method as Dynamic• Java is capable of linking in new class
• A component is an independent visual control, • Exception is an abnormal condition. • In Java, an declared in the parent class, it is known as method libraries, methods, and
such as a push button or slider. • A container holds . exception is an event that disrupts the normal flow of overriding in Java.In other words, If a subclass objects. • It supports functions from native languages
a group of components. Thus, a container is a provides the specific implementation (the functions written
the program. It is an object which is thrown at
special type of component that is designed to hold of the method that has been declared by one of its in other languages such as C and C++). • It supports
runtime. • Exception Handling is a mechanism to
other Components. • Swing components inherit dynamic loading of classes. It means classes are
handle runtime errors such as parent class, it is known as method overriding.Usage
from the javax.Swing.JComponent class, loaded on demand
ClassNotFoundException, IOException, of Java Method Overriding
which is the root of the Swing component hierarchy.
SQLException, RemoteException, etc. • The core Method overriding is used to provide the specific
COMPONENTS Java Lexical Issues (Java Tokens)
advantage of exception handling is to maintain the implementation of a method which is already
• Swing components are derived from the TOKENS
normal flow of the application. • An exception provided by its superclass. • Method overriding is
JComponent class. • JComponent provides the • Java Tokens are the smallest individual building
normally disrupts the normal flow of the application used for runtime polymorphism.Rules for Java
functionality that is common to all block or smallest unit of a Java program
that is why we use exception handling Method Overriding The method must have the same
components. For example, JComponent supports • Java program is a collection of different types of
Checked Exception name as in the parent class The method must have
the pluggable look and feel. • JComponent inherits tokens, comments, and white spaces
• The classes which directly inherit Throwable class
the AWT classes Container and Component. the same parameter as in the parent class. • There Keywords
except // RuntimeException and Error are known as
Thus, a Swing component is built on and must be an IS-A relationship (inheritance). • A static • A keyword is a reserved word. You cannot use it as
checked exceptions //• e.g. IOException,
compatible with an AWT component. • All of method cannot be overridden. It is because the a variable name, constant name etc. • The meaning
SQLException etc. • Checked exceptions are
Swing’s components are represented by classes static method is bound with class whereas instance of the keywords has already been described to the
checked at compile-time.
defined within the package javax.swing. • The method is bound with an object. Static belongs to java compiler. These meaning cannot be changed. •
Unchecked Exception
following table shows the class names for Swing the class area, and an instance belongs to the heap Thus, the keywords cannot be used as variable
• The classes which inherit RuntimeException are
components area.Rules for Java Method Overriding The method names because that would try to change the existing
known as unchecked exceptions
CONTAINERS • e.g. ArithmeticException, NullPointerException, • must have the same name as in the parent class meaning of the keyword,which is not allowed.
• Swing defines two types of containers. The first The method must have the same parameter as in the • Java language has reserved 50 words as
Unchecked exceptions are not checked at
are top-level containers: JFrame, JApplet, parent class. • There must be an IS-A relationship keywords
compile-time, but they are checked at runtime
JWindow, and JDialog. These containers do not (inheritance).A static method cannot be overridden. Whitespace
Throw keyword
inherit JComponent. They inherit the AWT It is because the static • Java is a free-form language. This means that you
The Java throw keyword is used to explicitly throw
classes Component and Container. • The second do not need to follow any special indentation rules •
an exception. // We can throw either checked or method is bound with class whereas instance
type container are lightweight and the top-level White space in Java is used to separate tokens in
unchecked expectation in java by throw keyword method is bound with an object. Static belongs to
containers are heavyweight. This makes the the source file. It is also used to improve readability
public class TestThrow1{ the class area, and an instance belongs to the heap
top-level containers a special case in the Swing of the source code. Eg: int i = 0; • White spaces are
static void validate(int age){ if(age<18) // throw new area.
component library. required in some places. For example between the
ArithmeticException("not valid"); else Method overriding: int keyword and the variable name. • In java
System.out.println("welcome to vote"); } public static class Vehicle{
Java DataBase Connectivity (JDBC) whitespace is a space, tab, or newline
void main(String args[]) { validate(13); void run(){System.out.println("Vehicle is running");}
JDBC stands for Java Database Connectivity, which Operators •
System.out.println("rest of the code..."); } } }
is a standard //Java API for database-independent An operator is a symbol that takes one or more
Throws keyword class Bike2 extends Vehicle{
connectivity between the Java programming arguments and operates on them to produce a
The Java throws keyword is used to declare an void run(){System.out.println("Bike is running
language and a wide range of databases.//The result. • Unary Operator • Arithmetic Operator • shift
exception.// It gives an information to the
JDBC library includes APIs for each of the tasks safely");} Operator • Relational Operator • Bitwise Operator •
programmer that there may occur an exception so it
mentioned below that are commonly associated public static void main(String args[]){ Logical Operator • Ternary Operator • Assignment
is better for the programmer to provide the exception
with database usage. • Making a connection to a Bike2 obj = new Bike2(); Operator
handling code so that normal flow can be maintained
database //Exception Handling is mainly used to handle the obj.run(); String • In java, string is basically an object that
• Creating SQL or MySQL statements } } represents sequence of char values. • An array of
checked exceptions. //If there occurs any unchecked
• Executing SQL or MySQL queries in the database characters works same as java string. Eg: char[] ch =
exception such as NullPointerException, it is
• Viewing & Modifying the resulting records THIS KEYWORD {'a','t','n','y','l','a'}; String s = "atnyla"; • Java String
programmers fault that he is not performing check up
There can be a lot of usage of java this keyword. In class provides a lot of methods to perform
before the code being used.
JDBC Architecture java, this is a reference variable that refers to the operations on string such as compare(), concat(),
TRY & CATCH
JDBC Architecture consists of two layers current object.Usage of java this keyword this can be equals(), split(), length(), replace(), compareTo(),
The try statement allows you to define a block of
• JDBC API: This provides the application-to-JDBC used to refer current class instance variable. • this intern(), substring() etc.
code to be tested for errors while it is being
Manager connection. • JDBC Driver API: This can be used to invoke current class method Constants or Literals • Constants are fixed values
executed.// The catch statement allows you to define
supports the JDBC Manager-to-Driver Connection. (implicitly) • this() can be used to invoke current of a particular type of data,which cannot be modified
a block of code to be executed, if an error occurs in
The JDBC API uses a driver manager and in a program. • Java language specifies five major
the try block. class constructor. • this can be passed as an
database-specific drivers to provide transparent type of literals.
The try and catch keywords come in pairs argument in the method call. • this can be passed as
connectivity to heterogeneous databases. Eg: Integer literal : 100
argument in the constructor call.It is better approach
The JDBC driver manager ensures that the correct Floating-point literal : 98.6
finally block to use meaningful names for variables. So we use
driver is used to access each data source. Character literal : ‘s’
Java finally block is a block that is used to execute same name for instance variables and parameters in String literal : “sample”
important code such as closing connection, stream real time,and always use this keyword.this: to invoke Identifiers
etc. current class method You may invoke the method of • Identifiers are the names of variables, methods,
Java finally block is always executed whether the current class by using the this keyword.•If you classes, packages and interfaces
exception is handled or not. don't use the this keyword, compiler automatically
Java finally block follows try or catch block. adds this keyword while invoking the method.
Note: If you don't handle exception, before
terminating the program, JVM executes finally
block(if any)
</10>MOD 5.4; </9>MOD 4.4 </8>MOD 3.4 </7>MOD 2.4 </6>MOD 1.4
p.add(bm);p.add(b0); p.add(be); THREAD SYNCHRONIZATION ABSTRACT CLASSES AND METHODS
p.add(bd); • When we start two or more threads within a Data abstraction is the process of hiding certain
p.add(beq); program, there may be a situation when multiple details and
p.add(beq1); threads try to access the same resource and finally showing only essential information to the
p.setBackground(Color.pink); they can produce unforeseen result due to user.Abstract class: is a restricted class that cannot
f.add(p); concurrency issues. • For example, if multiple be used to create objects (to access it, it must be
f.setSize(200,200); f.show(); threads try to write within a same file then inherited from another class).Abstract method: can
} they may corrupt the data because one of the only be used in an abstract class, and itdoes not
public void actionPerformed(ActionEvent e) threads can override data or while one thread is have a body. The body is provided by the subclass
{ opening the same file at the same time (inherited from).An abstract class can have both
String s = e.getActionCommand(); another thread might be closing the same file. abstract and regular methods
if ((s.charAt(0) >= '0' && s.charAt(0) <= '9') || • So there is a need to synchronize the action of abstract class Bank{
s.charAt(0) == '.') { multiple threads and make sure that only one abstract int getRateOfInterest();}
if (!y.equals("")) thread can access the resource at a class SBI extends Bank{
y = y + s; given point in time. Following is the general form of int getRateOfInterest(){return 7;}
else the synchronized statement : Syntax }
x = x + s; l.setText(x + y + z); } synchronized(object identifier) { class PNB extends Bank{
else if (s.charAt(0) == 'C') { // Access shared variables and other shared int getRateOfInterest(){return 8;}
x = y = z = ""; resources } }
l.setText(x + y + z); } Understanding the problem without Synchronization class TestBank{
else if (s.charAt(0) == '=') { • In this example, we are not using synchronization public static void main(String args[]){
double te; and creating multiple threads that are accessing Bank b;
if (y.equals("+")) display method and produce b=new SBI();
te = (Double.parseDouble(x) + the random output. System.out.println("Rate of Interest is:
Double.parseDouble(z)); Thread suspend() method "+b.getRateOfInterest()+" %");
else if (y.equals("-")) • The suspend() method of thread class puts the b=new PNB();
te = (Double.parseDouble(x) - thread from System.out.println("Rate of Interest is:
Double.parseDouble(z)); running to waiting state. • This method is used if "+b.getRateOfInterest()+" %");
else if (y.equals("/")) you want to stop the thread execution and }}
te = (Double.parseDouble(x) / start it again when a certain event occurs. • This
Double.parseDouble(z)); method allows a thread to temporarily cease
else execution. • The suspended thread can be resumed
te = (Double.parseDouble(x) * using the resume() method.
Double.parseDouble(z)); Syntax
l.setText(x + y + z + "=" + te); public final void suspend()
x = Double.toString(te); y = z = ""; } Thread resume() method
else {if (y.equals("") || z.equals("")) • The resume() method of thread class is only used
y = s; with suspend() method. • This method is used to
else { resume a thread which was suspended
double te; if (y.equals("+")) using suspend() method. • This method allows the
te = (Double.parseDouble(x) + suspended thread to start again.
Double.parseDouble(z)); Syntax
else if (y.equals("-")) public final void resume()
te = (Double.parseDouble(x) - Thread stop() method
Double.parseDouble(z)); • The stop() method of thread class terminates the
else if (y.equals("/")) te = (Double.parseDouble(x) / thread execution. • Once a thread is stopped, it
Double.parseDouble(z)); cannot be restarted by start() method.
else Syntax
te = (Double.parseDouble(x) * public final void stop()
Double.parseDouble(z)); public final void stop(Throwable obj)
x = Double.toString(te);
y = s;
z = ""; } l.setText(x + y + z); } }}
MOD5.P3 MOD5.P5 MOD5.P7
Creating GUI programs in Java using Swing involves several steps. Below JDBC (Java Database Connectivity) is a Java API that allows Java
Containers is a step-by-step guide along with an example to create a simple GUI program applications to interact with relational databases like MySQL, Oracle,
that displays a window with a button. PostgreSQL, SQL Server, etc. Here are the general steps to establish JDBC
Swing defines two types of containers.
### Steps to Create a GUI Program with Swing: connectivity with a relational database, followed by a simple example:
The first are top-level containers (heavyweight) 1. **Import Necessary Packages:Import the required packages to use Swing Steps to Establish JDBC Connectivity:
The second typeof containers supported by components. 1. Import JDBC Packages: Import the necessary JDBC packages, which
Swing Components are lightweight because Swing are lightweight containers. 2. **Create the Main Frame: Create a `JFrame` object, which represents the typically include `java.sql` and database-specific packages (e.g.,
they are written entirely in Java
The first are top-level containers main window of the GUI application. `com.mysql.jdbc` for MySQL).
Lightweight components do not call the native operating system for
JFrame, JApplet, JWindow, and JDialog. 3. **Set Layout Manager: Choose an appropriate layout manager (e.g., 2. Load and Register JDBC Driver: Load and register the JDBC driver for the
drawing the graphical user interface(GUI) components
`FlowLayout`, `BorderLayout`, `GridLayout`) for the main frame and set it specific database you're using. This is typically done using
They can be transparent, which enables non rectangular shapes. These containers do not inherit JComponent using the `setLayout()` method. `Class.forName()`.
lightweight components are more efficient and more flexible.
They inherit the AWT classes Component and Container 4. **Create Components: Create the necessary components (e.g., `JButton`, 3. Establish Connection: Establish a connection to the database using the
Swing supports a pluggable look and feel (PLAF).
`JLabel`, `JTextField`, etc.) that you want to add to the frame. `DriverManager.getConnection()` method. Provide the database URL,
Because each Swing component is rendered by Java code not by The top-level containers are heavyweight. 5. **Add Components to the Frame: Add the components to the main frame username, and password.
native peers, the look and feel of a component is under the control The second type of containers supported by Swing using the `add()` method. 4. Create Statement:: Create a `Statement` or `PreparedStatement` object
of Swing. are lightweight containers. 6. **Set Frame Properties: Set properties for the main frame, such as title, to execute SQL queries.
It is possible to separate the look and feel of a component from
Lightweight containers do inherit JComponent size, default close operation, etc. 5. Execute Query: Execute SQL queries using the `executeQuery()` method
the logic of the component. 7. **Display the Frame: Set the visibility of the frame using the `setVisible()` for SELECT statements or `executeUpdate()` method for INSERT, UPDATE,
Advantage:
E.g. JPanel is a general-purpose container.
Lightweight containers are often used to organize and method. DELETE statements.
It is possible to change the way that a component is rendered without Example: Simple GUI Program with a Button 6. Process Results: Process the results obtained from the database, if any,
affecting any of its other aspects manage groups of related components because a
Here's a simple example that demonstrates how to create a GUI program by iterating through the result set using `ResultSet` object.
it is possible to lightweight container can be contained within another with a button using Swing: 7. Close Connection: Close the connection, statement, and result set to
given component without creating any side effects in the code container. import javax.swing.JButton; release database resources.
that uses that component. The Top-Level Container Panes: import javax.swing.JFrame;
It is possible to define entire sets of look-and-feels that represent Glass pane : import javax.swing.JPanel; Example: JDBC Connectivity with MySQL Database:
different GUI styles The glass pane is the top-level pane. public class SimpleGUIExample {
It sits above and completely covers all other panes. public static void main(String[] args) { import java.sql.*;
o Once this is done, all components are automatically rendered // Step 2: Create the main frame (JFrame) public class JDBCDemo {
using that style.
By default, it is a transparent instance of JPanel.
JFrame frame = new JFrame("Simple GUI Example"); public static void main(String[] args) {
Layered pane : // Step 3: Set layout manager (Optional, by default it's BorderLayout) try {
MVC The layered pane is an instance of JLayeredPane. frame.setLayout(new FlowLayout()); Class.forName("com.mysql.cj.jdbc.Driver");
A component is a composite of three distinct visual aspects: The layered pane allows components to be given a // Step 4: Create components (JButton) String jdbcUrl = "jdbc:mysql://localhost:3306/yourdatabase";
The state information associated with the depth value. JButton button = new JButton("Click Me!"); String username = "yourusername";
component MODEL This value determines which component overlays another. // Step 5: Add components to the frame String password = "yourpassword";
The way that the component looks when rendered on Content pane: frame.add(button); Connection connection = DriverManager.getConnection(jdbcUrl,
the screen VIEW The pane with which yourapplication will interact // Step 6: Set frame properties username, password);
frame.setSize(300, 200); // Set frame size Statement statement = connection.createStatement();
The way that the component reacts to CONTROLLER the most is the content pane
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); ResultSet resultSet = statement.executeQuery("SELECT * FROM
MVC (Model View Controller) architecture is successful because each When we add a component, such as a button, to a top- frame.setLocationRelativeTo(null); yourtable");
piece of the design corresponds to an aspect of a component. level container, we will add it to the content pane. // Step 7: Display the frame while (resultSet.next()) {
By default, the content pane is an frame.setVisible(true); int id = resultSet.getInt("id");
opaque instance of JPanel. } String name = resultSet.getString("name");
} System.out.println("ID: " + id + ", Name: " + name);

MOD5.P9 MOD3.P1 MOD3.P3 MOD3.P5


Creating and executing queries in Java using JDBC involves utilizing STREAM CLASSES
`Statement` or `PreparedStatement` objects to execute SQL statements
against a database. Below, I'll provide examples for creating and executing
SELECT, INSERT, UPDATE, and DELETE queries using JDBC.

1. SELECT Query Example:


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class SelectQueryExample {
publicstaticvoidmain(String[]args){
try(Connectionconnection=DriverManager.getConnection("jdbc:mysql://local
host:3306/mydatabase", "root", "password");
Statement statement = connection.createStatement(); Checked Exceptions Unchecked Exceptions
ResultSet resultSet = statement.executeQuery("SELECT * FROM Occur at compile time. Occur at runtime.
users")) {
The compiler checks for a checked The compiler doesn't check for
while (resultSet.next()) {
exception. exceptions.
int id = resultSet.getInt("id");
String name = resultSet.getString("name"); Can be handled at the compilation Can't be caught or handled during
String email = resultSet.getString("email"); time. compilation time.
System.out.println("ID: " + id + ", Name: " + name + ", Email: " + The JVM requires that the exception The JVM doesn't require the exception
email); be caught and handled. to be caught and handled.
} } catch (Exception e) { Example of Checked exception- Example of Unchecked Exceptions-
e.printStackTrace(); 'File Not Found Exception' 'No Such Element Exception'
} }}
2. INSERT Query Example:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class InsertQueryExample {
publicstaticvoidmain(String[]args){
try(Connectionconnection=DriverManager.getConnection("jdbc:mysql://local
host:3306/mydatabase", "root", "password");
Statement statement = connection.createStatement()) {
String insertQuery = "INSERT INTO users (name, email) VALUES
('John Doe', '[email protected]')";
int rowsAffected = statement.executeUpdate(insertQuery);
if (rowsAffected > 0) {
System.out.println("Record inserted successfully!");
} } catch (Exception e) {
e.printStackTrace(); } }}
MOD1.P1 MOD1.P3 MOD1.P5 MOD1.P7
Basic Object Oriented Programming(OOPS) Concepts:
Encapsulation: It is the bundling of data (attributes) and methods (functions)
that operate on the data into a single unit or class, restricting direct access to
some of its components and hiding the internal state of an object.
Example: A class `BankAccount` encapsulates attributes like account
number, balance, and methods like deposit, withdraw, and get Balance.
These methods control access to the account balance and ensure it is
maintained correctly.
Purpose:
- Protects the data from unauthorized access and modification.
- Provides a way to control the behaviour of an object.
Inheritance: It is a mechanism where a new class inherits properties
(attributes and methods) and behaviours (functionality) from an existing Two types of garbage collection activity usually happen in Java.
class, allowing the creation of a hierarchy of classes. These are:
Example: Consider a class `Vehicle` with attributes and methods common to
all vehicles. We can create subclasses like `Car` and `Motorcycle` that inherit 1. Minor or incremental Garbage Collection: It is said to have
from the `Vehicle` class and extend it with specific attributes and methods occurred when unreachable objects in the young generation heap
unique to cars and motorcycles. memory are removed.
Purpose: 2. Major or Full Garbage Collection: It is said to have occurred
- Promotes code reusability by allowing the reuse of existing code. when the objects that survived the minor garbage collection are
- Facilitates the creation of a class hierarchy, leading to more organized and copied into the old generation or permanent generation heap
maintainable code. memory are removed. When compared to the young generation,
Polymorphism: It allows objects of different classes to be treated as objects garbage collection happens less frequently in the old generation.
of a common superclass, providing a way to perform a single action in
different ways. It is achieved through method overriding and method
overloading.
Example: Consider a superclass `Shape` with a method `draw()`. Subclasses
like `Circle` and `Rectangle` can override the `draw()` method to provide
specific implementations for drawing a circle and rectangle, respectively. At
runtime, the appropriate `draw()` method is called based on the object type.
- Purpose:
- Enhances flexibility and extensibility by allowing the use of a single
interface to represent different types of objects.
- Enables code to work with objects of multiple types, promoting code
reusability and maintainability.

In summary, Object-Oriented Programming (OOP) is a programming


paradigm that focuses on organizing code around objects and their
interactions. The four core OOP concepts (Data Abstraction, Encapsulation,
Inheritance, and Polymorphism) provide a foundation for designing robust,
modular, and scalable applications by promoting code reusability,
maintainability, and flexibility.

MOD4.P1
Thread Creation: Thread life cycle in Java, as well as in many other programming
1. Extending Thread Class: languages, refers to the different states a thread goes through
Create a class that extends the Thread class.
from its creation to its termination. Understanding these states is
Override the run() method to define the thread's code.
essential for effective multithreaded programming.
List Interface:Ordered Collection: It extends Collection, defining Create an instance of your class and call its start() method to
Here are the typical states a thread can be in:
an ordered collection of elements that allows duplicates. start the thread.
1. New:
Features: class MyThread extends Thread {
o The thread object has been created but not yet started.
o Maintains insertion order. public void run() {
o It's not yet eligible for execution by the thread scheduler.
o Allows random access to elements via indices. System.out.println("Thread is running...");
} 2. Runnable:
o The thread has been started using the start() method.
}
o It's ready to run but might be waiting for its turn to be
public class Main {
public static void main(String[] args) { executed by the scheduler.
o It's also considered Runnable when it's temporarily
MyThread thread = new MyThread();
thread.start(); // Starts the thread inactive due to I/O or other events.
} 3. Running:
} o The thread is actively executing its code on a CPU core.

2. Implementing Runnable Interface: o Only one thread can be in the Running state on a

Create a class that implements the Runnable interface. single core at a time.
Implement the run() method to define the thread's code. 4. Blocked (or Waiting):
Create a Thread object, passing an instance of your o The thread is temporarily inactive, waiting for a specific

Runnable class to its constructor. event to occur.


2.ArrayList Class: Call the start() method on the Thread object to start the o This can happen due to:
Implementation of List: It's a resizable array implementation of thread. Trying to acquire a lock on a shared resource
the List interface. Java (Blocked).
Key Characteristics: class MyRunnable implements Runnable { Calling methods like wait(), join(), or sleep()
o Dynamically resizes as needed.
public void run() { (Waiting).
o Efficient for random access and manipulation.
System.out.println("Thread is running..."); 5. Timed Waiting:
o Not thread-safe (use Vector for multithreading).
} o The thread is waiting for a specific amount of time to
3.Iterator Interface: }
For Traversing Collections: It provides a way to iterate through
elapse.
Public class Main{ o This typically occurs when using methods like sleep()
the elements of a collection sequentially.
Public static void main(String[] args){ or wait(timeout).
Key Methods:
MyRunnable runnable = new MyRunnable(); 6. Terminated:
o hasNext(): Returns true if there are more elements to
Thread thread = new Thread(runnable); o The thread has finished executing its code.
iterate over.
thread.start(); // Starts the thread o It can no longer be restarted and won't transition to any
o next(): Returns the next element in the iteration.

o remove(): Removes the last element returned by next().


} other state.
}
M5.P2 Swing AWT
Swing components are AWT components are
platform- independent. platform- dependent
}
resultSet.close(); Swing provides several The AWT defines a basic set
additional components such as of controls, windows, and
statement.close(); scroll panes, trees etc in addition dialog boxes that support a usable,
connection.close(); to other standard components but limited graphical interface.
} catch (Exception e) { Swing is written entirely in Java. AWT components use
e.printStackTrace(); So swing components are light- native code. So they are heavy
} weight weight
}
Swing supports a pluggable look In AWT look and feel of
} and feel (PLAF) that can be each component is fixed and it
dynamically changed at run-time is difficult to change its look and feel.
depending on environment
Explanation: Swing follow MVC AWT does not follow MVC
- **Step 2:** The MySQL JDBC driver is loaded using
`Class.forName()`.
- **Step 3:** A connection to the MySQL database is
established using `DriverManager.getConnection()`.
- **Step 4:** A `Statement` object is created to execute SQL
queries.
- **Step 5:** A SELECT SQL query is executed using
`executeQuery()`, which returns a `ResultSet`.
- **Step 6:** The `ResultSet` is processed to retrieve and
display the data.
- **Step 7:** Finally, the connection, statement, and result set
are closed to release resources.

Swing components are derived from the JComponent class.


JComponent provides the functionality that is common to
all components.
E.g JComponent supports the pluggable look and
feel. JComponent inherits the AWT classes
Container and Component.
So, a Swing component is built on and compatible with an AWT
component.
components are represented by classes
defined within the package javax.swing.

3. UPDATE Query Example:


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class UpdateQueryExample {
publicstaticvoidmain(String[]args){
try(Connectionconnection=DriverManager.getConnection("jdbc:mysql://local
host:3306/mydatabase", "root", "password");
Statementstatement=connection.createStatement()){
StringupdateQuery="[email protected]
m' WHERE id = 1";
int rowsAffected = statement.executeUpdate(updateQuery);
if (rowsAffected > 0) {
System.out.println("Record updated successfully!");
} } catch (Exception e) {
e.printStackTrace();
} }}

4. DELETE Query Example:


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class DeleteQueryExample {
publicstaticvoidmain(String[]args){
try(Connectionconnection=DriverManager.getConnection("jdbc:mysql://local
host:3306/mydatabase", "root", "password");
Statement statement = connection.createStatement()) {
String deleteQuery = "DELETE FROM users WHERE id = 1";
int rowsAffected = statement.executeUpdate(deleteQuery);
if (rowsAffected > 0) {
System.out.println("Record deleted successfully!");
}
} catch (Exception e) {
Thread Synchronization:
Purpose: To prevent multiple threads from accessing
shared resources or code simultaneously, ensuring data
consistency and preventing race conditions.
Mechanisms:
o Synchronized blocks: Use the synchronized

keyword to lock a specific object or code block.


o Synchronized methods: Declare a method as

synchronized to lock the object on which it's called.

public class SharedCounter {


private int count = 0;
public synchronized void increment() {
count++;
}
} Feature/Aspect String Class StringBuffer Class
Event Listener Interface Event Source(s)
Mutability Immutable Mutable
ActionListener Buttons, Menu Items, Text Fields
Key Points: Less efficient for Designed for efficient
Mouse Listener Any Component
Use Thread.sleep() to pause a thread for a specified Key Listener Text Fields, Text Areas
frequent string string manipulations using
time. manipulations due to methods like append(),
Window Listener Windows, Frames, Dialogs
Use Thread.join() to wait for a thread to finish before Performance immutability insert(), delete()
Component Listener Components
continuing. Thread-safe due to
Consider thread pools for managing multiple threads Thread-safe due to synchronization
efficiently. Thread Safety immutability mechanisms
Handle exceptions properly within threads to prevent May lead to memory
inefficiencies when More memory-efficient for
program crashes.
frequently creating new frequent modifications as it
Memory string objects allows in-place changes
Suitable when Suitable when frequent
immutability is desired, string manipulations are
and frequent changes needed, and thread safety
Usage are not required is required

You might also like