Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
10 views

Java

Java is a widely used, object-oriented programming language. It was developed by James Gosling in 1995 and is now owned by Oracle. Java can be used to create a variety of applications including mobile apps, desktop apps, web apps, and more. It is platform independent, meaning code written in Java can run on any system that supports Java without needing to be recompiled. To write a Java program, you define a class with a main method, write code within the class, and use print statements or return values to output results. Common Java constructs include variables, data types, operators, conditionals, loops, arrays, and methods.

Uploaded by

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

Java

Java is a widely used, object-oriented programming language. It was developed by James Gosling in 1995 and is now owned by Oracle. Java can be used to create a variety of applications including mobile apps, desktop apps, web apps, and more. It is platform independent, meaning code written in Java can run on any system that supports Java without needing to be recompiled. To write a Java program, you define a class with a main method, write code within the class, and use print statements or return values to output results. Common Java constructs include variables, data types, operators, conditionals, loops, arrays, and methods.

Uploaded by

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

JAVA

Introduction:

-> Java is a High Level Programming language created in 1995.


-> It is owned by oracle, more than 3 billion devices run Java.
-> It is used for Mobile Applications, Desktop Applications, Web Applications,
Web Servers and Application Servers, Games, Database Connection, etc.
-> Java works on different platforms like Windows, Mac, Linux, Raspberry Pi,
etc, so it is called platform independent.
-> It is Open source and free, simple, secure, fast, object oriented language
which gives a clear structure to programs and allows code to be reused,
lowering development costs.
-> C is procedural oriented language whereas c++ and java are object
oriented language and c, c++ are platform dependent and java is platform
independent.
-> Java was Developed by James Gosling.
-> Java is case sensitive.

Java Installation:

-> First download java from oracle.com.


-> Then Run java jdk and install normal steps after that go to environment
variables > System Variables. Click on “New” button and then type
“JAVA_HOME” in Variable Name and location of jdk file where it is installed
i.e., “C:\Progrtam Files\Java\jdk\bin” in Variable Value.Then go to command
prompt and type java -version and javac.

Java Syntax:

MyProgram.java (filename)

public class MyProgram {


public static void main(String[] args) {
System.out.println("Hello World");

-> public class classname(MyProgram).


-> For classname it should b like “MyProgram” I.e., all first letters of the words
should be uppercase and for methods first letter should be lower case and
remaining all are upper case example “myData”.
-> Every line of code that runs in Java must be inside a class.
-> Every program must contain the main() method.
-> Inside the main() method, we can use the println() method to print a line of
text to the screen:

public static void main(String[ ] args) {


System.out.println("Hello World");
}

Java Comments:

-> Single-line comments start with two forward slashes (//).


-> Multi-line comments start with /* and ends with */.

Java Variables:

-> Variables are containers for storing data values.

type variableName =value;

int a=20;
String name=“kiran”;

-> print variables.

int a=1100;
System.out.println(a);

String name=“varun”;
System.out.println(“Hello”+name);

-> Declare Many Variables.

int x=5;
int y=10;
int z=15;
System.out.println(x+y+z);

Or
int x=5, y=10, z=15;
System.out.println(x+y+z);

-> Java Identifiers:

All Java variables must be identified with unique names.

These unique names are called identifiers.


int minutesPerHour=60;

and

int m=60;

Suppose m is a variable we don’t know the meaning of that in that case we


are using name as minutesPerHour then clearly we understand the meaning
of that variable which is having a unique name called identifiers.

Java Data Types:

Data Types are divided into two groups,

Primitive Data Types - byte, short, int, long, float, double, boolean, char.

Non-Primitive Data Types - String, Arrays and classes.

Primitive Data Types:

1) Byte (1 byte)
2) Short (2 bytes)
3) Int (4 bytes)
4) Long (8 bytes)
5) Float (4 bytes)
6) Double (8 bytes)
7) Boolean (1 bit)
8) Char (2 bytes)

1 byte=8 bits

Numbers:

Integer Types - stores whole numbers, positive or negative without decimals


(byte, short, int and long).

Floating Types - numbers with a fractional part containing one or more


decimals (float and double).

For float we use 0.05f but output should be 0.05. and for double 19.99d output
is 19.99.

Boolean Types - declared with boolean keyword and can only takes the
values True or False.

Java Characters - char data type is used to store a single character like a or c
surrounded by single quotes.

Non Primitive Data Types:


-> Primitive types are predefined (already defined) in Java. Non-primitive
types are created by the programmer and is not defined by Java (except for
String).
-> A primitive type has always a value, while non-primitive types can be null.
-> A primitive type starts with a lowercase letter, while non-primitive types
starts with an uppercase letter.
-> Non Primitive types are arrays, strings, classes will see later.

Java Type Casting:

Type casting means converting one data type to another data type.

Widening casting - converting smaller type to a larger type.

byte -> short -> char -> int -> long -> float -> double

Narrowing Casting - converting a larger type to a smaller type.

Java Operators:

Operators are used to perform operations on variables and values.

Arithmetic Operators:

Addition (+)
Subtraction(-)
Multiplication(*)
Division(/)
Modulus(%)
Increment(++)
Decrement(--)

Assignment Operators:

=, +=, -=, *=, /=, %=, &=, |=, ^=, >>=, <<=

Comparison Operators:

==, !=, <, >, <=, >=

Logical Operators:

Logical and (&&), Logical Or (||), Logical Not (!)

Java Strings:

String is a group of characters surrounded by double quotes.

String greeting = “Hello”;


String Length:

Length of a string can be found with the length() method.

String txt=“nfheggfvnjkhngbjhg”;
System.out.println(txt.length());

Output - 18

More String Methods:

-> toUpperCase(), toLowerCase()

String txt= “Hello”


System.out.println(txt.toUpperCase()); // Output-HELLO
System.out.println(txt.toLowerCase()); // Output-hello

-> Finding a character in a string (indexOf())

String txt= “okdhui”


System.out.println(txt.indexOf(“d”));

String Concatenation:

Combining of two strings with “++ operator is called Concatenation.

String FName=“John”;
String LName=“Doee”;
System.out.println(FName+“ ”+LName); // John Doee

-> Java uses + operator for both addition and concatenation, numbers are
added, strings are concatenated.

int x=10;
int y=15;
int z=x+y; // z=25

String x= “10”;
String y= “15”;
String z=x+y; // 1015

int x=10;
String y= “15”;
String z=x+y; // z=1015

Java Math:

Java Math has many methods,

Math.max(x,y):
Math.max(5,10); //10

Math.min(x,y):

Math.min(5,10); //5

Math.sqrt(x):

Math.sqrt(64); //8

Math.abs(x):

Math.abs(-4.7); //4.7

Random Numbers:

Math.random(); // every time numbers are generated randomly.

Java Booleans:

Only Data type having one of two values.

-> Yes/No
-> True/False
-> On/Off

int x=10;
int y=9;
System.out.println(x>y); // True

Java If … Else:

The IF Statement -

Use the if statement to specify a block of Java code to be executed if a


condition is true.

Syntax:

if (condition) {
// block of code to be executed if the condition is true
}

The else Statement -

Use the else statement to specify a block of code to be executed if the


condition is false.
Syntax:

if (condition) {
// block of code to be executed if the condition is true
}
else {
// block of code to be executed if the condition is false
}

The else if Statement -

Use the else if statement to specify a new condition if the first condition is
false.

if (condition1) {
// block of code to be executed if condition1 is true
}
else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
}
else {
// block of code to be executed if the condition1 is false and condition2 is
false
}

Java Switch:

Use the switch statement to select one of many code blocks to be executed.

switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block}

int day = 4;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
}
// Outputs "Thursday" (day 4)

-> The switch expression is evaluated once.


-> The value of the expression is compared with the values of each case.
-> When Java reaches a break keyword, it breaks out of the switch block.
-> The default keyword specifies some code to run if there is no case match.

Java While Loop:

The while loop loops through a block of code as long as a specified condition
is true.

While(condition) {
//code
}

Do While Loop-

The do/while loop is a variant of the while loop. This loop will execute the
code block once, before checking if the condition is true, then it will repeat the
loop as long as the condition is true.

do{
//code
}
While(condition);

Java For Loop:

When you know exactly how many times you want to loop through a block of
code, use the for loop instead of a while loop.

for(stat1; stat2; stat3){


//code
}

Java Break and Continue:

-> The break statement can also be used to jump out of a loop.
-> The continue statement breaks one iteration (in the loop), if a specified
condition occurs, and continues with the next iteration in the loop.

Java Arrays:

Arrays are used to store multiple values in a single variable, instead of


declaring separate variables for each value.

String[ ] cars = {"Volvo", "BMW", "Ford", "Mazda"};

int[] myNum = {10, 20, 30, 40};

Access the elements of an array -

String[ ] cars = {"Volvo", "BMW", "Ford", "Mazda"};


System.out.println(cars[0]); // Outputs Volvo

Java Arrays Loop -

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};


for (int i = 0; i < cars.length; i++) {
System.out.println(cars[i]);
}

Multidimensional arrays -

int[ ] [ ] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };

Java Methods:

-> A method is a block of code which only runs when it is called.

-> You can pass data, known as parameters, into a method.

-> Methods are used to perform certain actions, and they are also known as
functions.

Create A method:
-> A Method must be declared within a class, it is defined with the name of the
method, followed by parentheses().

public class Main{

static void myMethod() {

//code

-> call a method in java,

public class Main{

static void myMethod() {

System.out.println(“nfjhejv”);

Public static void main(String[ ] args) {

myMethod();

Java Method Parameters and Arguments -

Here, myMethod takes a string called fname as parameter.

public class Main {


static void myMethod(String fname) {
System.out.println(fname + " Refsnes");
}

public static void main(String[] args) {


myMethod("Liam");
myMethod("Jenny");
myMethod("Anja");
}}
// Liam Refsnes
// Jenny Refsnes
// Anja Refsnes

Method Overloading -

Multiple Methods can have the same name with different parameters.

int myMethod(int x)
float myMethod(float x)
double myMethod(double x, double y)

Java Scope -

In Java, variables are only accessible inside the region they are created. This
is called scope.

public class Main {


public static void main(String[] args) {

// Code here CANNOT use x

int x = 100;

// Code here can use x


System.out.println(x);
}}

Java Recursion -

Recursion is the technique of making a function call itself.

This technique provides a way to break complicated problems down into


simple problems which are easier to solve.

Use Recursion to add all of the numbers up to 10.

public class Main {


public static void main(String[] args) {
int result = sum(10);
System.out.println(result);
}
public static int sum(int k) {
if (k > 0) {
return k + sum(k - 1);
} else {
return 0;
}
}}

// output - 55

Java Classes:

Java OOP-

OOP stands for Object Oriented Programming.

Procedural programming is about writing procedures or methods that perform


operations on the data, while object-oriented programming is about creating
objects that contain both data and methods.

What are Classes and Objects -

Fruit is a class and Apple, Banana, Mango are Objects.

Car is a class and Volvo, Audi, Toyota are Objects.

So, a class is a template for objects and Object is an instance of a class.

Everything in Java is associated with classes and objects, along with its
attributes and methods. 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.

public class Main{

Int x=5;

Here class is Main we call it as class name.


Create an object-

In Java, an object is created from a class. We have already created the class
named Main, so now we can use this to create objects.

To create an object of Main, specify the class name, followed by the object
name, and use the keyword new.

public class Main {


int x = 5;

public static void main(String[] args) {


Main myObj = new Main();
System.out.println(myObj.x);
}}

Java Class Attributes -

class attributes are variables within a class.

public class Main{

Int x=5;

Int y =10;

Here x and y are attributes of Main Class.

-> Accessing the attributes by creating an object of the class and by using the
dot syntax(.)

Create an object called "myObj" and print the value of x:

public class Main {


int x = 5;

public static void main(String[] args) {


Main myObj = new Main();
System.out.println(myObj.x);
}
}
-> Modify atributes using dot syntax,

Set the value of x to 40:

public class Main {


int x;

public static void main(String[] args) {


Main myObj = new Main();
myObj.x = 40;
System.out.println(myObj.x);
}
}

-> Override the existing values,

Change the value of x to 25:

public class Main {


int x = 10;

public static void main(String[] args) {


Main myObj = new Main();
myObj.x = 25; // x is now 25
System.out.println(myObj.x);
}}

Java Class Methods -

public class MyProgram{

static void myMethod() {

System.out.println(“Hello”);

public static void main(String[ ] args) {

myMethod();

}
}

Java Constructors-

The constructor is called when an object of a class is created. It can be used


to set initial values for object attributes

// Create a Main class


public class Main {
int x; // Create a class attribute

// Create a class constructor for the Main class


public Main() {
x = 5; // Set the initial value for the class attribute x
}

public static void main(String[] args) {


Main myObj = new Main(); // Create an object of class Main (This will call
the constructor)
System.out.println(myObj.x); // Print the value of x
}}
// Outputs 5

Java Modifiers -

Public keyword is an access modifier.

 Access Modifiers - controls the access level


 Non-Access Modifiers - do not control access level, but provides
other functionality

-> Access Modifiers are public and default, for classes you can use either
public or default.

-> For attributes, methods and constructors you can use public, private,
default, protected.

-> Non Access Modifiers are final and abstract, for classes.

-> For attributes, methods use final,static, abstract, transient, synchronized,


volatile.

Final-
If you don't want the ability to override existing attribute values, declare
attributes as final.

public class Main {


final int x = 10;
final double PI = 3.14;

public static void main(String[] args) {


Main myObj = new Main();
myObj.x = 50; // will generate an error: cannot assign a value to a final
variable
myObj.PI = 25; // will generate an error: cannot assign a value to a final
variable
System.out.println(myObj.x);
}}

Java Encapsulation-

The meaning of Encapsulation, is to make sure that "sensitive" data is hidden


from users. To achieve this, you must:

 declare class variables/attributes as private


 provide public get and set methods to access and update the value of a
private variable

public class Person {


private String name; // private = restricted access

// Getter
public String getName() {
return name;
}

// Setter
public void setName(String newName) {
this.name = newName;
}}

Java Packages & API-

A package in Java is used to group related classes. Think of it as a folder in a


file directory. We use packages to avoid name conflicts, and to write a better
maintainable code. Packages are divided into two categories:

 Built-in Packages (packages from the Java API)


 User-defined Packages (create your own packages)
Built in Packages,

import package.name.Class; // import a single class

import package.name.*; // import the whole package

Suppose import Scanner class,

import java.util.Scanner;

Support import the whole package,

import java.util.*;

User-defined packages,

To create your own package, you need to understand that Java uses a file
system directory to store them. Just like folders on your computer.

package mypack;
class MyPackageClass {
public static void main(String[ ] args) {
System.out.println("This is my package!");
}
}

Java Inheritance-

In Java, it is possible to inherit attributes and methods from one class to


another. We group the "inheritance concept" into two categories:

 subclass (child) - the class that inherits from another class


 superclass (parent) - the class being inherited from

To inherit from a class, use the extends keyword.

class Vehicle {
protected String brand = "Ford"; // Vehicle attribute
public void honk() { // Vehicle method
System.out.println("Tuut, tuut!");
}}
class Car extends Vehicle {
private String modelName = "Mustang"; // Car attribute
public static void main(String[] args) {
// Create a myCar object
Car myCar = new Car();

// Call the honk() method (from the Vehicle class) on the myCar object
myCar.honk();

// Display the value of the brand attribute (from the Vehicle class) and the
value of the modelName from the Car class
System.out.println(myCar.brand + " " + myCar.modelName);
}}

Java Polymorphism-

Polymorphism means "many forms", and it occurs when we have many


classes that are related to each other by inheritance.

class Animal {
public void animalSound() {
System.out.println("The animal makes a sound");
}}
class Pig extends Animal {
public void animalSound() {
System.out.println("The pig says: wee wee");
}}
class Dog extends Animal {
public void animalSound() {
System.out.println("The dog says: bow wow");
}}

Java Inner Classes-

In Java, it is also possible to nest classes (a class within a class). The


purpose of nested classes is to group classes that belong together, which
makes your code more readable and maintainable.

class OuterClass {
int x = 10;

class InnerClass {
int y = 5;
}}
public class Main {
public static void main(String[] args) {
OuterClass myOuter = new OuterClass();
OuterClass.InnerClass myInner = myOuter.new InnerClass();
System.out.println(myInner.y + myOuter.x);
}}
// Outputs 15 (5 + 10)

Java Abstraction-

Data abstraction is the process of hiding certain details and showing only
essential information to the user.

abstract class Animal {


public abstract void animalSound();
public void sleep() {
System.out.println("Zzz");
}}

Interfaces-

Another way to achieve abstraction in Java, is with interfaces.

An interface is a completely "abstract class" that is used to group related


methods with empty bodies

// interface
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void run(); // interface method (does not have a body)

Java Enums:

An enum is a special "class" that represents a group of constants


(unchangeable variables, like final variables).

To create an enum, use the enum keyword (instead of class or interface), and
separate the constants with a comma. Note that they should be in uppercase
letters:

enum Level{
LOW,
MEDIUM,
HIGH
}
Also,

Level myVar = Level.MEDIUM;

Enum inside a class,

public class Main {


enum Level {
LOW,
MEDIUM,
HIGH
}

public static void main(String[] args) {


Level myVar = Level.MEDIUM;
System.out.println(myVar);
}}

Java User Input (Scanner)-

The Scanner class is used to get user input, and it is found in the java.util
package.

import java.util.Scanner; // Import the Scanner class


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
}}

Java Date and Time-

Date

import java.time.LocalDate; // import the LocalDate class


public class Main {
public static void main(String[ ] args) {
LocalDate myObj = LocalDate.now(); // Create a date object
System.out.println(myObj); // Display the current date
}}
Time

import java.time.LocalTime; // import the LocalTime class


public class Main {
public static void main(String[ ] args) {
LocalTime myObj = LocalTime.now();
System.out.println(myObj);
}}

Display Current Date and Time,

import java.time.LocalDateTime; // import the LocalDateTime class


public class Main {
public static void main(String[ ] args) {
LocalDateTime myObj = LocalDateTime.now();
System.out.println(myObj);
}}

Java ArrayList:

The difference between a built-in array and an ArrayList in Java, is that the
size of an array cannot be modified (if you want to add or remove elements
to/from an array, you have to create a new one). While elements can be
added and removed from an ArrayList whenever you want.

import java.util.ArrayList; // import the ArrayList class


ArrayList<String> cars = new ArrayList<String>(); // Create an ArrayList object

Java LinkedList:

The LinkedList class is almost identical to the ArrayList.

// Import the LinkedList class


import java.util.LinkedList;
public class Main {
public static void main(String[] args) {
LinkedList<String> cars = new LinkedList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
System.out.println(cars);
}
}

Java HashMap:
A HashMap however, store items in "key/value" pairs, and you can access
them by an index of another type (e.g. a String).

import java.util.HashMap; // import the HashMap class


HashMap<String, String> capitalCities = new HashMap<String, String>();

Java HashSet:

A HashSet is a collection of items where every item is unique, and it is found


in the java.util package.

import java.util.HashSet; // Import the HashSet class


HashSet<String> cars = new HashSet<String>();

Java Iterator:

An Iterator is an object that can be used to loop through collections, like


ArrayList and HashSet. It is called an "iterator" because "iterating" is the
technical term for looping.

import java.util.ArrayList;
import java.util.Iterator;
public class Main {
public static void main(String[] args) {

// Make a collection
ArrayList<String> cars = new ArrayList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");

// Get the iterator


Iterator<String> it = cars.iterator();

// Print the first item


System.out.println(it.next());
}
}

Java Wrapper Class:

Wrapper class provide a way to use primitive data types(int, boolean, etc) as
objects.
Primitive Data Type Wrapper Class
byte Byte
short Short
int Integer
long Long
float Float
double Double
boolean Boolean

char Character

ArrayList<int> myNumbers = new ArrayList<int>(); // Invalid


ArrayList<Integer> myNumbers = new ArrayList<Integer>(); // Valid

public class Main {


public static void main(String[] args) {
Integer myInt = 5;
Double myDouble = 5.99;
Character myChar = 'A';
System.out.println(myInt);
System.out.println(myDouble);
System.out.println(myChar);
}
}

Exception Handling in Java:

In Java, an exception is an event that disrupts the normal flow of the program.
It is an object which is thrown at runtime.

Exception Handling is a mechanism to handle runtime errors such as


ClassNotFoundException, IOException, SQLException, RemoteException, etc.

Types Of Java Exceptions -

-> Checked Exceptions


-> Unchecked Exceptions
-> Error
1) Checked Exception

The classes which directly inherit Throwable class except RuntimeException


and Error are known as checked exceptions e.g. IOException, SQLException
etc. Checked exceptions are checked at compile-time.

2) Unchecked Exception

The classes which inherit RuntimeException are known as unchecked


exceptions e.g. ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not
checked at compile-time, but they are checked at runtime.

3) Error

Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError,


AssertionError etc.

Java Exception Keywords,

-> try (The "try" keyword is used to specify a block where we should place
exception code. The try block must be followed by either catch or finally. It
means, we can't use try block alone.)

-> catch (The "catch" block is used to handle the exception. It must be
preceded by try block which means we can't use catch block alone. It can be
followed by finally block later.)

-> finally (The "finally" block is used to execute the important code of the
program. It is executed whether an exception is handled or not.)

-> throw (The "throw" keyword is used to throw an exception.)

-> throws (The "throws" keyword is used to declare exceptions. It doesn't


throw an exception. It specifies that there may occur an exception in the
method. It is always used with method signature.)

1. public class JavaExceptionExample{


2. public static void main(String args[]){
3. try{
4. //code that may raise exception
5. int data=100/0;
6. }catch(ArithmeticException e){System.out.println(e);}
7. //rest code of the program
8. System.out.println("rest of the code...");
9. }
10. }

Java Try and Catch,

try{
//Block of code to try
}

catch(Exception e) {
//Block of code to handle errors
}

Example:

public class Main {


public static void main(String[ ] args) {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]); // error!
}
}

Use try and catch,

public class Main {


public static void main(String[ ] args) {
try {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
} catch (Exception e) {
System.out.println("Something went wrong.");
}
}
}

Finally,

public class Main {


public static void main(String[] args) {
try {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
} catch (Exception e) {
System.out.println("Something went wrong.");
} finally {
System.out.println("The 'try catch' is finished.");
}
}
}

Throw,

The throw statement allows you to create a custom error.

public class Main {


static void checkAge(int age) {
if (age < 18) {
throw new ArithmeticException("Access denied - You must be at least 18
years old.");
}
else {
System.out.println("Access granted - You are old enough!");
}
}

public static void main(String[] args) {


checkAge(15); // Set age to 15 (which is below 18...)
}}

Java Regex (Regular Expression):

A regular expression is a sequence of characters that forms a search pattern.


When you search for data in a text, you can use this search pattern to
describe what you are searching for.

Import the java.util.regex package to work with regex this package includes
Pattern class, Matcher class, PatternSyntaxException class.

import java.util.regex.Matcher;import java.util.regex.Pattern;


public class Main {
public static void main(String[] args) {
Pattern pattern = Pattern.compile("w3schools",
Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher("Visit W3Schools!");
boolean matchFound = matcher.find();
if(matchFound) {
System.out.println("Match found");
} else {
System.out.println("Match not found");
}
}}// Outputs Match found

Multi threading in Java:

It is a process of executing multiple threads simultaneously.

Multithread is a light weight sub-process, the smallest unit of multiprocessing.


Multiprocessing and multithreading both are used to achieve multitasking,
multithreading mostly used in games, animation, etc.

MultiTasking -

Multitasking is a process of executing multiple tasks simultaneously.

Types,

Process-based multitasking (Multiprocessing):

Each process has an address in memory and heavy weight.

Thread-based Multitasking (Multi threading):

Threads have the same address space and light weight.

Threads are independent. If there occurs exception in one thread, it doesn't


affect other threads. It uses a shared memory area.

Creating a thread -

1)
public class Main extends Thread{

public void run() {

System.out.println(“This code is running in a thread”);


}

}
2)
public class Main implements Runnable{
public void run(){
System.out.println(“This code is running in a thread”);
}
}

Java Lambda:

A lambda expression is a short block of code which takes in parameters and


returns a value. Lambda expressions are similar to methods, but they do not
need a name and they can be implemented right in the body of a method.

Syntax,

parameter -> expression

import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<Integer>();
numbers.add(5);
numbers.add(9);
numbers.add(8);
numbers.add(1);
numbers.forEach( (n) -> { System.out.println(n); } );
}
}

