Introduction to Java programming covering syntax, data types, control structures, object-oriented principles, and basic algorithms through hands-on projects.
JAVA
Introduction:
Compilation Flow of Java:
Writing Code: You write your Java code in a text editor or an Integrated Development Environment (IDE).
Compilation: You compile your Java code using the Java compiler (javac). The compiler checks for syntax errors and generates byte code files (.class files) for each class in your code.
Byte code Generation: The byte code files contain instructions that the Java Virtual Machine (JVM) can understand. This byte code is platform-independent, meaning it can run on any device or platform with a JVM.
Execution: The JVM loads and executes the byte code files. It translates the byte code into machine code specific to the underlying hardware, allowing your Java program to run.
Features Of Java:
Application of Java:
Hello world! Program:
Public class Simple{
Public static void main(String args[]){
System.out.println(“Hello world!”);
}
}
Output:
Hello world!
Variables:
In java, a variable is a named storage location that holds a value that can change during the execution of a program.
Variables in Java must be declared before they are used. When declaring a variable, you specify its type and name.
Example: int value;
There are three types of variables in java.
Local: Local Variables are declared within a Method. They are only accessible within the scope in which they are declared.
Example:
public class Vari {
public static void main(String[] args) {
int Number = 26;
System.out.println(“The Value Of Number is:” + Number);
}
Output: 26
Instance Variable: Instance variables are variables declared within a class, holding unique data for each object instance; they define the state of individual objects in object-oriented programming.
Example:
public class Vari{
int Number1=30;
public static void main(String[] args) {
int Number = 26;
Vari Obj = new Vari();
System.out.println (“The Value Of Number1 is:” + Obj.Number1);
}
Output: 30
Static Variable: A variable that is declared as static is called a static variable. It cannot be local. You can create a single copy of the static variable and share it among all the instances of the class. Memory allocation for static variables happens only once when the class is loaded in the memory.
Example:
public class Vari{
static int Number1=30;
public static void main(String[] args) {
int Number = 26;
System.out.println (“The Value Of Number1 is:” + Number1);
}
Output: 30
Data Type:
Data types are used to declare variables and specify the type of data that the variable can hold.
Data types are classified into two types.
Size of Primitive Data types:
Data Type |
Values |
Example |
Size |
boolean |
true, false |
boolean one=false; |
1 bit |
char |
‘A’ |
char letr=’A’ |
2 byte |
byte |
-128 to 127 |
byte val=-50; |
1 byte |
short |
-32 k to 32 k |
short val1=-34; |
2 byte |
int |
-2 B to 2 B |
int val2=9000; |
4 byte |
long |
Above 2 B |
long val3=8923438 L |
8 byte |
float |
1.0998 f |
float val4=1.987f |
4 byte |
double |
2.334 d |
double val5=0.9834 d |
8 byte |
Type Casting:
typecasting refers to the process of converting one data type into another. Typecating are classified into two types, they are implicit and explicit.
Implicit Type Casting:
Implicit typecasting occurs automatically when the destination data type can hold all possible values of the source data type. For example, converting an integer to a floating-point number.
int numInt = 10;
double numDouble = numInt; // Implicit typecasting from int to double
Explicit Type Casting:
Explicit typecasting is performed manually by the programmer and is required when the destination data type cannot hold all possible values of the source data type. This conversion may result in loss of data. For example, converting a double to an int.
double numDouble = 10.5;
int numInt = (int) numDouble; // Explicit typecasting from double to int
Scanner:
A scanner is used to obtain values from the user, and it is found in the java.util package.
Input Types:
Types |
Definition |
nextBoolean() |
Obtains a Boolean Values from the User. |
nextByte() |
Obtains a Byte Values from the User. |
nextDouble() |
Obtains a Double Values from the User |
nextFloat() |
Obtains a Float Values from the User |
nextInt() |
Obtains a Int Values from the User |
nextLine() |
Obtains a String Values from the User |
nextLong() |
Obtains a Long Values from the User |
nextShort() |
Obtains a Short Values from the User |
import.java.util.Scanner ; // Import the Scanner class
public class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter username");
String userName = myObj.nextLine(); // Read user input
System.out.println("Username is: " + userName); // Output user input
}
}
Example:
Output:
Operators:
In Java, operators are symbols that perform operations on operands. Operands can be variables, values, or expressions.
Types of Operators:
Operators |
Precedence |
Arithmetic |
*, /, %, +, - |
Unary |
expr ++, ++expr, --expr, expr--,~,! |
Shift |
>>, <<, >>> |
Relational |
<, >, <=, >=, !=, == |
Bitwise |
And (&), inclusive OR (^), Excusive Or (|) |
Logical |
Logical And (&&), Logical OR (||) |
Ternary |
?, : |
Assignment |
=, +=,-=,*=,/=,%=,etc. |
Arithmetic Operator:
arithmetic operators are used to perform mathematical operations on numeric data types, including addition(+), subtraction (-), Multiplication (*), division (/), modulo(%) operation.
TASK: Write a Java program to perform the following arithmetic operation.
|
Unary Operator:
A unary operator is an operator that operates on a single operand. This means it performs an operation with only one operand. Which includes postfix (a++)and prefix(++a) increment, postfix(a--) and prefix(--a) decrement, Logical Complement (!) and Bitwise Complement(~).
A=30; b=false
Operators |
Example |
A++ |
30++ à30; |
++A |
++30 à32; |
A-- |
30-- à32; |
--A |
--30 à30; |
! |
! b à true |
~ |
~30 à -29; |
TASK: Write a Java program to perform the following Unary operation.
a=18; b=16; a1=-10; b1=true;
|
Bitwise Operator:
Bitwise And (&):
The bitwise & operator always checks both conditions whether first condition is true or false.
If both condition are true it returns TRUE; Otherwise, it returns FALSE.
Example:
A=10; B=2;
C=A>B & B<A à true
C=A<B & B<A à false
Bitwise Or (|):
The bitwise | operator always evaluates both conditions, regardless of whether the first condition is true or false. If either condition is true, it returns TRUE; otherwise, it returns FALSE.
Example:
Num1=234 ; Num2=263
Num=Num1> Num2 | Num1 !=Num2 àtrue
Num= Num1 == Num2 | Num1 >= Num2 àfalse
TASK: Write a Java program to perform the following Bitwise operation.
Val1= 20; Val2=15
|
Logical Operator:
Logical And (&&):
The logical && operator doesn't check the second condition if the first condition is false. It checks the second condition only if the first one is true.If both condition are true it returns TRUE; Otherwise, it returns FALSE.
Example:
a=50;b=30
Out= (a>b && a==b) àFalse
Out= (a!= b && a>b) àTrue
Logical Or (||):
The logical || operator doesn't check the second condition if the first condition is true. It checks the second condition only if the first one is false. If either condition is true, it returns TRUE; otherwise, it returns FALSE.
Example:
a=50;b=30
Out= (a>b && a==b) àTrue
Out= (a!= b && a>b) àTrue
Out= (a==b && a<b) àFalse
TASK: Write a Java program to perform the following Logical operation.
Val1 = 80; Val2 = 40;
|
Assignment Operator:
An assignment operator is used to assign a value to a variable.
a=10;b=5;
Operator |
Example |
= |
C=a; |
+= |
a+=b àa=a+b |
-= |
b-=a; àb=b-a |
*= |
a*=a; àa=a*a; |
/= |
a/=b; à a=a/b; |
%= |
b%=a;àb=b%a; |
TASK: Write a Java program to perform the following Assignment operation.
x=10; y=5;
|
Relational Operator:
Relational operators are used to compare two values and determine the relationship between them. These operators return a boolean value (true or false) based on whether the comparison is true or false.
x=50; y=28
Operation |
Example |
Output |
== |
Z= x == x |
True |
!= |
Z= x!=x |
False |
< |
Z= x<y |
False |
> |
Z= x>y |
True |
>= |
Z= x>=x |
True |
<= |
Z= x<=y |
False |
TASK: Write a Java program to perform the following Relational operation.
num1=100; num2= 150
|
Ternary Operator:
The ternary operator (also known as the conditional operator) is a compact way to express a simple conditional expression. It's the only ternary operator in Java, and it takes three operands.
Syntax:
Boolean Expression ? value If True : value If False |
Example:
int x = 10; int y = (x > 5) ? 100 : 200; |
Output: 100
TASK:
int y = (x > 5) ? ((x < 15) ? 100 : 200) : 300;
Here's the expression breakdown:
|
Shift Operator:
In Java, shift operators are used to perform bit-level operations on integer data types (byte, short, int, long). These operators shift the bits of a value left or right. There are three types of shift operators:
Left Shift Operator (<<):
The left shift operator shifts all bits of a value to the left by a specified number of positions.
Syntax: value << num Positions
|
Example: int result = 5 << 2;
This will shift the binary representation of 5, which is 0000 0101, to the left by 2 positions, resulting in 0001 0100, which is 20 in decimal.
Right Shift Operator(>>):
The right shift operator shifts all bits of a value to the right by a specified number of positions.
Syntax: value >> num Positions
|
If the value is positive, the most significant bit (sign bit) is shifted in from the left. If the value is negative, the sign bit is extended as well.
Example: int result = 20 >> 2;
This will shift the binary representation of 20, which is 0001 0100, to the right by 2 positions, resulting in 0000 0101, which is 5 in decimal.
Unsigned Right Shift Operator:
The unsigned right shift operator shifts all bits of a value to the right by a specified number of positions. Unlike the right shift operator (>>), it fills the leftmost positions with zeros regardless of the sign bit.
Syntax: value >>> numPositions
|
Example: int result = -20 >>> 2;
This will shift the binary representation of -20, which is 1111 1111 1111 1111 1111 1111 1110 1100, to the right by 2 positions, resulting in 0011 1111 1111 1111 1111 1111 1111 1101, which is 1073741821 in decimal.
Control Statement:
Control Statement are used to manage the flow of execution in a program.
Decision Making:
Decision-making statements decide which statement to execute and when. Decision-making statements evaluate the Boolean expression and control the program flow depending upon the result of the condition provided. There are two types of decision-making statements in Java, i.e., If statement and switch statement.
If Statement : In java, there are four types of If statements.
if:
Syntax: if(condition) { statement 1; //executes when condition is true } |
Example:
Output:
else:
Syntax: if(condition) { statement 1; //executes when condition is true } else{ statement 2; //executes when condition is false } |
Example:
Output:
else if:
Syntax: if(condition 1) { statement 1; //executes when condition 1 is true } else if(condition 2) { statement 2; //executes when condition 2 is true } else { statement 2; //executes when all the conditions are false }
|
Example:
Output:
Nested if:
Syntax: if(condition 1) { statement 1; //executes when condition 1 is true if(condition 2) { statement 2; //executes when condition 2 is true } else{ statement 2; //executes when condition 2 is false } } |
Example:
Output:
TASK:
A: 90-100 B: 80-89 C: 70-79 D: 60-69 F: 0-59
Here are the rules:
Underweight: BMI less than 18.5 Normal weight: BMI 18.5 - 24.9 Overweight: BMI 25 - 29.9 Obesity: BMI 30 or greater
|
Switch:
A switch statement in Java evaluates an expression and executes different blocks of code based on the possible values of that expression. It provides a concise way to handle multiple conditional cases within a single control structure.
Syntax: switch (expression) { case value1: // Code block 1 break; case value2: // Code block 2 break; // More cases as needed default: // Default code block } |
The case variables can be int, short, byte, char, or enumeration. Cases cannot be duplicate.
The default clause is optional and executes when none of the case statements match the expression's value.
The break statement, also optional, exits the switch block once a condition is met, otherwise, the control flows to the next case.
It's crucial to ensure that the case expressions match the variable's type and are constant values.
Example:
Output:
TASK:
|
Loop Statement:
In Java, a loop statement is used to execute a block of code repeatedly. There are several types of loop statements available in Java:
for:
Syntax: for (initialization; condition; iteration) { // code to be executed } |
Example:
Output:
While:
Syntax: while (condition) { // code to be executed } |
Example:
Output:
Do-while:
Syntax: do { // code to be executed } while (condition); |
Example:
Output:
TASK:
|
Jump Statement:
Jump statements are used to transfer the control of the program to the specific statements. There are two types of Jump statements in Java.
break:
Syntax: break; |
Example:
Output:
Continue:
Syntax: continue; |
Example:
Output:
Array:
Array is a collection of similar data type. Arrays are used to store multiple values in a single variable.
The index of the first element is always 0, and the index of the last element is (length - 1).
There are two types of arrays in java: Single dimensional Array and Multi Dimensional Array.
Single Dimensional Array:
A single-dimensional array in Java is an array that stores elements of the same data type in a linear sequence. It is the simplest form of an array, where elements are arranged in a single row.
Syntax:
dataType[] arrayName = new dataType[size]; |
Example:
Output:
Multi Dimensional Array:
A multi-dimensional array in Java is an array of arrays. Unlike one-dimensional arrays which consist of a single line of elements, multi-dimensional arrays can represent data in multiple dimensions, such as rows and columns in a table or layers in a cube.
Output:
OOPS:
OOPS Stands for Object Oriented Programming Language.
OOPs in Java is a programming paradigm that revolves around the concept of "objects" which can contain data in the form of fields (attributes or properties) and code in the form of procedures (methods). The key principles of OOPs in Java are:
Class:
In Java, a class is a blueprint or template for creating objects. It defines the properties and behaviors (methods) that objects of that type will have. Each object created from a class is an instance of that class.
Syntax:
Class <Class Name>{
Field;
Method;
}
Object:
In Java, an object is a fundamental concept representing a tangible entity that exists in memory at runtime. It is an instance of a class, created using the new keyword followed by a constructor invocation. Objects encapsulate data (properties or fields) and behaviors (methods or functions) defined by their class.
Here's a brief explanation of objects in Java:
Instance: An object is an instance of a class. You can create multiple objects from the same class, and each object will have its own set of properties.
Properties: Objects have state, which is defined by the values of their instance variables or fields.
Behavior: Objects can perform actions or exhibit behaviors, which are defined by the methods or functions associated with their class.
Passing Objects: Objects can be passed as parameters to methods, returned from methods, stored in data structure, etc
Syntax:
public class ClassName{
Public static void main {
ClassName Obj=new ClassName();
}
}
Encapsulation:
This is the mechanism that binds together the data and functions that manipulate the data, and keeps both safe from outside interference and misuse. In Java, this is achieved using classes, where data (fields) and methods (functions) are encapsulated together. Encapsulation is achieved through access modifiers: public, private, and default, protected.
Public: The member is accessible from any other class.
Ex: Shirt, Destination.
Private: The member is accessible only within the same class.
Ex: ATM Pin, Mobile Password.
Default: The member is accessible only within the same package.
Ex: pet, pet name.
Inheritance:
Inheritance is a mechanism in which one object acquires all the properties and behaviors of a parent object. It promotes code reusability and allows the creation of hierarchical classifications. In Java, classes can inherit attributes and methods from other classes using the extends keyword.
Protected: The member is accessible within the same package and subclasses (even if they are in different packages).
Ex: Neighbours and Relativesà Job, SSLC Mark
In Java, There are Several type of Inheritance
Single Inheritance:( 1 Parent Class & 1 Child Class)
Single inheritance in Java refers to the capability of a class to inherit properties and behaviors from only one superclass, enabling a parent-child relationship where a subclass extends exactly one superclass.
|
|
Syntax:
Class Parents{ } Class Child extends Parents{ } |
Example:
Output:
Multi level Inheritance:
Multi-level inheritance in Java involves a chain of inheritance where a subclass extends another subclass, forming a hierarchical structure. This enables the sharing of properties and behaviors from multiple levels up the inheritance tree.
Parent A |
Intermediate B |
Child C |
Here, Intermediate B can access Parent A and Child C; also Child C can access Intermediate B; however, Child C can’t access Parent A.
Syntax:
class Parent{ //Methods and Fields } class Intermediate extends Parent{ //Methods and Fields } class Child extends Intermediate{ //Methods and Fields } |
Example:
Output:
Multiple Inheritance: ( 2 Parent Class and 1 Child Class)
In Java, multiple inheritance of classes is not supported to reduce complexity and to avoid issues such as the diamond problem. However, Java does support multiple inheritance of types through interfaces, where a class can implement multiple interfaces.
Parent A |
Parent B |
Child C |
What is Interface?
An interface in Java serves as a blueprint for a class, providing a way to achieve abstraction.
It consists of static constants and abstract methods, enabling multiple inheritance by allowing classes to implement multiple interfaces.
Interfaces can only contain abstract method decalrations and constant variables; they can’t have method implementations.
Why use Java Interface?
It is used to achieve abstraction.
By interface, we can support the functionality of multiple inheritance.
Syntax:
class Subclass extends Superclass { // subclass members and methods } |
Example:
Output:
Hierarchical Inheritance: ( 1 Parent Class and N number of Child Class)
Hierarchical inheritance in Java involves multiple Child Class inheriting from a single Parent Class, allowing each Chid Class to share common characteristics while also having its own unique properties and behaviours. This creates a hierarchical structure where Child Class form branches stemming from a common ancestor Parent Class.
|
Child B |
Child C |
Child N |
Syntax:
// Superclass class Parent Class { // Parent Class members }
// Child 1 class Child1 extends Parent Class { // Child 1 members }
// Child 2 class Child2 extends Parent Class { // Child 2 members }
// Additional Child Class can be defined similarly |
Example:
Output:
Hybrid Inheritance:
In Java, hybrid inheritance refers to a combination of two or more types of inheritance, such as single and multiple inheritance, multilevel and hierarchical inheritance, or single and multilevel inheritance.
Here's an example program demonstrating hybrid inheritance in Java by combining single and multilevel inheritance:
Example:
Output:
Polymorphism:
Polymorphism means "many forms" and refers to the ability of an object to take on multiple forms. In Java, polymorphism allows objects to be treated as instances of their parent class, enabling methods to be called on objects without knowing their exact type. This is achieved through method overriding and method overloading.
Method Overloading:
This occurs when a class has multiple methods with the same name but different parameter lists. Java determines which method to call based on the arguments provided at compile time.
Example:
Output:
Method Overriding:
This occurs when a subclass provides a specific implementation of a method that is already defined in its superclass. The method in the subclass has the same name, return type, and parameter list as the method in the superclass. At runtime, Java determines which version of the method to execute based on the actual type of the object.
Example:
Example:
Abstraction:
Abstraction is a process of hiding the implementation details and showing only functionality to the user.
Ex: SMS, Phone Call.
Abstract class:
A class is which declared with the abstract keyword is known as abstract class in java. It can have abstract and non abstract methods.
There are two Ways to achieve abstraction such as, Abstract and Interface.
An Abstract class must be declared with an abstract keyword.
Syntax:
abstract class A{} |
Abstract method: A method which is declared as abstract & doen not have Implementation is known as abstract method.
Example: abstract void Print(); // No method body & abstract.
Output:
Threads:
A thread is a lightweight process that enables a program to perform multiple tasks concurrently, allowing for more efficient use of resources and enabling parallel execution of code. Threads operate independently within a program, each with its own execution path, and can execute tasks simultaneously without interfering with each other or the main program's execution.
Another benefit of using thread is that if a thread gets an exception or an error at the time of its execution, it doesn't affect the execution of the other threads. All the threads share a common memory and have their own stack, local variables and program counter. When multiple threads are executed in parallel at the same time, this process is known as Multithreading.
New |
Runnable |
Runnable |
Terminated |
Non Runnable
|
New:When a thread is created, but the start() method hasn't been called yet, it's in the new state.
Runnable: Once the start() method is invoked, the thread becomes runnable. This means it's eligible to run, but the scheduler hasn't selected it to run yet.
Blocked: A thread transitions to the blocked state when it's waiting for a monitor lock. This happens when it's trying to enter a synchronized block or method, but another thread holds the lock.
Terminated: A thread enters the terminated state when its run() method exits or when it's terminated prematurely using methods like interrupt() or stop(). Once terminated, a thread cannot be restarted.
Methods in Thread:
start(): Starts the execution of the thread by calling its run() method.
run(): Contains the code that defines the behavior of the thread. This method needs to be overridden by subclasses of Thread or provided to the Thread constructor via a Runnable object.
sleep(long millis): Causes the currently executing thread to sleep (temporarily pause) for the specified number of milliseconds.
join(): Waits for the thread to complete its execution. If necessary, it can also specify a timeout.
interrupt(): Interrupts the thread, causing it to exit from a sleeping or waiting state, or to throw an InterruptedException if it's in an interruptible blocking method.
isAlive(): Checks whether the thread is still alive (i.e., has started but not yet terminated).
setName(String name): Sets the name of the thread.
getName(): Retrieves the name of the thread.
yield(): Causes the currently executing thread to yield execution to another thread of equal priority.
isInterrupted():Checks whether the thread has been interrupted.
setPriority(int priority): Sets the priority of the thread.
getPriority(): Retrieves the priority of the thread. |
Example:
Output:
Multi Threading:
Multithreading refers to the ability of a program to execute multiple threads concurrently within a single process.
Each thread represents a separate flow of control, allowing different parts of the program to perform tasks simultaneously.
Multithreading enhances efficiency by utilizing available resources more effectively and improving responsiveness, particularly in applications with parallelizable tasks such as handling multiple user requests or performing background processing.
Advantages:
It doesn't block the user because threads are independent and you can perform multiple operations at the same time.
You can perform many operations together, so it saves time.
Threads are independent, so it doesn't affect other threads if an exception occurs in a single thread.
Example:
Output:
Multitasking:
Multitasking in Java refers to the ability of a Java program to execute multiple tasks simultaneously. This is typically achieved using threads, where each thread represents a separate flow of control. Multitasking allows different parts of the program to run concurrently, improving performance, responsiveness, and resource utilization.
Example:
Output:
Multitasking can be achieved in two ways:
Process based Multitasking:
Each process has an address in memory. In other words, each process allocates a separate memory area.
A process is heavyweight.
Cost of communication between the process is high.
Switching from one process to another requires some time for saving and loading registers, memory maps, updating lists, etc.
Thread based Multitasking:
Threads share the same address space.
A thread is lightweight.
Cost of communication between the thread is low.
Method:
The method in Java or Methods of Java is a collection of statements that perform some specific task and return the result to the caller. A Java method can perform some specific task without returning anything. Java Methods allow us to reuse the code without retyping the code.
A method is like a function i.e. used to expose the behavior of an object.
It is a set of codes that perform a particular task.
Syntax:
[access_modifier] [return_type] methodName(parameter1_type parameter1_name, parameter2_type parameter2_name, ...) { // Method body // Code to perform the specific task // Optionally return a value using 'return' statement if return type is not void }
|
Access Modifier: public, private, protected, default.
Return type: void, int, double, float, long, short, byte.
public void Sample (int a, int b){
int c=a+b;
System.out.println(c);
}
Types of method Creation:
There are two type of method creation in java,
Instance methods are non-static methods that are associated with instances of the class. They can access instance variables and other instance methods directly.
Syntax: void methodName(){
//body
}
Output:
These methods are associated with the class rather than with any instance of the class. They can be called directly using the class name.
Syntax: static void methodname() {
//body
}
Output:
Constructor:
A constructor resembles a method in appearance, but it differs in function. It contains the code executed when you instantiate an object using the new keyword. In essence, it initializes the newly created object.
Types of Constructor:
Here are some familiar common types of constructions in Java.
Default Constructor:
A constructor without parameters is referred to as a default constructor. A default constructor is invisible.
Syntax:
public class ClassName { // Instance variables
// Constructor(s) public ClassName() { // Constructor body } } |
Example:
Output:
Parameterized Constructor:
A parameterized constructor is a constructor that accepts parameters when an object of a class is instantiated.
Syntax:
public class ClassName{ //body ClassName(Parameter Type Parameter){ //body } } |
Example:
Output:
Copy Constructor:
A copy constructor in Java is a constructor that creates a new object by copying the state of an existing object of the same class, typically used to clone objects with distinct memory addresses while maintaining identical values.
Syntax:
Public class ClassName { //body ClassName(Parameter type, Parameter){ //body } ClassName(ClassName object){ //body } } |
Example:
Output:
Final:
In Java, the final keyword is used to define entities that cannot be changed. It can be applied to variables, methods, and classes, each with its own implications:
Final Variable:
When applied to a variable, it means that once initialized, the value of that variable cannot be changed.
Example:
Output:
Final Method:
Super:
In Java, the super keyword is used to refer to the immediate parent class of a subclass. It can be used to access methods, variables, and constructors of the superclass within the subclass. Here are two lines explaining its usage:
Output:
This:
In Java, the this keyword refers to the current instance of the class in which it is used, allowing access to instance variables and methods within the class scope. It is commonly used to disambiguate between instance variables and parameters or to call another constructor within the same class.
Output:
Exception Handling:
Exception handling in Java is a mechanism to gracefully manage runtime errors or exceptional situations by enclosing risky code within a try-catch block to prevent program crashes and maintain application stability.
printStackTrace():
The printStackTrace() method in Java is a utility used for handling exceptions and errors. It displays the stack trace, including the error line number and class name, aiding in debugging
Types of Exception Handling:
Checked Exception:
Checked exceptions in Java are exceptions that must be either caught or declared in the method signature using the throws keyword. They are checked at compile-time.
In Java, checked exceptions are divided into several categories, including but not limited to:
IOException:
This category includes exceptions related to input-output operations, such as FileNotFoundException, IOException, EOFException, etc.
FileNotFoundException:
In this example, we're trying to read from a file (example.txt). However, if the file doesn't exist, a FileNotFoundException is thrown, which is a checked exception. We handle it using a try-catch block to catch the exception and handle it gracefully.
Output:
ClassNotFoundException:
In this example, Class.forName("NonExistentClass") tries to load a class named "NonExistentClass", which does not exist. This results in a ClassNotFoundException being thrown. We catch this exception and handle it by printing an error message.
Output:
Unchecked Exception:
Unchecked exceptions, also known as runtime exceptions, are exceptions that occur during program execution and are not required to be handled explicitly by the compiler, typically representing errors or conditions beyond the program's control.
In Java, some common types of unchecked exceptions include NullPointerException, ArrayIndexOutOfBoundsException, ArithmeticException, NumberFormatException, and NullPointerException, among others. These exceptions occur at runtime and typically indicate errors in the program logic or unexpected conditions during execution.
ArithmeticException:
This Java program attempts to divide an integer by zero within a try block. If an ArithmeticException occurs (due to division by zero), it catches the exception, prints a message indicating the error ("Divided By Zero"), and displays the stack trace of the exception.
Output:
NumberFormatException:
This Java program attempts to convert a string, "Hello", into an integer using the parseInt method. Since "Hello" cannot be converted into a valid integer, it throws a NumberFormatException.
Output:
ArrayIndexOutOfBoundsException:
Output:
NullPointerException:
Output:
Memory Management in Java:
Memory management in Java refers to the process by which Java manages memory allocation and deallocation for objects created during program execution. Here are some key aspects of memory management in Java:
Stack:
Stack memory primarily stores primitive values and references to object.
It is used to storing method calls, local variables, and reference variables.
Each thread in a Java program has its own stack memory. It operates in a Last-In-First-Out (LIFO) manner, meaning the most recently called method is the first one to finish and be removed from the stack. Stack memory is generally faster to access but limited in size compared to the heap memory.
Heap:
Heap memory is used for storing objects.
When you create an object using the new keyword, memory is allocated from the heap to store that object.
Heap memory is dynamic, meaning it can grow or shrink as needed during the execution of the program. The Java garbage collector manages heap memory by automatically deallocating memory for objects that are no longer in use, freeing up space for new objects.
Code |
Stack |
Heap |
int x=10; int y=a; |
x=10 y=10 |
|
int[] a; a=new int[3]; int[] b=a; |
a b |
[0,0,0] |
Garbage Collection:
Garbage collection in Java is an automatic process performed by the JVM (Java Virtual Machine) to identify and remove unreferenced objects from memory. This helps manage memory efficiently by freeing up space for new allocations, eliminating the need for manual memory management and reducing the risk of memory leaks.
Here some of the unreferenced objects,
By Nulling the reference:
Nulling a reference in Java means setting a reference variable to null, indicating it no longer points to any object. This action allows unreferenced objects to become eligible for garbage collection.
By Assigning a Reference to another:
In Java, when you assign a reference variable to another, you're essentially making both variables point to the same object in memory. However, when it comes to garbage collection, what matters is the number of references to an object. If an object has no references pointing to it, it becomes eligible for garbage collection.
Ref obj1=new Ref(); Ref obj2=new Ref(); obj1=obj2; //now the first object referred by e1 is available for garbage collection . |
Example:
By anonymous object
In Java, an anonymous object refers to an object that is instantiated without assigning it to a reference variable.
Difference between Stack and Heap memory management:
Stack |
Heap |
Stack Memory is used for Static Memory Allocation |
Heap Memory is used for Dynamic Memory Allocation. |
It stores method frames, local variables and reference variables. |
It stores objects and instance variables. |
Memory Allocation and Deallocation are handled automatically by the JVM. |
Memory allocation and deallocation are managed explicitly by the programmer using the new and delete Operators. |
Each thread in a java application has its own stack memory. |
Heap memory is shared among all threads in a Java application. |
Stack Memory is efficient and has a limited size. |
Heap memory is larger and can grow dynamically based on application requirements. |
It is used for short lived data and method invocation. |
It is used for long lived data and objects. |
String:
In java, String is an object that is used for storing characters or text surrounded by double quotes.
Strings are immutable. immutability means the property of an object that once it is created, its state cannot be changed.
There are two ways to create a string object in java;
String Literal:
In Java, a string literal refers to a sequence of characters enclosed within double quotes(“ “). It represents a constant value that is assigned to a variable of type String. String literals are commonly used to initialize String objects or as arguments in method calls that expect String parameters.
Example:
By using new Keyword:
In Java, the new keyword is used to instantiate objects. When creating a new object using the new keyword with the String class, you're essentially creating a new instance of the String class.
String Methods:
In Java, there are numerous string methods available to manipulate strings. Here are some of the commonly used ones:
Concatenation:
Combining two or more strings together. This can be done using the + operator or the concat() method.
Example:
Output:
length ():
Getting the length of a string, i.e., the number of characters in the string. This is done using the length() method.
Example:
Output:
Sub String:
Extracting a portion of a string. This can be achieved using the substring() method.
Example:
Output:
charAt():
The charAt() method in Java is used to retrieve the character at a specified index within a string. The indexing of characters starts from 0, meaning the first character of the string has an index of 0, the second character has an index of 1, and so on.
Example:
Output:
Conversion:
Converting a string to upper case or lower case. This can be done using methods like toUpperCase() and toLowerCase().
toUpperCase:
It is used to convert all the characters in a string to uppercase.
This method does not modify the original string; instead, it returns a new string with all characters converted to uppercase.
Example:
Output:
toLowerCase():
It is used to convert all the characters in a string to Lower Case.
This method does not modify the original string; instead, it returns a new string with all characters converted to Lower Case.
Example:
Output:
replace():
Replacing characters or substrings within a string. This can be done using methods like replace().
Example:
Output:
Searching:
Finding occurrences of characters or substrings within a string. This can be done using methods like indexOf() and contains().
indexOf():
The indexOf() method in Java is a part of the String class. It is used to find the index of the first occurrence of a specified substring within the string. If the substring is found, indexOf() returns the index of its first occurrence; otherwise, it returns -1.
Example:
Output:
Contains():
The contains() method in Java is a part of the String class. It is used to check whether a specified substring is present within the string. It returns true if the substring is found within the string, and false otherwise.
Example:
Output:
StringBuffer:
StringBuffer is a class in Java that represents a mutable sequence of characters. It provides an alternative to the immutable String class, allowing you to modify the contents of a string without creating a new object every time.
Methods of StringBuffer:
Here are some of the StringBuffer methods.
append():
append() is a method in Java used to add characters or sequences of characters to the end of an existing StringBuffer.
It modifies the original object by concatenating the provided data at the end.
Example:
Output:
Insert():
insert() is a method in Java used to insert characters or sequences of characters into an existing StringBuffer or StringBuilder object at a specified position.
It modifies the original object by inserting the provided data at the specified index.sert method is java is used to insert character or sequence of character into anStringBuffer.
Example:
Output():
Delete():
The delete() method of the StringBuffer class deletes the string from the specified beginIndex to endIndex-1.
Example:
Output:
replace():
replace() is a method in Java used to replace characters or substrings within an existing StringBuffer or StringBuilder object. It allows you to specify the start and end indices of the substring to be replaced, along with the replacement string.
Example:
Output:
reverse():
The reverse() method of the StringBuilder can reverse the current String.
Example:
Output:
StringBuilder:
Introduced in Java 5, StringBuilder is similar to StringBuffer but lacks synchronization.
StringBuilder in Java is also a mutable sequence of characters, like StringBuffer, but it's not thread-safe.
This lack of synchronization overhead makes StringBuilder faster than StringBuffer.
It provides similar methods for appending, inserting, deleting, replacing, and reversing characters within the string.
StringBuilder is typically used in single-threaded environments or when synchronization is managed externally, offering better performance compared to StringBuffer.
append():
Example:
Output:
delete():
Example:
Output:
insert():
Example:
Output:
replace():
Example:
Output:
reverse():
Example:
Output:
Difference BetweenStringBuffer and StringBuilder:
Feature |
StringBuffer |
StringBuilder |
Introduced |
Since Java 1.0. |
Since Java5. |
Thread Safety |
Synchronized (Thread-safe). |
Not Synchronized (Not thread- safe). |
Performance |
Slower due to synchronization. |
Faster due to lack of synchronization. |
Usage |
Recommenden in multithreaded environments. |
Recommended in single threaded Enviornments. |
Methods |
All methods are Synchronized. |
All methods are not Synchronized. |
File Handling:
File handling in Java involves performing various operations on files and directories, such as creating, reading, writing, deleting, and manipulating them.
This is achieved using classes and methods provided by the java.io and java.nio.file packages.
These classes allow Java programs to interact with files and directories on the file system, enabling tasks such as reading data from files, writing data to files, managing file metadata, and performing file system operations.
Read File:
Reading a file in Java involves retrieving data stored within a file on the file system.
Write File:
Writing a file in Java involves creating, opening, and writing data to a file on the file system.
Serialization:
Serialization in Java refers to the process of converting an object into a byte stream, which can be easily saved to a file or sent over a network. This byte stream can later be reconstructed to get back the original object. It's commonly used for persisting object. It's commonly used for persisting object states or for transmitting objects across a network.
Deserialization:
Deserialization is the process of reconstructing an object from its serialized form, which is typically a byte stream. In Java, deserialization is the reverse process of serialization. It involves reading the byte stream from a file, network, or any other source, and converting it back into an object.
Output:
GUI:
GUI stands for Graphical user Interface. A GUI allows user to interact with a program using graphical elements such as, windows, buttons, textfields and other graphical components.
Java, one of the most popular programming languages in the world, provides several libraries for GUI development. GUI Libraries includes, AWT (Abstract Window Toolkit), Swing, JavaFX.
AWT:
The Abstract Window Toolkit (AWT) was introduced as part of Java's standard library in its early days and was the first GUI library for Java. AWT provides a set of basic components and widgets, such as buttons, labels, text fields, and more, that developers can use to create simple GUI interfaces.
Here, Some key concepts and components in AWT,
Button:
A button in Java GUI is a clickable component allowing user interaction. It triggers actions when clicked, commonly represented by Button in AWT.
It has a label (text) that is displayed on the button.
Example:
Output:
Frame:
In AWT (Abstract Window Toolkit) Java, a frame is a top-level window with a title and a border. It serves as the container for other components, such as buttons, text fields, etc., allowing users to interact with them. Frames can be resized, minimized, maximized, and closed by the user. They form the backbone of graphical user interfaces (GUIs) in Java applications.
Example:
Output:
Label:
In Java AWT (Abstract Window Toolkit), a label is a component used to display a single line of read-only text or an image.
It is typically used to provide descriptive text or visual cues in graphical user interfaces (GUIs).
Labels can be added to frames, panels, or other containers to provide information to the user or to enhance the user interface.
They are created using the Label class and can be customized with fonts, colors, and alignment settings.
Example:
Output:
TextField:
In Java AWT (Abstract Window Toolkit), a TextField is a GUI component used for accepting user input of a single line of text.
It provides a text editing area where users can type alphanumeric characters, symbols, or other text input.
TextFields are commonly used in graphical user interfaces (GUIs) for forms, search boxes, login screens, and other areas where user input is required.
TextFields in Java AWT are represented by the TextField class.
Example:
Output:
TextArea:
In Java AWT, TextArea is a component for inputting and displaying multiline text, commonly used in GUIs for tasks like document editing or displaying logs.
Example:
Output:
Layout:
A layout in Java GUI programming specifies how components are organized within a container, determining their position and size relative to each other. Layouts manage the spatial arrangement of components to achieve desired user interface designs.
GridLayout:
GridLayout in Java GUI AWT arranges components in a grid of rows and columns, where each component occupies one cell. Components are added in left-to-right, top-to-bottom order within the grid.
Example:
Output:
GridBagLayout:
GridBagLayout is a layout manager in Java used to arrange components in a grid-like manner. It allows you to create flexible and complex layouts by specifying constraints for each component.
Example:
Output:
FlowLayout:
FlowLayout arranges the components in a container like the words on a page.It fills the top line from left to right and top to bottom.
Example:
Output:
Event Handling & Listener:
An event listener is an object that listens for and responds to events generated by GUI components. In Java AWT, event listeners are interfaces that define methods for handling specific types of events. Components can have multiple event listeners attached to them, each responsible for handling a different type of event.
Event Class |
Event Listener |
Action Event |
Action Listener |
Mouse Event |
Mouse Listener |
Key Event |
Key Listener |
Item Event |
Item Listener |
Adjustment Event |
Adjustment Listener |
Text Event |
Text Listener |
Window Event |
Window Listener |
Component Event |
Component Listener |
Container Event |
Container Listener |
Action Listener:
The ActionListener interface is commonly used to handle action events, such as button clicks. To handle button clicks, you would implement the ActionListener interface and override its actionPerformed() method, which gets called when the associated button is clicked.
Example:
Output:
Key Listener:
In Java AWT (Abstract Window Toolkit), a KeyListener interface is used to handle keyboard events. It provides methods to handle the key being pressed, released, or typed.
Example:
Output:
Mouse Listener:
In Java AWT (Abstract Window Toolkit), a MouseListener interface is used to handle mouse events such as mouse clicks, mouse movements, and mouse button releases. This interface is part of the java.awt.event package.
The MouseListener interface declares five methods:
Example:
Output:
MouseMotion Listener:
In Java AWT and Swing, the MouseMotionListener interface is used to handle mouse motion events, such as mouse movement and mouse dragging (when a mouse button is pressed and moved). This interface is part of the java.awt.event package.
The MouseMotionListener interface declares two methods:
Swing:
In Java, Swing is a GUI (Graphical User Interface) toolkit and framework for building graphical user interfaces. It provides a set of components, such as buttons, text fields, labels, etc., and layout managers to help you create user-friendly interfaces for your Java applications.
This swing brings in all the classes and interfaces from the javax.swing package, allowing you to use Swing components like JFrame, JButton, JPanel, JTextField, etc., in your Java code.
Output:
When you click the "Submit" button in the GUI form created by the program, it triggers an action event. In response to this action event, the actionPerformed method is called.
Within the actionPerformed method, the program prints out the text entered into the text fields for "First Name", "Last Name", and "Age". Therefore, clicking the "Submit" button indeed displays the values entered into these fields on the console or output window.
Console Window Output:
Feature |
AWT |
Swing |
Platform dependency |
platform dependent |
Platform independent |
Component Customization |
Limited customization Options |
Extensive customization options |
Performance |
Less efficient due to platform dependence |
More efficient due to lightweight nature. |
Components |
Heavy Weighted components |
Light Weighted components |
Package |
import java.awt.* |
import javax.swing.* |
Look and feel |
Native Look and Feel |
Pluggable Look and Feel |
Memory Usage |
Occupies more memory space |
Occupies less memory space |
Java Networking:
Java networking refers to the capability of the Java programming language to facilitate communication and data exchange between different computing devices over a network.
It provides classes and APIs (Application Programming Interfaces) for creating network-aware applications, including functionalities for establishing connections, transmitting data, handling protocols such as TCP/IP and UDP, and managing network resources.
Java networking enables developers to build client-server applications, including functionalities for establishing connections, transmitting data, handling protocols such as TCP/IP and UDP, and managing network resources. Java networking enables developers to build client-server applications, web services, and distributed systems effectively.
Networking Types:
LAN |
MAN |
WAN |
LAN stands for Local Area Network |
MAN stands for Metropolitan Area Network |
WAN stands forWide Area Network |
It covers Small Geographical area such as single building, campus or office |
It covers larger geographical area such as city or metropolitan region. |
WAN extends over a wide geographical area, often spanning across cities, countries, or continents. |
LANs usually have a limited number of devices connected together, often within the same physical location. |
MANs connect multiple LANs together, allowing communication between devices across different locations within the same city. |
WANs connect multiple LANs, MANs, and other networks over long distances, often using telecommunication technologies. |
LAN typically offers higher speeds and bandwidth compared to MAN and WAN. |
MAN generally offers lower speeds compared to LAN but higher speeds compared to WAN, as it covers a larger geographical area. |
WAN may have lower speeds and higher latency compared to LAN and MAN. |
LANs are often owned and controlled by single organization. |
MANs may involve collaboration between multiple organizations or be owned by a single entity. |
WANs typically involve connections between multiple organizations, service providers, and geographic regions. |
Less Expensive compare to MAN and WAN |
It require more investment in infrastructure and coordinate between organizations. |
More Expensive compare to LAN and MAN. |
Network Protocols:
TCP:
TCP stands for Transmission control protocol. It provides reliable communication between the sender and receiver.
TCP is used along with the internet protocol referred as TCP/IP.
UDP:
UDP stands for User Datagram protocol provides a connectionless protocol service by allowing packet of data to be transferred along two or more nodes.
Networking Terminology:
Client Server Communication:
Client:
The client application creates a socket object, specifying the server’s IP address, port number, to connect the server.
Once the connection is established, the client can use input and output streams (InputStream and OutputStream) obtained from the Socket to send and receive data to/from the server.
Server:
The server application creates a ServerSocket object, which listens for incoming client connections on a specific port.
Once a client connection request is received, the server accepts the connection and creates a Socket object to communicate with the client.
The server can then use input and output streams (InputStream and OutputStream) obtained from the Socket to send and receive data to/from the client.
Example:
Output:
URL:
In Java, the URL class is used to represent a Uniform Resource Locator, which is a pointer to a resource on the World Wide Web. The URL class provides methods for accessing the various components of a URL, such as the protocol, host, port, path, query parameters, and more.
Creating URL object:
URL url=new URL(“https://www.Example.com//path/to/resource?param1=value1¶m2=value2"); |
URL Components:
Components |
Definition |
getProtocol() |
Returns the Protocol of the URL(https) |
getHost() |
Returns the Host of the URL(www.Example.com) |
getPort() |
Returns the Port of the URL(-1) |
getPath() |
Returns the Path of the URL(path/to/resource) |
getQuery() |
Returns the Query of the URL(param1=value1¶m2=value2) |
Example:
Output:
JDBC:
JDBC stands for Java Database Connectivity. It is a Java API that allows java program to interact with Database. JDBC provides a standard interface for accessing relational databases, enabling Java applications to perform various database operations such as querying, updating, inserting, and deleting data.
JDBC API uses JDBC Drivers to connect with the database. Here are 5 steps to connect JDBC to a database.
In Java, to use JDBC to connect to a database, need to import classes from the java.sql package.
Register the Driver Class:
The forName() method of class is used to register the driver class.
This method is used to dynamically load the driver class.
Syntax:
Class.forName();
Create the Connection object:
The getConnection() method of Driver manager class is used to establish communication with the database.
Syntax:
Connection connection=DriverManager.getConnection(url,username,password);
Create Statement:
The CreateStatement() method of connection interface is used to create statement.
The object of statement is responsible to execute queries with the database.
Syntax:
Statement statement=connection.CreateStatement();
Execute Query:
The ExecuteQuery() method of statement interface is used to execute queries to the database.
This method returns the object of resultset that can be used to get all the records of a table.
ResultSet resultSet=statement.getQuery(query);
Close the Connection:
By closing connection object statement and resultset will be closed automatically.
The close() method of connection interface is used to close the connection.
Syntax:
Connection.close();
resultSet.close();
"Before JDBC code execution, establishing a connection to the database is necessary for communication and executing SQL operations, facilitated by JDBC API's interfaces and classes." |
Steps to Connect Java to Database:
Open IntelliJàFileàProject Structureàchoose Javaàadd MySQL Connector/J.
SQL Code:
Java Code:
Output:
Update:
The SQL UPDATE statement is used to modify existing records in a database table.
Output:
Delete:
The SQL Delete statement is used to delete records in a database table.
Output:
Insert:
The SQL Insert statement is used to ADD records in a table.
Output: