We've moved! — MindVault360 is now SrcForge. Better design, more content & premium notes.

Visit SrcForge →

MindVault360 has moved!

We've upgraded to SrcForge — a faster, more professional platform with better content, premium notes, and a modern design.

Visit us at SrcForge

Wednesday, July 31, 2024

Java Constructor

(Tap the post to see more)


 Constructor

         Constructor is a special member function of a class which is automatically called whenever a new object is created.

Rules

  1. It must have the same name as the class name
  2. It cannot have any return type not even void
  3. It must be declared under the public section

Types of Constructor

  • Default Constructor 
  • Parameterized Constructor 
  • Copy Constructor

Example 01:Default Constructor

package Constructor;

class square //class definition

{

int side,area;


square()

{

side=20;

}

void calculate()

{

area=side*side;

}

void display()

{

System.out.println("Area of square="+area);

}

}


class constructor

{

public static void main(String args[])

{

square s=new square(); //creating object and constructor is called

s.calculate();

s.display();

}

}



Example 02: Parameterized Constructor

package Constructor;

class Square_prgm //class definition

{

int side,area;


Square_prgm(int side)

{

this.side=side;

}

void calculate()

{

area=side*side;

}

void display()

{

System.out.println("Area of square=" +area);

}

}


class parameterized_constructor

{

public static void main(String args[])

{

Square_prgm s=new Square_prgm(20); //creating object and parameterized constructor is called

s.calculate();

s.display();

}

}


Example 03: Copy Constructor

package Constructor;


import java.util.Scanner;


class CopyConstructor

{

int age;

String name;


CopyConstructor(int a,String n)//parameter

{

age=a;

name=n;

}

CopyConstructor(CopyConstructor cc) //copy

{

age=cc.age;

name=cc.name;

}

void display()

{

System.out.println("Your name is : "+name + "\nAge is : "+age);

}

public static void main(String[] arg)

{

System.out.print("Enter your name and age :");

Scanner scan = new Scanner(System.in);

String name =scan.nextLine();

int age =scan.nextInt();

CopyConstructor cc = new CopyConstructor(age,name);

CopyConstructor c2=new CopyConstructor(cc);

cc.display();

c2.display();

}

/*Constructors are special methods named after the class and without a return type, and are used to construct objects.

* Constructors, like methods, can take input parameters. Constructors are used to initialize objects.

* A copy constructor is a constructor that creates a new object using an existing object of the same

* class and initialize each instance variable of a newly created object with corresponding instance

* variables of the existing object passed as argument.


Syntax :

public class_Name(const className old_object)


Example :

Public student(student o)*/

}







← Back Next →

Labels:

Tuesday, July 30, 2024

Java Methods

(Tap the post to see more)


Methods

Methods in Java are the same as functions in another programming language. It will execute a block of code whenever it is being called.

Syntax


--Declaring a method ---

Datatype methodname(){

//block of code

}

--calling a method---

methodname()

 

Types of Methods

1.   Method with parameter without return type.

2.   Method without parameter without return type.

3.   Method with parameter with return type.

4.   Method without parameter with return type.

 

Parameters and Arguments

They are the values that are passed during the run time of the program.

Java Scope

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

Note: static method, which means that it can be accessed without creating an object of the class, unlike public, which can only be accessed by objects

 

Java Class

         A class is a blueprint for the object. Before we create an object, we first need to define the class.

         Class is a user-defined data type that defines data and functions

Create a class in Java

We can create a class in Java using the class keyword.

Syntax:

class ClassName

{

 // variables

 // methods

 }

         Here, variables and methods represent the state and behavior of the object respectively.

          variables are used to store data and adding variables inside the body of the class are called instance variables/attribute   

         methods are used to perform some operations and adding methods inside the body of the class is called instance methods

Objects

An object is called an instance of a class.

Creating an Object in Java or instantiation

Here is how we can create an object of a class.

className object = new className(); //creating a reference variable.

E.g: circle c=new circle();

Steps for using class and object

1.   Define a class by adding variables and methods

2.   Creating objects

3.   Accessing the class members

4.   Example 01:program to find the area of a triangle using class and object

class triangle   //class definition

{

  double base,height,area;

      void getinput()

  {

               base=10.5;

          height=5.3;

      }

     

      void calculate()

  {

          area=(0,5)*base*height;

  }

    

     void display()

     {

             System.out.println(“Area of triangle=“+area);

    }

}

class triangledemo

{

         public static void main(String args[])

         {

                 triangle t=new triangle(); //creating object

                

                 t.getinput();  //accessing methods

                 t.calculate();

                 t.display();

         }

}

Example 02:

package Methods;

