Java notes
Java notes
Introduction to Java
History of java
Data types
Comments
Variables
C++ vs Java
Explain jvm
JVM(Java Virtual Machine) runs Java applications as a run-time
engine.
1.Documentation Section
Package Declaration
Import Statements
Interface Section
Class Definition
Operator in java
Java operators are special symbols that perform operations on variables or values. They can
be classified into several categories based on their functionality. These operators play a
crucial role in performing arithmetic, logical, relational, and bitwise operations etc.
1. Arithmetic Operators
2. Unary Operators
3. Assignment Operator
4. Relational Operators
5. Logical Operators
6. Ternary Operator
7. Bitwise Operators
8. Shift Operators
1. Arithmetic Operators
Arithmetic Operators are used to perform simple arithmetic operations on primitive and
non-primitive data types.
* : Multiplication
/ : Division
% : Modulo
+ : Addition
– : Subtraction
Example:
// Arithmetic Operators
import java.io.*;
class Geeks
int a = 10;
int b = 3;
2. Unary Operators
Unary Operators need only one operand. They are used to increment, decrement, or negate
a value.
++ , Increments by 1.
-- , Decrements by 1.
Example:
// Unary Operators
import java.io.*;
// Driver Class
class Geeks {
// main function
// Interger declared
int a = 1-0;
int b = 10;
. Assignment Operator
‘=’ Assignment operator is used to assign a value to any variable
+= , Add and assign.
-= , Subtract and assign.
*= , Multiply and assign.
/= , Divide and assign.
%= , Modulo and assign
EXAMPLE
// Java Program to show the use of
// Assignment Operators
import java.io.*;
// Driver Class
class Geeks {
// Main Function
public static void main(String[] args)
{
// Assignment operators
int f = 7;
System.out.println("f += 3: " + (f += 3));
System.out.println("f -= 2: " + (f -= 2));
System.out.println("f *= 4: " + (f *= 4));
System.out.println("f /= 3: " + (f /= 3));
System.out.println("f %= 2: " + (f %= 2));
System.out.println("f &= 0b1010: " + (f &= 0b1010));
System.out.println("f |= 0b1100: " + (f |= 0b1100));
System.out.println("f ^= 0b1010: " + (f ^= 0b1010));
System.out.println("f <<= 2: " + (f <<= 2));
System.out.println("f >>= 1: " + (f >>= 1));
System.out.println("f >>>= 1: " + (f >>>= 1));
}
}
4. Relational Operators
Relational Operators are used to check for relations like equality, greater than, and less than
== , Equal to.
// Driver Class
class Geeks {
// main function
public static void main(String[] args)
{
// Comparison operators
int a = 10;
int b = 3;
int c = 5;
6. Ternary operator
The Ternary Operator is a shorthand version of the if-else statement. It has three operands
and hence the name Ternary. The general format is ,
condition ? if true : if false
Control Statements in Java
What is a Statement?
Definition:
o if statements
o switch statement
2. Loop statements
o do while loop
o while loop
o for loop
3. Jump statements
o break statement
o continue statement
LOOP STATEMENT
Java Loops
In Java, there are three types of Loops which are listed below:
for loop
while loop
do-while loop
1. for loop
The for loop is used when we know the number of iterations (we
know how many times we want to repeat a task). The for
statement consumes the initialization, condition, and
increment/decrement in one line thereby providing a shorter,
easy-to-debug structure of looping.
import java.io.*;
class Geeks {
2. while Loop
A while loop is used when we want to check the condition before running the code.
import java.io.*;
class Geeks {
int i = 0;
i++;
}
}
do-while Loop
The do-while loop in Java ensures that the code block executes at least once before the
condition is checked.
import java.io.*;
class Geeks {
int i = 0;
do {
i++;
JUMPP/BRANCHING STATEMENT
Branching statements are used to change the flow of execution from one section of a
program to another. Branching statements are typically utilized within control statements.
Java includes three types of branching statements: continue, break, and return.
if (num == 5) {
System.out.println(num);
}
The continue statement is used to skip the current loop iteration and go to the next.
5. if (num == 5) {
7. }
8. System.out.println(num);
9. }
10. }
11. }
Look at the following illustration to see the difference between class and
objects:
class
Fruit
objects
Apple
Banana
Mang
Java Classes/Objects
Java is an object-oriented programming language.
. For example: in real life, a car is an object. The car has attributes, such as weight and color,
and methods, such as drive and brake.
A Class is like an object constructor, or a "blueprint" for creating objects.
Create a Class
To create a class, use the keyword class:
Create a class named "Main" with a variable x:
Ex.
public class Main {
int x = 5;
}
Create an Object
Example
Create an object called "myObj" and print the value of x:
public class Main {
int x = 5;
Java Constructors
A constructor in Java is a special method that is used to initialize objects. The constructor is
called when an object of a class is created. It can be used to set initial values for object
attributes:
Example
Create a constructor:
// Create a Main class
public class Main {
int x; // Create a class attribute
// Outputs 5
Types of constructor
Types of Constructors in Java
Now is the correct time to discuss the types of the constructor, so primarily there are three
types of constructors in Java are mentioned below:
Default Constructor
Parameterized Constructor
Copy Constructor
Example
public class Main {
int x;
public Main(int y) {
x = y;
System.out.println(myObj.x);
// Outputs 5
java Strings
Strings are used for storing text.
A String variable contains a collection of characters surrounded by double quotes:
Example
Create a variable of type String and assign it a value:
String greeting = "Hello";
Try it Yourself »
String Length
A String in Java is actually an object, which contain methods that can perform certain
operations on strings. For example, the length of a string can be found with
the length() method:
Example
String txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
System.out.println("The length of the txt string is: " + txt.length());
Try it Yourself »
INHERITANCE IN JAVA
Java, Inheritance is an important pillar of OOP(Object-Oriented Programming). It is the
mechanism in Java by which one class is allowed to inherit the features(fields and methods)
of another class. In Java, Inheritance means creating new classes based on existing ones
Important Terminologies Used in Java Inheritance
Class: Class is a set of objects which shares common characteristics/ behavior and
common properties/ attributes. It is just a template or blueprint or prototype from
which objects are created.
Super Class/Parent Class: The class whose features are inherited is known as a
superclass(or a base class or a parent class).
Sub Class/Child Class: The class that inherits the other class is known as a subclass(or
a derived class, extended class, or child class)
Single Inheritance
In single inheritance, a sub-class is derived from only one super class. It inherits the
properties and behavior of a single-parent class. Sometimes, it is also known as simple
inheritance. In the below figure, ‘A’ is a parent class and ‘B’ is a child class. The class ‘B’
inherits all the properties of the class ‘A’.
3. Hierarchical Inheritance
In Hierarchical Inheritance, one class serves as a superclass (base class) for more than one
subclass. In the below image, class A serves as a base class for the derived classes B, C, and
D.
3. Multiple Inheritance (Through Interfaces)
In Multiple inheritances
Please note that Java does not support multiple inheritances with classes. In Java, we can
achieve multiple inheritances only through Interfaces. In the image below, Class C is derived
from interfaces A and B.
Method overloading
Method overloading allows you to define multiple methods within the same class that share
the same name but have different parameter lists (number, type, or order of parameters)
Example;
class Calculator {
// Method to add two integers
int add(int a, int b) {
return a + b;
}
An abstract class is declared using the “abstract” keyword in its class definition.
// Abstract class
abstract class Animal {
// Abstract method (does not have a body)
public abstract void animalSound();
// Regular method
public void sleep() {
System.out.println("Zzz");
}
Interfaces.
An interface is a completely "abstract class" that is used to group related methods with
empty bodies:
To access the interface methods, the interface must be "implemented" (kinda like inherited)
by another class with the implements keyword (instead of extends).
Example
// Interface
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void sleep(); // interface method (does not have a body)
}
class Main {
public static void main(String[] args) {
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
myPig.sleep();
}
}
Multithreading
Multithreading is a Java feature that allows concurrent execution of two or more parts of a
program for maximum utilization of CPU. Each part of such program is called a thread. So,
threads are light-weight processes within a process.
Threads can be created by using two mechanisms :
1. Extending the Thread class
2. Implementing the Runnable Interface
1. New State
2. Runnable State
3. Blocked State
4. Waiting State
6. Terminated State
Java Applets
A Java Applet is a Java program that runs inside a web browser. An Applet is embedded in an
HTML file using <applet> or <objects> tags. Applets are used to make the website more
dynamic and entertaining. Applets are executed in a sandbox for security, restricting access
to local system resources.
Java Applet Life Cycle
Local Applet
Local Applet is written on our own, and then we will embed it into web pages. Local Applet
is developed locally and stored in the local system.
<applet
codebase = "tictactoe"
code = "FaceApplet.class"
width = 120
height = 120>
</applet>
FaceApplet.java
//Import packages and classes
import java.applet.*;
import java.awt.*;
import java.util.*;
import java.awt.event.*;
//Creating FaceApplet class that extends Applet
public class FaceApplet extends Applet
{
//paint() method starts
public void paint(Graphics g){
//Creating graphical object
g.setColor(Color.red);
g.drawString("Welcome", 50, 50);
g.drawLine(20, 30, 20, 300);
g.drawRect(70, 100, 30, 30);
g.fillRect(170, 100, 30, 30);
g.drawOval(70, 200, 30, 30);
g.setColor(Color.pink);
g.fillOval(170, 200, 30, 30);
g.drawArc(90, 150, 30, 30, 30, 270);
g.fillArc(270, 150, 30, 30, 0, 180);
}
}
Remote Applet
A remote applet is designed and developed by another developer. It is located or available
on a remote computer that is connected to the internet.
we must know the applet's address on the web that is referred to as Uniform Recourse
Locator(URL).
<applet
codebase = "http://www.myconnect.com/applets/"
code = "FaceApplet.class"
width = 120
height =120>
</applet>
Java Application is just like a Java program that runs on an underlying operating
system with the support of a virtual machine. It is also known as an application program.
The graphical user interface is not necessary to execute the java applications, it can be run
with or without it.
Parameter in Applet
We can get any information from the HTML file as a parameter. For this purpose, Applet
class provides a method named getParameter().
import java.applet.Applet;
import java.awt.Graphics;
myapplet.html
<html>
<body>
<applet code="UseParam.class" width="300" height="300">
<param name="msg" value="Welcome to applet">
</applet>
</body>
</html>
The java.awt package contains AWT API classes such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List, and so on.
Java AWT Hierarchy
Components: AWT provides various components such as buttons, labels, text fields,
checkboxes, etc used for creating GUI elements for Java Applications.
Containers: AWT provides containers like panels, frames, and dialogues to organize
and group components in the Application.
1. Java AWT Label
AWT Button is a control component with a label that generates an event when clicked on.
Button Class is used for creating a labeled button that is platform-independent.
The object of the AWT List class represents a list of text items.
Classification of Events
1. Foreground Events: Foreground events are the events that require user interaction
to generate. Examples of these events include Button clicks, Scrolling the scrollbar,
Moving the cursor, etc.
2. Background Events: Events that don’t require interactions of users to generate are
known as background events.
ActionEvent ActionListener
AdjustmentEvent AdjustmentListener
Event Class Listener Interface
ContainerEvent ContainerListener
ComponentEvent ComponentListener
FocusEvent FocusListener
ItemEvent ItemListener
KeyEvent KeyListener
MouseWheelEvent MouseWheelListener
TextEvent TextListener
WindowEvent WindowListener
5. InetAddress – The InetAddress class is used to provide methods to get the IP address
of any hostname. An IP address is expressed by a 32-bit or 128-bit unsigned number.
InetAddress can handle both IPv4 and IPv6 addresses.
7. Socket – The Socket class is used to create socket objects that help the users in
implementing all fundamental socket operations. The users can implement various
networking actions such as sending, reading data, and closing connections. Each
Socket object built using java.net.Socket class has been connected exactly with 1
remote host; for connecting to another host, a user must create a new socket object.
10. URL – The URL class in Java is the entry point to any available sources on the internet.
A Class URL describes a Uniform Resource Locator, which is a signal to a “resource”
on the World Wide Web. A source can denote a simple file or directory, or it can
indicate a more difficult object, such as a query to a database or a search engine.
4. SocketOption – The SocketOption interface helps the users to control the behavior of
sockets. Often, it is essential to develop necessary features in Sockets. SocketOptions
allows the user to set various standard options.
Example:
// Java code to illustrate print()
import java.io.*;
class Demo_print {
public static void main(String[] args)
{
// using print()
// all are printed in the
// same line
System.out.print("GfG! ");
System.out.print("GfG! ");
System.out.print("GfG! ");
}
}
The InputStream and OutputStream classes (abstract) are the super classes of all the
input/output stream classes: classes that are used to read/write a stream of bytes. Following
are the byte array stream classes provided by Java −
InputStream OutputStream
FIleInputStream FileOutputStream
ByteArrayInputStream ByteArrayOutputStream
ObjectInputStream ObjectOutputStream
PipedInputStream PipedOutputStream
FilteredInputStream FilteredOutputStream
BufferedInputStream BufferedOutputStream
DataInputStream DataOutputStream
JDBC Drivers
Java Database Connectivity (JDBC) is an application programming interface (API) for
the Java programming language that defines how a client can access and interact with any
kind of tabular data, especially a relational database. JDBC Drivers uses JDBC APIs which was
developed by Sun Microsystem, but now this is a part of Oracle.
The JDBC classes are contained in the Java Package java.sql and javax.sql.
JDBC helps you to write Java applications that manage these three programming activities:
1. Connect to a data source, like a database.
2. Send queries and update statements to the database
3. Retrieve and process the results received from the database in answer to your query
connectivity model
In Java, the connectivity model for interacting with databases is achieved through the Java
Database Connectivity (JDBC) API, which provides a standard interface for Java applications
to connect to and interact with various relational databases.