Java Files:

The File class from the java.io package allows us to work with files.

import java.io.File; // Import the File class


File myObj = new File("filename.txt"); // Specify the filename

Create and Write to Files,

Create a file,

import java.io.File; // Import the File classimport java.io.IOException; //


Import the IOException class to handle errors
public class CreateFile {
public static void main(String[] args) {
try {
File myObj = new File("filename.txt");
if (myObj.createNewFile()) {
System.out.println("File created: " + myObj.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}

Write to a file,

import java.io.FileWriter; // Import the FileWriter classimport


java.io.IOException; // Import the IOException class to handle errors
public class WriteToFile {
public static void main(String[] args) {
try {
FileWriter myWriter = new FileWriter("filename.txt");
myWriter.write("Files in Java might be tricky, but it is fun enough!");
myWriter.close();
System.out.println("Successfully wrote to the file.");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}

Read a file,

import java.io.File; // Import the File classimport


java.io.FileNotFoundException; // Import this class to handle errorsimport
java.util.Scanner; // Import the Scanner class to read text files
public class ReadFile {
public static void main(String[] args) {
try {
File myObj = new File("filename.txt");
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) {
String data = myReader.nextLine();
System.out.println(data);
}
myReader.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}

Delete a File,

import java.io.File; // Import the File class


public class DeleteFile {
public static void main(String[] args) {
File myObj = new File("filename.txt");
if (myObj.delete()) {
System.out.println("Deleted the file: " + myObj.getName());
} else {
System.out.println("Failed to delete the file.");
}
}
}

You might also like