class Methods {

//Method without parameter without return type

public void add() {

int a = 123;

int b = 10;

System.out.println("Addition : " + (a + b));

}

//Method with parameter without return type

public void sub(int x, int y) {

System.out.println("Subtraction : " + (x - y));

}

//Method without parameter with return type

public int mul() {

int a = 123;

int b = 10;

return a * b;

}

//Method with parameter with return type

public float div(int x, int y) {

return (x / y);

}

//Recursion Function

public int factorial(int n)//5! =1*2*3*4*5=120

{

if(n==1)

return 1;

else

return (n*factorial(n-1));

}

/*

factorial(5)

factorial(4)

factorial(3)

factorial(2)

factorial(1)

return 1;

return 2*1;

return 3*2;

return 4*6;

return 5*24;

* */

}

//Type of User Define Methods in Java

public class functions {

public static void main(String args[]) {

Methods o = new Methods();

o.add();

o.sub(123, 10);

System.out.println("Muli : "+o.mul());

System.out.println("Division : "+o.div(123,10));

}

}






← Back Next →

Labels:

Wednesday, July 17, 2024

Java Regex



(Tap the post to see more)



Java Regex


The Java Regex or Regular Expression is an API that defines a pattern for searching or manipulating strings.

It is widely used to define the constraint strings such as password and email validation.

The Matcher and Pattern classes provide the facility of Java regular expression. The java.util.regex package provides the following classes and interfaces for regular expressions.

  • 1.   MatchResult interface
  • 2.   Matcher class
  • 3.   Pattern class
  • 4.   PatternSyntaxException class

 

Regex Character classes

No.

Character Class

Description

1

[abc]

a, b, or c (simple class)

2

[^abc]

Any character except a, b, or c (negation)

3

[a-zA-Z]

a through z or A through Z, inclusive (range)

4

[a-d[m-p]]

a through d, or m through p: [a-dm-p] (union)

5

[a-z&&[def]]

d, e, or f (intersection)

6

[a-z&&[^bc]]

a through z, except for b and c: [ad-z] (subtraction)

7

[a-z&&[^m-p]]

a through z, and not m through p: [a-lq-z](subtraction)


Regex Quantifiers

The quantifiers specify the number of occurrences of a character.

Regex Description

X?

X occurs once or not at all

X+

X occurs once or more times

X*

X occurs zero or more times

X{n}

X occurs n times only

X{n,}

X occurs n or more times

X{y,z}

X occurs at least y times but less than z times


Regex Metacharacters

The regular expression metacharacters work as shortcodes.

Regex Description

.

Any character (may or may not match terminator)

\d

Any digits, short of [0-9]

\D

Any non-digit, short for [^0-9]

\s

Any whitespace character, short for [\t\n\x0B\f\r]

\S

Any non-whitespace character, short for [^\s]

\w

Any word character, short for [a-zA-Z_0-9]

\W

Any non-word character, short for [^\w]

\b

A word boundary

\B

A non-word boundary





Example 1:

package String;

import java.util.regex.Matcher;

import java.util.regex.Pattern;


public class RegexExample {

public static void main(String[] args) {

// Input text containing phone numbers

String inputText = "John: 123-456-7890, Jane: 987-654-3210, Bob: 555-1234";


// Define a regex pattern for matching phone numbers

String phoneRegex = "\\b\\d{3}-\\d{3}-\\d{4}\\b";


// Create a Pattern object

Pattern phonePattern = Pattern.compile(phoneRegex);


// Create a Matcher object

Matcher matcher = phonePattern.matcher(inputText);


// Find and print all matching phone numbers

System.out.println("Matching phone numbers:");

while (matcher.find()) {

System.out.println(matcher.group());

}


// Extract area codes from phone numbers using capturing groups

String areaCodeRegex = "\\b(\\d{3})-\\d{3}-\\d{4}\\b";

Pattern areaCodePattern = Pattern.compile(areaCodeRegex);


Matcher areaCodeMatcher = areaCodePattern.matcher(inputText);


// Find and print all area codes

System.out.println("\nExtracted area codes:");

while (areaCodeMatcher.find()) {

System.out.println("Area Code: " + areaCodeMatcher.group(1));

}

}

}







Example 2:


package String;


import java.util.regex.*;


public class RegexExample2 {


public static void main(String[] args) {

Pattern pat = Pattern.compile(" .m");

Matcher mat = pat.matcher(" .am");

Boolean bool = mat.matches();

System.out.println(bool); //return whether the pattern matches/not

Boolean bool1 = Pattern.matches(" .m", " .am");

System.out.println(bool1);

System.out.println(Pattern.matches("[amn]", "acd"));

System.out.println(Pattern.matches("[^amn]", "c"));

System.out.println(Pattern.matches("[a-zA-S]", "T"));

System.out.println(Pattern.matches("[MS][a-z]{5}", "Monica"));

System.out.println(Pattern.matches("[xyz]?", "x"));

System.out.println(Pattern.matches("[xyz]+", "x"));

System.out.println(Pattern.matches("[xyz]*", "xyyza"));

System.out.println(Pattern.matches("[\\d]", "1"));

System.out.println(Pattern.matches("[\\D]", "1"));

}

}

← Back Next →

Labels: