The post Calculus Derivatives -Types & Quotient Rule appeared first on Letstacle.

]]>Calculus has two main concept explained below:

1)Differential calculus

2)Integral Calculus

**Differential Calculus**

Differential Calculus is the change in a variable. The derivative ∂y/ ∂x is another function of x which can be differentiated. The Derivative of ∂y/ ∂x is also called the second derivative of y and is denoted by ∂^² y/ ∂^² 2. Similarly, in general, the Nth derivative of y is denoted by ∂^ny/ ∂x_n.

**Problem 1:**

```
If y=e^{ax}\sin {bx} ,
prove that y_2-2ay_1+(a^2+b^2)y=0
```

**Solution:**

```
We have, y=e^{ax}\sin {bx} \\
y_1= e^{ax}(\cos {bx.b} )+\sin {bx}(e^{ax}.a) =be^{ax}\cos bx+at \\
y_1-ay=be^{ax}\cos bx\\
Differentiation on both side
y_2-ay_1=be^{ax}(-\sin bx.b)+b\cos bx(e^{ax}.a)=-b^2y+a(y_1-ay)
As a result,y_2-2ay_1+(a^2+b^2)y=0
```

**Integral Calculus**

In Mathematics, Integral is the area under the graph of a function for some definite interval and is used to find the volume, area, Displacement, and other combining infinitesimal data. It is one of the main operations of Calculus and inverse operation. It is also referred as Anti-derivative or indefinite integral.

`F(x)= \int f(x) dx`

For example,

`\int\sin^n x {\text dx} =-\frac{sin^{n-1} x cos x}{n}+\frac{n-1}{n}\int\sin^{n-2} x {\text dx}`

Here, we will explain to you about the calculus quotient rule with an example:

This rule is a special rule in calculus derivates which is defined as a formal method of dividing the function of one differential to another.

Hence, we have mentioned some techniques to master this rule in calculus.

**Calculus Quotient rule**

if y=\frac{u}{v}

then, \frac{\text{d}y}{\text{d}x}=\frac{v\frac{\text{d}u}{\text{d}x}+u\frac{\text{d}v}{\text{d}x}}{v^2}

**Problem 2: **

`Solve using the quotient rule y=\frac{3}{x+1}`

**Solution:**

```
We want to differentiate y=\frac{3}{x+1}
As per the rule we can see u = 3 and v = x+1.
So, the derivative of these two functions would be:
\frac{\text{d}u}{\text{d}x}=0 and \frac{\text{d}v}{\text{d}x}=1
Therefore, when we put this in Calculus quotient rule
\frac{\text{d}y}{\text{d}x}=\frac{(v \frac{\text{d}u}{\text{d}x}-u \frac{\text{d}v}{\text{d}x})}{v^2}
=\frac{((x+1)(0)-(3)(1))}{(x+1)^2}
=\frac{\text{(x+1)}{(0)}-\text{(3)}{(1)}}{\text{(x+1)}^2}
=\frac{-3}{(x+1)^2}
As a result, \frac{-3}{(x+1)^2} is the differential.
```

In Conclusion, We have learned about the integrals and derivatives Calculus with example that helped us to understand the changes between the values which are related by a function. Calculus Derivatives mainly focuses on two concepts of differential calculus which helps to find the rate of change of a quantity, whereas integral calculus helps to find the quantity when the rate of change is known. Therefore, this article will give you the basic knowledge of calculus derivates.

Need help with maths assignment?

We hope that you learned the concept of calculus derivative and integral along with Quotient rule with examples . Keep learning keep sharing. Follow us on Facebook and Instagram.

The post Calculus Derivatives -Types & Quotient Rule appeared first on Letstacle.

]]>The post Java Math.random | Method to get Random values appeared first on Letstacle.

]]>`rand()`

in C, `random()`

in Python.
Likewise, for Java, we have `Math.random()`

to do the job.

**Syntax**

`double myRandomNumber = Math.random();`

**Ever wondered how it worked?** In this article, you will learn more about math.random() java function or method.

Computers can generate truly random numbers by observing some external data, like mouse movements or fan noise, which are not predictable and create data from it. This is known as entropy.

Other times, they generate “*pseudorandom*” numbers by using an algorithm so the results appear random, even though they aren’t.

The `Math.random()`

the function returns such a pseudo-random number with approximately uniform distribution over the range 0 to 1 (including 0 and excluding 1) — which we can then scale to our desired range.

With all that being said, it is a fact that we can use this method in lots of situations and scenarios. This method has a lot more practical uses than theories to discuss.

To demonstrate the basics I have used a for-loop to iterate 5 times and generate 5 random numbers for 0 to 1 excluding 1.

```
public class RandomDemo {
public static void main(String[] args) {
for(int i = 0; i < 5; i++) {
System.out.println("Random number "+(i+1)+": "+Math.random());
}
}
}
```

**OUTPUT**

```
Random number 1: 0.4083247223370633
Random number 2: 0.1969001864492308
Random number 3: 0.26956654243092026
Random number 4: 0.8746480298131365
Random number 5: 0.06343364819000619
```

You can see that our random numbers are a bit ugly.

To Big decimals might not be useful to us. So we can simply multiply the fraction by 10 and round up the value using `Math.round()`

.

Alternatively, we can also explicitly type-cast it to an int data type. In this way, we can obtain a random number from 0 – 10.

**Math.round() Java fucntion**

Syntax: `Math.round(10*Math.random())`

**Type Cast to int **

Syntax: `(int)(10*Math.random())`

**Modified Output**

```
Random number 1: 7
Random number 2: 4
Random number 3: 6
Random number 4: 7
Random number 5: 0
```

With the basics clear, we can try a simple program called ‘RollDice’.

Create a method called `rollDice()`

which returns a random integer between 1 and 6 every time it is called.

**[Hint: adjust the range with proper factor. Remember if we round numbers between 0 and 0.5, we get 0. It is not a valid move.]**

Great! We hope you succeeded. Here’s the solution for you.

```
public class RandomDemo {
static int rollDice() {
return (int)(Math.random()*6 + 1);
}
public static void main(String[] args) {
for(int i = 0; i < 5; i++) {
System.out.println("Dice value "+(i+1)+": "+rollDice());
}
}
}
```

**OUTPUT**

```
Dice value 1: 4
Dice value 2: 3
Dice value 3: 6
Dice value 4: 6
Dice value 5: 2
```

The real solution is this line: `return (int)(Math.random()*6 + 1);`

. We generated a random number between 0 and 1 excluding 1 and multiplied it with 6.

**Note** if 1 is excluded then the product will always be greater or equal to 0 and less than 6. It may be 5.999..9 but no matter.

Typecasting to int will result in loss of the decimal data and we shall get 5 only. Therefore it is important to add 1 at the end to make sure we get ‘6’ too. Also adding 1 increases the lower bound from 0 to 1.

Still not sure that the values are random? Execute the code over and over again. Every time the result set will be different!

An interesting problem that requires the use of random numbers.

**Write a Program to calculate the value of pi. **

We know that the value is 22/7 approximately 3.141592653589793238. But can we derive it using a program? This question is more about mathematics less about code.

[Hint: Imagine a square of side 1 with one of its vertexes as the center of a circle of radius 1. Now generate random points (x,y) within the square and check whether it lies in or outside the circle. The ratio of points inside circle and points outside circle will be equal to pi/4]

Hope you tried. Here’s the solution for help.

```
public class CalcPi {
static double calculatePi(int iteration) {
int pointsInCircle = 0;
for(int i=0 ; i<iteration; i++) {
double x = Math.random();
double y = Math.random();
// if x and y satisfies x^2 + y^2 <= r^2
// the point lies in the circle
if((x*x) + (y*y) <= 1) {
pointsInCircle++;
}
}
return (double)pointsInCircle/iteration*4;
}
public static void main(String[] args) {
System.out.println(calculatePi(10000));
}
}
```

**OUTPUT**

`3.1284`

In the method `calculatePi(int iteration)`

we have received an integer parameter ‘*iteration*‘.

The loop runs this many times. Each time it generates a random point P(x,y) and if the point lies in the circle of radius 1 it increments ‘*pointsInCircle*‘ by 1.

After the loop ends we return the value of (points in the quarter-circle divided by points in the square).

**Note** that all points generated are inside the square of side 1 since **Math.random** returns a number between 0 and 1 excluding 1. Therefore we use the number of iterations as the number of points inside the square.

With an increasing number of iterations, the value of pi will tend to be more accurate.

Moreover, every time the code has executed the result will fluctuate. The fluctuations will keep decreasing with the increasing number of iterations. So, if you try to generate the same list, you will probably get a similar but different data set.

Here is the comparative list.

1. `System.out.println(calculatePi(10));`

**output:** `2.8`

2. `System.out.println(calculatePi(100));`

**output:** `2.92`

3. `System.out.println(calculatePi(1000));`

**output:** `3.22`

4. `System.out.println(calculatePi(10000));`

**output:** `3.15`

5. `System.out.println(calculatePi(100000));`

**output:** `3.1438`

6. `System.out.println(calculatePi(`

**1000000**));**output:** **3.141832**

Read more awesome Java tutorials such as Binary Tree in Java.

We hope this tutorial helped you to achieve the same. Keep learning keep sharing. Follow us on Facebook and Instagram.

The post Java Math.random | Method to get Random values appeared first on Letstacle.

]]>The post int to String Java | 5 Ways to Convert int to String in Java appeared first on Letstacle.

]]>For converting **int to string java**, we must understand the two data types and how to interchange them.

Simply speaking, `int`

data type stores numbers from –**2,147,483,648** to **2,147,483,647**.

Whereas, `String`

contains a set of characters also known as `char`

in Java. The int is a **primitive data type** in Java.

Unlike int, String is a **pre-defined class** and every word that we create using String class is treated as an Object.

Data type | Size | Description |
---|---|---|

byte | 1 byte | Stores whole number from -128 to 127 |

short | 2 byte | Stores whole number from -32,768 to 32,767 |

short | 2 byte | Stores whole number from -32,768 to 32,767 |

int | 4 bytes | Stores whole number from -2,147,483,648 to 2,147,483,647 |

long | 8 bytes | Stores whole number from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 |

float | 4 bytes | Stores fractional number. Sufficient for storing 6 to 7 decimal digits |

double | 8 bytes | Stores fractional number. Sufficient for storing 15 decimal digits |

boolean | 1 bit | Stores true or false |

char | 2 bytes | Stores a single character/letter or ASCII values |

Let’s take a tour.

- Firstly, Using toString:
`Integer.toString(Integer i)`

- Second, Using concatenation:
`'int i'+"";`

- Using valueOf:
`String.valueOf(Integer i)`

- Using StringBuffer/ StringBuilder:
`builderObject.apend(Integer i)`

method - Finally, Using String format:
`String.format("%d",'int i');`

Before we dive in, you should know that just like int we also have an Integer class in Java. They are both meant to store ‘numbers’ or ‘integers’ **BUT** `int`

is a primitive data type whereas `Integer`

is a wrapper class for int.

The primary advantage of **Wrapper Classes** is that we need Wrapper objects to function with collections which are only possible with the help of Wrapper classes. As the wrapper classes have objects** we can store null** as a value.

We could not store null in variables of primitive datatype.

In all these methods we have used `int i`

to be converted to String but the same could be achieved using `Integer i`

.

`Integer i = new Integer(1);`

]
A ** toString()** is an in-built method in Java that returns the value given to it in

We call the toString method from the Integer class as shown below.

```
public class IntToStringDemo {
public static void main(String[] args) {
int i = 1;
String s = Integer.toString(i);
System.out.println("Java int "+i+" to String \""+s+"\"");
}
}
```

**OUTPUT**

`Java int 1 to String "1"`

This is an indirect way but a very popular one to convert int to String. I personally prefer to use it as it is the simplest among all options. We combine an empty String with the int value using the ‘+’ operator, and we get back the String value.

```
public class IntToStringDemo {
public static void main(String[] args) {
int i = 2;
String s = i+"";
System.out.println("Java int "+i+" to String \""+s+"\"");
}
}
```

**OUTPUT**

`Java int 2 to String "2"`

To use this method we use the valueOf method from the String class. While doing so we pass the Integer value.

The

method converts different types of values into string. With the help of the string valueOf() method, you can convert int to string, long to string, boolean to string, character to string, float to string, double to string, object to a string, and char array to string.**Java String valueOf()**

```
public class IntToStringDemo {
public static void main(String[] args) {
int i = 3;
String s = String.valueOf(i);
System.out.println("Java int "+i+" to String \""+s+"\"");
}
}
```

**OUTPUT**

`Java int 3 to String "3"`

The

in Java represents a mutable sequence of characters(value can be changed). Since the String Class in Java creates an immutable sequence of characters, the StringBuilder class provides an alternative to String Class.**StringBuilder**

We create a StringBuilder object and call the append method with the int value as a parameter. The Format remains the same with

which is thread-safe but less efficient than StringBuilder.**StringBuffer**

String Buffer | String Builder |
---|---|

1. StringBuffer is synchronized. i.e it is thread-safe.
It means two threads can’t call the methods of StringBuffer simultaneously. |
1. StringBuilder is non-synchronized i.e. it is not thread-safe.
It means two threads can call the methods of StringBuilder simultaneously. |

2. StringBuffer is less efficient than StringBuilder. | 2. StringBuilder is more effecient. |

```
public class IntToStringDemo {
public static void main(String[] args) {
int i = 4;
StringBuilder s = new StringBuilder();
s.append(i);
System.out.println("Java int "+i+" to String \""+s+"\"");
}
}
```

**OUTPUT**

`Java int 4 to String "4"`

Use String format in the format shown. If you are from **C programming** background, it will seem familiar. “**%d**” is the format specifier for an int value. Similarly, we can use “**%f**” for float, “**%d**” for double, “**%c**” for char.

```
public class IntToStringDemo {
public static void main(String[] args) {
int i = 5;
String s = String.format("%d", i);
System.out.println("Java int "+i+" to String \""+s+"\"");
}
}
```

**OUTPUT**

`Java int 5 to String "5"`

It is a little unusual to change numbers into words. But think of a scenario where we are given a number and we will have to format the number with a dollar ‘$’ sign and commas. These characters are not numbers.

**So how do we do it?**

Well, we shall convert The int value to a String type using `Integer.toString('Integer value')`

the method. As the name suggests we pass an Integer value to the method and the method returns a String. Here’s the code for you.

```
public class IntToString {
public static void main(String[] args) {
int amount = 10000;
String dollar_amount = Integer.toString(amount);
System.out.println("amount: $"+dollar_amount);
}
}
```

**OUTPUT**

`amount: $10000`

It is good that we can print the dollar sign with the amount but where are the commas?

Well, for them we have to iterate through each digit of the number and add commas in regular intervals of 3 digits from the end. If you have a good grasp of loops, be confident and go ahead try it on your own.

[Hint: create a new String and use`charAt('int index')`

method to get each digit of the previous String.
Great! if you tried. Here is the solution for help.

```
public class IntToString {
public static void main(String[] args) {
int amount = 100000;
String dollar_amount = Integer.toString(amount);
String new_dollar_amount = "";
int count_digit = 0;
/*traverse the string in reverse order*/
for(int i= dollar_amount.length()-1; i>=0; i--) {
count_digit++;
/* add commas after 3 digits*/
if(count_digit % 4 == 0)
new_dollar_amount += ',';
new_dollar_amount = new_dollar_amount + dollar_amount.charAt(i);
/*Alternate syntax:
* new_dollar_amount += dollar_amount.charAt(i);
*/
}
System.out.println("amount: $"+new_dollar_amount);
}
}
```

**OUTPUT**

`amount: $000,001`

Wait! that is not correct! Our amount value is completely reversed.

We can fix that using the common solution for reversing a String or we can use the pre-defined method of the StringBuilder class in Java to get it done in one line!

```
public class IntToString {
public static void main(String[] args) {
int amount = 100000;
String dollar_amount = Integer.toString(amount);
String new_dollar_amount = "";
int count_digit = 0;
/*traverse the string in reverse order*/
for(int i= dollar_amount.length()-1; i>=0; i--) {
count_digit++;
/* add commas after 3 digits*/
if(count_digit % 4 == 0)
new_dollar_amount += ',';
new_dollar_amount = new_dollar_amount + dollar_amount.charAt(i);
/*Alternate syntax:
* new_dollar_amount += dollar_amount.charAt(i);
*/
}
/*code to reverse value of new_dollar_amount starts*/
StringBuilder fixed_amount = new StringBuilder(new_dollar_amount);
fixed_amount.reverse();
/*code to reverse value of new_dollar_amount ends*/
System.out.println("amount: $"+fixed_amount);
}
}
```

**OUTPUT**

`amount: $100,000`

You can also read out popular posts on How to Compare Two Strings?

We hope this tutorial helped you to achieve the same. Keep learning keep sharing. Follow us on Facebook and Instagram.

The post int to String Java | 5 Ways to Convert int to String in Java appeared first on Letstacle.

]]>The post Calculus Formula Sheet | Differentials calculus appeared first on Letstacle.

]]> **Leibnitz’s theorem **

**Rolle’s Theorem **

**Lagrange’s Mean-value theorem **

**Cauchy’s Mean value theorem **

**Taylor’s theorem **

**Maclaurin’s theorem **

**Taylor’s series **

**Indeterminate forms**

**Tangents & Normal-Cartesian curves**

** Polar curves Pedal equation **

**Derivation of arc **

**Radius of Curvature **

**Centre of Curvature **

**Maxima & Minima **

**Asymptotes**

**Leibnitz’s theorem for nth derivative of the production of two functions**

If u, v be two function of x derivatives of the nth order, then

`(uv)_{n} = u_n v + ^nC_1 \:u_{n-1} v_1 + ^nC_2\: u_{n-2} v_2+……..+ ^nC_r u_{n-r} v_r+….+ ^nC_n u v_n`

**Problem** : Find the nth derivative of e^x(2x+1)^3.

**Solution** :

```
Take u=e^x and \: v=(2x+3)^3
So that, u=e^x for all the integeral values of n
v_{1}=6(2x+3)^2,v_{2}=24(2x+3),v_{3}=48,v_{4},v_{5 }.... all are zeros .
By Leibnitz's theorem,
(uv)_{n} = u_n v + ^nC_1 \:u_{n-1} v_1 + ^nC_2\: u_{n-2} v_2+ ^nC_3 u_{n-3} v_3
[e^x (2x+3)^3]_n=e^x(2x+3)^3+ne^x[6(2x+3)^2]+\frac{n(n-1)}{1\times2}e^x[24(2x+3)]+\frac{n(n-1)(n-2)}{1\times 2\times 3}e^x[48]\\
\:\:\:\:\:\:\:\:\:\:=e^x{(2x+3)^3+6n(2x+3)^2]+12n(n-1)(2x+3)+8n(n-1)(n-2)}
```

**Rolle’s Theorem**

If f(x) is continues function in the closest interval [a,b] ,f’(x) exists for every value of x in the open interval (a,b) and f(a)=f(b), then there is at least one value c of x in (a,b)

Such that,

`f’(c)=0.`

**Lagrange’s Mean-value theorem**

If f(x ) is a continuous function in the closed interval [a,b] and f’x exists in an open interval (a,b), then there will be at least one of c of x in (a,b)

Such that,

`\frac{f(b)-f(a)}{b-a}=f'(c)`

If b=a+h then,

`a<c<b , c=a+ \theta h where 0< \theta <1 `

So, the mean value theorem is as follows-

If f(x) is a continuous function in a closed interval [a,a+h] and f’(x) exists in open interval (a, a+h), then there will be at least one number \theta (0< \theta <1)

Such as,

`f(a+h)=f(a)+hf'(a+\theta h)`

**Cauchy’s Mean value theorem**

If f(x) and g(x) are continuous function in closed interval [a,b] and they exist in (a,b) and g’(x)≠0 for any value of x in open interval (a,b)

then, there will be a least on value of x

Such as,

`\frac{f(b)-f(a)}{g(b)-g(a)}=\frac{f'(c)}{f'(c)}`

**Taylor’s theorem**

If f(x) and its first (n-1) derivatives be continuous in [a, a+h] and fn(x) exists for every value of x in (a,a+h), then then there is at least one number \theta (0 < \theta <1)

`f(a+h)=f(a)+hf'(a)+\frac {(h^2)}{2!}f"(a)+\dotso+\frac {(h^n)}{n!}f^n(a+\theta h)`

**Maclaurin’s theorem**

If f(x) can be expanded as an infinite series,

`f(x)=f(0)+xf'(0)+\frac {x^2}{2!}f"(0)+\frac {x^3}{3!}f'''(0)+\dotso\infty`

**Taylor’s series**

If f(x+h) can be expanded as an infinite series then

`f(x+h)=f(x)+hf'(x)+\frac {h^2}{2!}f"(x)+\frac {h^3}{3!}f'''(x)+\dotso\infty `

if f(x)= all derivates of all order and Rn tends to zero as n -> \infty then Taylor’s theorem become the Taylor’s series

**Indeterminate forms**

`\lim_{x \to a} \frac{f(x)}{\phi(x)}=\lim_{x \to a} \frac{f'(x)}{\phi'(x)}`

Form 0/0 : when \lim_{x \to a} f(x) and \lim_{x \to a} {\phi(x) }are Zero then, quotient reduces to the indeterminate form 0/0.

\lim_{x \to a} \frac{f(x)}{\phi(x)} is a finite value

**Tangents & Normal- Cartesian curves**

(Grape photo)

** 1.Equation of tangent**

At point (x,y) of the curve y=f(x) is

`Y-y=\frac{\text{d}y}{\text{d}x}(X-x)`

** 2.Equation of normal**

`Y-y=-\frac{\text{d}x}{\text{d}y}(X-x)`

**Polar curves**

**1.Angle between radius vector and tangent**If \phi be the angle between the radius of the vector and the tangent at any point of the curve

then,

`r=f(\theta),tan(\theta)= r\frac{\text{d}\theta}{\text{d}r}`

*2.Length of the perpendicular from pole on the tangent*(Grape)

If p is perpendicular from the pole on the tangents`P=r \sin\theta,`

\frac{1}{p^2}=\frac{1}{r^2}+\frac{1}{r^4}({\frac{\text{d}r}{\text{d}\theta}})^2**Pedal equation**

If r be the radius vector of any point on the curve and p the length of the perpendicular from the pole at that point on a tangent then, the relation between p and r is called the pedal equation.

**Derivation of arc**

if y=f(x)

then,

`\frac{\text{d}s}{\text{d}x}=\sqrt{[{1}+{(\frac{\text{d}y}{\text{d}x})^2}]} `

**Radius of Curvature**

** 1.Radius of curvature for polar curve**

If r=f(\theta)

then,

`\rho=\frac{(r^2+r_1^2)^(\frac{3}{2})}{r^2+2r_1^2-rr_2}`

**2.Radius of curvature for pedal curve**

`\rho=r\frac{\text{d}r}{\text{d}p}`

**Centre of Curvature**

At any point P(x,y) on the curve y=f(x) is

Given by,

```
\bar{x}=x-\frac{y_1(1+y_1^2)}{y_2}
\bar{y}=y+\frac{1+y_1^2}{y_2}
```

The locus of the center of curvature for a curve is called its Evolute and the curve is called an involute of its Evolute

**Maxima & Minima**

`f(x) is called maximum at x=a, if there exist a small number h, such as f(a)>both f(a-h) and f(a+h).`

f(x) is called minimum at x=a, if there exist a small number h, such as f(a)<both f(a-h) and f(a+h).

**Asymptotes**

It is defined as the straight line at a finite/ infinity distance from the origin, to which a tangent to the curve to the point of contact reduces to infinity.

`a_0x^n+(a_1y+b_1)x^{(n-1)}+(a_2y^2+b_2y+c_2)x^{(n-2)}+\dotso 0 (parallel to axes)`

Need help with maths assignment?

We hope this Calculus Formula Sheet helped you to achieve the same. Keep learning keep sharing. Follow us on Facebook and Instagram.

The post Calculus Formula Sheet | Differentials calculus appeared first on Letstacle.

]]>The post Algebra with fractions | Solved Examples appeared first on Letstacle.

]]>In this article we will be solving few problems related to Algebra with fractions in order to get better understanding about it.

**Examples 1**: Simplify

`\frac{1}{(x + 2)}+ \frac{6}{(x + 10)}`

**Solution:**

We have,

Hence, after simplification we get \frac{7x + 22}{(x + 2)(x + 10)}

**Example 2**: Simplify

`\frac{5x+10}{5}`

**Solution:**

We have,

Here, the common factor of 5

=\frac{5(x+2)}{5}=x+2

So, after simplification we get x+2

**Example 3**: Reduce

`\frac{4x^4}{2x^2}`

**Solution:**

We have,

** ****Example 1: **Solve

`\frac{1}{x+4}=\frac{1}{2}`

** ****Solution: **** **

\frac{1}{x+4}=\frac{1}{2}

(1)(2)=(1)(x+4)

2=x+4

x= -2

As a result, the value of x= -2

**Example 2**: Solve

`\frac{1}{(x + 2)}+ \frac{6}{(x + 10)} =\frac{4}{3}\\ `

**Solution:**

\frac{ 1(x + 10) + 6(x + 2)}{(x + 2)(x + 10)}=\frac{4}{3}\\

Don’t forget to comment, share this article with your friends, and for more updates, follow us on Facebook, Instagram, and Twitter.

Read the articles related**: Algebraic expressions, Algebra formula, Algebra in maths**

The post Algebra with fractions | Solved Examples appeared first on Letstacle.

]]>The post Graph Java | Graph Data Structure Java appeared first on Letstacle.

]]>The above graph has 5 vertices named from 0 to 4. Now the question arises, how to create a graph to operate within our code? Basically, there are 2 ways to demonstrate a Graph.

Using-

- adjacency-list
- adjacency-matrix

**Adjacency List:** A graph is represented as an array of the linked list. The index of the array represents a vertex and each element in its linked list represents the vertices that form an edge with the vertex. The following image represents the adjacency list representation:

All our methods are created in GraphDemo class. These global declarations are used in our code:

```
public class GraphDemo {
int n; // number of nodes
int adjmat[][];
List adjlist[];
GraphDemo(int n){
adjmat = new int[n][n];
adjlist = new ArrayList[n];
this.n = n;
}
```

In this method, we use an array of ArrayList to add the nodes connected for each node. We have used the number to character conversion following ASCII code to print the Graph nodes. 65-90 represents A-Z. At the same time, we avoid questions like if the same nodes are connected?

```
void createList() {
Scanner sc = new Scanner(System.in);
for(int i=0; i<n; i++) {
List addlist = new ArrayList();
for(int j = 0; j<n; j++) {
if(i == j) // to skip questions like: are A and A connected?
continue;
System.out.print("Are "+(char)(65+i)+" and "+(char)(65+j)+" connected? 1-YES/ 0-NO : ");
int inp = sc.nextInt();
if(inp == 1)
addlist.add((65+j));
}
adjlist[i] = addlist;
}
sc.close();
}
```

**Adjacency Matrix:** Here, a graph is represented in the form of a two-dimensional array. The size of the array is **V x V**, where V is the set of vertices. The following image represents the adjacency matrix representation:

This is the method used to populate the matrix for graph representation.

```
void createMatrix() {
Scanner sc = new Scanner(System.in);
for(int i=0; i<n; i++) {
for(int j=0; j<n; j++) {
if(i == j) // to skip questions like: are A and A connected?
continue;
System.out.print("Are "+(char)(65+i)+" and "+(char)(65+j)+" connected? 1-YES/ 0-NO : ");
int inp = sc.nextInt();
if(inp == 1) {
adjmat[i][j] = 1;
}
}
}
sc.close();
}
```

We have used a print Matrix method to print the output in a readable manner.

```
void printMatrix() {
for(int i=0; i<n; i++) {
if(i == 0) {
System.out.print(" ");
for(int m = 0; m < n; m++) {
System.out.print((char)(65+m)+" ");
}
System.out.println();
}
for(int j=0; j<n; j++) {
if(j == 0) {
System.out.print((char)(65+i)+" ");
}
System.out.print(adjmat[i][j]+" ");
}
System.out.println();
}
}
```

The basic algorithm is about how to search in a graph?

The two main methods are **Depth-First Search(DFS)** and **Breadth-First Search(BFS)**.

We have implemented both these methods using an adjacency matrix. The same will be possible using the adjacency list. In fact, using a list will be more efficient as we shall not be iterating through cases where there are no connections at all.

Now we shall study each of them in details:

In DFS the concept is that we shall dive as deep as possible in the graph and print each node as we visit them. Technically we use a stack to achieve this order.

```
void DFS(int v) {
if(v > n) {
System.out.println("node "+v+" exceeds limit! max: "+n);
return;
}
int visited[] = new int[n];
System.out.print("DFS: ");
DFSUtil(visited,v);
}
void DFSUtil(int visited[], int v) {
if(visited[v] == 1)
return;
visited[v] = 1;
System.out.print((char)(65+v)+" ");
for(int i=0; i<n; i++) {
if(adjmat[v][i] == 1) {
DFSUtil(visited,i);
}
}
}
```

In the above output, we have entered a graph with 4 nodes – A, B, C, and D. A is connected to B and C. D is connected to B only. We start the search from node A, move to B then D. Every time we update the visited array so that we don’t revisit any node. Since the D node has no connections, the control returns to the next connection of Node A, that is C.

In this algorithm, we start from any node and traverse the adjacent nodes. Similarly proceeding to the next node and traverse all the adjacent nodes. It is quite similar to level-order traversal in trees. Only we keep a record of the nodes visited so that we don’t revisit any node.

```
void BFS(int v) {
if(v > n) {
System.out.println("node "+v+" exceeds limit! max: "+n);
return;
}
int visited[] = new int[n];
System.out.print("BFS: ");
BFSUtil(visited,v);
}
private void BFSUtil(int[] visited, int v) {
Queue q = new LinkedList();
q.add(v);
visited[v] = 1;
while(true) {
for(int i=0; i<n; i++) {
if(adjmat[v][i] == 1) {
if(visited[i] == 1)
continue;
visited[i] = 1;
q.add(i);
}
}
if(!q.isEmpty()) {
System.out.print((char)(65+q.poll())+" ");
if(q.isEmpty())
break;
v = q.peek();
}
}
}
```

Here, we push all the connections of starting node(node-A) in a queue. Then we pop the head of the queue and in the next iteration, we search the connections of this node. In this way, we print the starting node, followed by all its connection node and their connections after them.

We hope this tutorial helped you to achieve the same. Keep learning keep sharing. Follow us on Facebook and Instagram.

The post Graph Java | Graph Data Structure Java appeared first on Letstacle.

]]>The post Binary Tree Java | Complete Guide with Code Example appeared first on Letstacle.

]]>Every value in the tree is a node. The first value 6 has 2 child nodes 4 and 8. 4 and 8 again have 2 child nodes each.

In general, a Binary Tree has no conditions for new insertion but a Binary Search Tree will follow a definite order.

The above example is also a BST(**Binary Search Tree**).

Here, we shall also take care that every **left child of a node is smaller** than the node itself and **the right child is greater**. This later **helps in** several types of **search implementations.**

Let’s say we want to **find the smallest value in a BST,** then we simply move left from the **root node(6)** until **we hit end(node 3)**.

*How easy!*

First, we define a **class** named `TreeNode`

for every node in the Tree.

This class will contain the value, the **left**,** right child**, and also the **parent node**.

```
//defining a TreeNode class with data, parent, left and right child
private class TreeNode{
int data;
TreeNode parent;
TreeNode left;
TreeNode right;
public TreeNode(int data, TreeNode parent) {
this.data = data;
this.parent = parent;
}
public TreeNode() {
// TODO Auto-generated constructor stub
}
}
```

Now, we must define the necessary functions to work with our **Binary Search Tree**.

- add
- traversal
- delete.

Let’s look at them one at a time.

In this method, we **pass a tree node** and its **parent node** and the **new value**.

- At first, we
**check if the head is null?** - Then we
**create**a**head node.** **Else**we**compare**the**new node**value**with**the**current node value**.**If**the**new node**value**is less than**the**current node then**we**make a recursive call with the left node**of the current node in line 13.**Before**that, we must**make sure that the left node is null**.**Similarly**, the**right child node**is**called**if the**new node**is**larger than**the**current node**.

```
void addUtil(TreeNode t, TreeNode parent, int value) {
if (head == null) {
head = new TreeNode(value, parent);
//System.out.println(" "+head.data);
}
else {
if(t.data > value) {
if(t.left == null) {
t.left = new TreeNode(value,t);
return;
}
addUtil(t.left,t,value);
}
else {
if(t.right == null) {
t.right = new TreeNode(value,t);
return;
}
addUtil(t.right,t,value);
}
}
}
```

We can traverse a BST in four primary ways

- InOrder
- PreOrder
- PostOrder
- LevelOrder

Here, we make a recursive call to the left child. Then print the current node value and again make a recursive call with the right child.

```
void inorderUtil(TreeNode t, int i) {
i++;
if(t == null)
return;
inorderUtil(t.left, i);
System.out.print(" "+t.data);
inorderUtil(t.right, i);
if(i == 1)
System.out.println();
}
```

You can ignore the value i. As its sole purpose is to move to the next line after traversing the tree.

In this traversal, we visit every node and print it first. Then we make two sequential recursive calls with left and right children.

```
void preorderUtil(TreeNode t, int i) {
i++;
if(t == null)
return;
System.out.print(" "+t.data);
preorderUtil(t.left, i);
preorderUtil(t.right, i);
if(i == 1)
System.out.println();
}
```

First, we make the recursive calls and then we print the node value in the end.

```
void postorderUtil(TreeNode t, int i) {
i++;
if(t == null)
return;
postorderUtil(t.left, i);
postorderUtil(t.right, i);
System.out.print(" "+t.data);
if(i == 1)
System.out.println();
}
```

We traverse the tree each level at a time. For this one, we also need a maxHeight function to calculate the height of the Binary Tree.

```
int maxHeight(TreeNode t) {
if(t == null)
return 0;
else {
int lheight = maxHeight(t.left);
int rheight = maxHeight(t.right);
if(lheight > rheight)
return lheight+1;
else
return rheight+1;
}
}
void levelorder() {
System.out.print("levelorder: ");
int height = maxHeight(head);
for(int i = 1; i<=height; i++)
levelorderUtil(head, i);
System.out.println();
}
void levelorderUtil(TreeNode t, int lvl) {
if(t == null)
return;
else if(lvl == 1)
System.out.print(t.data+" ");
else {
levelorderUtil(t.left, lvl-1);
levelorderUtil(t.right, lvl-1);
}
}
```

Let’s say we want to delete a Treenode from our tree. We shall face 3 distinct situations, the node to be deleted having –

- no child
- one child
- two child

In the **case of no child**, we don’t have anything to take care of. We **simply delete the required node**.

In **case 2, for one child**, we **delete the connection of the node with its parent** by establishing a connection between its parent and child.

In the **last case**, **for 2 children**, the complexity arises. Here, we **search for the maximum** in the **left sub-tree** **and update** the value of the **node to be deleted with it**. Then we** again call the function to delete the Maximum value in the left-subtree** because now our tree has a duplicate of that node in place of the node to be deleted.

```
void delete(int value) {
if(findNode(head, value)) {
System.out.println("deleted node "+value);
}
else {
System.out.println("node "+value+" not found! ");
}
}
boolean findNode(TreeNode t, int value) {
while(t != null) {
if(t.data > value) {
t = t.left;
}
else if(t.data < value){
t = t.right;
}
else {
//delete
deleteUtil(t,t.parent,value);
return true;
}
}
return false;
}
void deleteUtil(TreeNode t,TreeNode p, int value) {
//2 child
if(t.left != null && t.right != null) {
t.data = findMax(t.left);
deleteUtil(t.left, t, t.data);
}
//no child
else if(t.left == null && t.right == null) {
if(p.left.data == t.data) {
p.left = null;
}
else {
p.right = null;
}
}
//1 child
else {
TreeNode temp = t.left == null ? t.right : t.left;
if(p.left.data == t.data) {
p.left = temp;
}
else {
p.right = temp;
}
}
}
int findMax(TreeNode t) {
if(t.right != null) {
t = t.right;
}
return t.data;
}
```

**BST.java**

```
public class BST {
TreeNode head;
//defining a TreeNode class with data, parent, left and right child
private class TreeNode{
int data;
TreeNode parent;
TreeNode left;
TreeNode right;
public TreeNode(int data, TreeNode parent) {
this.data = data;
this.parent = parent;
}
}
//insertion of node in BST
void add(int value) {
addUtil(head,null,value);
}
void addUtil(TreeNode t, TreeNode parent, int value) {
if (head == null) {
head = new TreeNode(value, parent);
//System.out.println(" "+head.data);
}
else {
if(t.data > value) {
if(t.left == null) {
t.left = new TreeNode(value,t);
return;
}
addUtil(t.left,t,value);
}
else {
if(t.right == null) {
t.right = new TreeNode(value,t);
return;
}
addUtil(t.right,t,value);
}
}
}
void inorder() {
System.out.print("inorder: ");
inorderUtil(head, 0);
}
void inorderUtil(TreeNode t, int i) {
i++;
if(t == null)
return;
inorderUtil(t.left, i);
System.out.print(" "+t.data);
inorderUtil(t.right, i);
if(i == 1)
System.out.println();
}
void preorder() {
System.out.print("preorder: ");
preorderUtil(head, 0);
}
void preorderUtil(TreeNode t, int i) {
i++;
if(t == null)
return;
System.out.print(" "+t.data);
preorderUtil(t.left, i);
preorderUtil(t.right, i);
if(i == 1)
System.out.println();
}
void postorder() {
System.out.print("postorder: ");
postorderUtil(head, 0);
}
void postorderUtil(TreeNode t, int i) {
i++;
if(t == null)
return;
postorderUtil(t.left, i);
postorderUtil(t.right, i);
System.out.print(" "+t.data);
if(i == 1)
System.out.println();
}
int maxHeight(TreeNode t) {
if(t == null)
return 0;
else {
int lheight = maxHeight(t.left);
int rheight = maxHeight(t.right);
if(lheight > rheight)
return lheight+1;
else
return rheight+1;
}
}
void levelorder() {
System.out.print("levelorder: ");
int height = maxHeight(head);
for(int i = 1; i<=height; i++) levelorderUtil(head, i); System.out.println(); } void levelorderUtil(TreeNode t, int lvl) { if(t == null) return; else if(lvl == 1) System.out.print(t.data+" "); else { levelorderUtil(t.left, lvl-1); levelorderUtil(t.right, lvl-1); } } void print() { printUtil(head, 0, 0); } void printUtil(TreeNode t, int c, int lvl) {//left -> -1 right -> 1
int shift = 20;
if(t == null) {
return;
}
for(int i = 0; i<c+shift; i++) { System.out.print(" "); } System.out.println(t.data); lvl += 2; printUtil(t.left, c-10+(lvl), lvl); printUtil(t.right, c+10-(lvl), lvl); } void delete(int value) { if(findNode(head, value)) { System.out.println("deleted node "+value); } else { System.out.println("node "+value+" not found! "); } } boolean findNode(TreeNode t, int value) { while(t != null) { if(t.data > value) {
t = t.left;
}
else if(t.data < value){
t = t.right;
}
else {
//delete
deleteUtil(t,t.parent,value);
return true;
}
}
return false;
}
void deleteUtil(TreeNode t,TreeNode p, int value) {
//2 child
if(t.left != null && t.right != null) {
t.data = findMax(t.left);
deleteUtil(t.left, t, t.data);
}
//no child
else if(t.left == null && t.right == null) {
if(p.left.data == t.data) {
p.left = null;
}
else {
p.right = null;
}
}
//1 child
else {
TreeNode temp = t.left == null ? t.right : t.left;
if(p.left.data == t.data) {
p.left = temp;
}
else {
p.right = temp;
}
}
}
int findMax(TreeNode t) {
if(t.right != null) {
t = t.right;
}
return t.data;
}
}
```

**testTree.java**

```
public class testTree {
public static void main(String[] args) {
BST t = new BST();
t.add(3);
t.add(4);
t.add(1);
t.add(0);
t.add(2);
t.add(6);
t.add(7);
t.add(5);
t.inorder();
t.preorder();
t.postorder();
t.levelorder();
t.print();
t.delete(4);
t.print();
}
}
```

**OUTPUT**

Java also provides tree-based data structure implementations for us to use:

- TreeSet
- TreeMap

TreeSet is one of the most important implementations of the SortedSet interface in Java that uses a Tree for storage. The ordering of the elements is maintained by a set using their natural ordering. It can also be ordered by a Comparator provided at set creation time, depending on which constructor is used. The TreeSet implements a NavigableSet interface by inheriting AbstractSet class.

```
import java.util.*;
class TreeSetExample {
public static void main(String[] args)
{
TreeSet ts1 = new TreeSet();
// Elements are added using add() method
ts1.add("A");
ts1.add("B");
ts1.add("C");
// Duplicates will not get insert
ts1.add("C");
// Elements get stored in default natural
// Sorting Order(Ascending)
System.out.println(ts1);
}
}
```

Java TreeMap class is a red-black tree-based implementation. It provides an efficient means of storing key-value pairs in sorted order.

The important points about the Java TreeMap class are:

- Java TreeMap contains values based on the key. It implements the NavigableMap interface and extends AbstractMap class.
- Contains only unique elements.
- Java TreeMap cannot have a null key but can have multiple null values.
- Java TreeMap is non synchronized.
- Maintains an ascending order.

**OUTPUT**

```
import java.util.*;
class TreeMapExample{
public static void main(String args[]){
TreeMap<Integer,String> map=new TreeMap<Integer,String>();
map.put(100,"Amit");
map.put(102,"Ravi");
map.put(101,"Vijay");
map.put(103,"Rahul");
for(Map.Entry m:map.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
```

**OUTPUT**

We hope this tutorial helped you to achieve the same. Keep learning keep sharing. Follow us on Facebook and Instagram. Also, if you need any help with Java coding help, feel free to contact us.

The post Binary Tree Java | Complete Guide with Code Example appeared first on Letstacle.

]]>The post Java LinkedList appeared first on Letstacle.

]]>In Linked List, we are going to defines each nodes with data and a self-referential structure to contain the next node. The first node will be named as head and it will be the access point of the entire list! Therefore, if we need to access any element in the middle or end of the list we shall iterate through the list until we find the required node. In Java, we can use the ready-made class named LinkedList from **util** package. For instance,

```
import java.util.*;
public class LinkedListDemo {
public static void main(String[] args) {
List mylist = new LinkedList();
mylist.add(1);
mylist.add(2);
mylist.add(3);
System.out.println(mylist);
}
}
```

**OUTPUT**

But here we shall learn how to create a LinkedList of our own!

First, we must define a **Node**. each combination of **data and next** must be defined in a **class** called “node”.

```
public class listnode {
int data;
listnode next;
}
```

This class will have a global variable that will serve as the head node for our List.

```
public class MyLinkedList {
listnode head; //global list head
```

- insertion
- deletion

```
void insertion(int data) {
listnode newnode = new listnode();
newnode.data = data;
if(head == null) {
head = newnode;
}
else {
listnode temp = head;
while(temp.next != null) {
temp = temp.next;
}
temp.next = newnode;
}
}
```

On line 4, we check if the **head value is null**? If **true**, it indicates that it is the f**irst insertion in the list**. Therefore, we simply, assign the ‘newnode’ as head for the List.

However, from the 2nd insertion and so on, we iterate to the end of the list by checking for null in the next of current node using * ‘if (temp.next == null)’.* When reached the end, we link the new node at the tail of the list.

```
void print() {
listnode temp = head;
System.out.print("my list: ");
while(temp != null){
System.out.print(temp.data+" ");
temp = temp.next;
}
}
```

Finally, this function is used to print LinkedList in Java. We iterate the end of the list using a similar logic and print the data every time.

In the deletion function, we get 3 cases:

- head
- in-between
- at the end

```
void delete(int data) {
listnode temp = head;
if(temp.data == data) {
head = temp.next;
return;
}
while(temp.next != null) {
if(temp.next.data == data) {
temp.next = temp.next.next;
}
if(temp.next == null)
return;
temp = temp.next;
}
}
```

For instance, in line 3 we check for the first case, delete the first element. Then in the while block, we search if temp next data matches with the data to be deleted. If true we assign the value of temp.next.next to temp next.

The second if block checking if **temp next** is **null** or not, is very important. It is used for the 3rd case, or else a `NullPointerException`

will be thrown.

```
public class listnode {
int data;
listnode next;
}
```

```
public class MyLinkedList {
listnode head;
void insertion(int data) {
listnode newnode = new listnode();
newnode.data = data;
if(head == null) {
head = newnode;
}
else {
listnode temp = head;
while(temp.next != null) {
temp = temp.next;
}
temp.next = newnode;
}
}
void delete(int data) {
listnode temp = head;
if(temp.data == data) {
head = temp.next;
return;
}
while(temp.next != null) {
if(temp.next.data == data) {
temp.next = temp.next.next;
}
if(temp.next == null)
return;
temp = temp.next;
}
}
void print() {
listnode temp = head;
System.out.print("my list: ");
while(temp != null){
System.out.print(temp.data+" ");
temp = temp.next;
}
System.out.println();
}
}
```

```
public class testList {
public static void main(String[] args) {
MyLinkedList list = new MyLinkedList();
list.insertion(1);
list.insertion(2);
list.insertion(3);
list.print();
list.delete(1);//deletes the head node
list.print();
}
}
```

**OUTPUT**

A Queue is a linear Data structure that follows the FIFO mechanism. First in First out. In other words, it behaves just like a normal queue we see in our day-to-day lives.

To insert a value in the queue, we use the `enqueue`

function. However, it is exactly the same as the insertion function we created for our Linked List.

We shall insert the queue elements one after the other.

```
void enqueue(int data) {
listnode newnode = new listnode();
newnode.data = data;
if(head == null) {
head = newnode;
}
else {
listnode temp = head;
while(temp.next != null) {
temp = temp.next;
}
temp.next = newnode;
}
}
```

In this function, we will return the head node and then delete it using the previous delete function.

```
listnode dequeue() {
listnode temp = head;
delete(head.data);
return temp;
}
```

```
public class testList {
public static void main(String[] args) {
MyLinkedList list = new MyLinkedList();
list.enqueue(1);
list.enqueue(2);
list.enqueue(3);
list.print();
System.out.println("first element in queue: "+list.dequeue().data);
System.out.println("first element in queue: "+list.dequeue().data);
System.out.println("first element in queue: "+list.dequeue().data);
}
}
```

**OUTPUT**

We hope this tutorial helped you to achieve the same. Keep learning keep sharing. Follow us on Facebook and Instagram. Also, if you need any help with Java coding help, feel free to contact us.

The post Java LinkedList appeared first on Letstacle.

]]>The post Add days to a date in JavaScript appeared first on Letstacle.

]]>We can use inbuilt JavaScript functions to get the date such as

`getDate()`

and `setDate()`

.
The **setDate** and **getDate** methods can be used setting the day of the month.

```
obj.getDate(); // Get the day as number
obj.setDate(5); //Set the day as a number (1-31)
```

We need to create a **Date object.** Let see how we can add a day to the current date.

```
let currentDate=new Date(); //current date object
let nextDayDate=new Date(); // next date object
//Add a day to the current date in JavaScript
nextDayDate.setDate(currentDate.getDate() + 1);
//console log to check the value
console.log(nextDayDate.getDate());
```

As you can see that we have used `setDate()`

method to update the existing date. It is really easy in JavaScript.

**How to add 50 days to a date in JavaScript?**

```
let currentDate=new Date(); //current date object
let obj=new Date(); // another date object
//Add 7 days to the current date in JavaScript
obj.setDate(currentDate.getDate() + 50);
//console log to check the value
console.log(obj.getDate());
console.log(obj);
```

Further, we can also make the code reusable by adding a new method to the `Date`

prototype.

```
Date.prototype.addDays = function (numofDays) {
const date = new Date(this.valueOf());
date.setDate(date.getDate() + numofDays);
return date;
};
// Add 7 Days to current date
const date = new Date(); //the obj will have current date
console.log(date.addDays(7)); // function call and passing 7 as parameter
```

If you need expert help with JavaScript coding you can reach us out any time.

The post Add days to a date in JavaScript appeared first on Letstacle.

]]>The post Java Capitalize First Letter of String appeared first on Letstacle.

]]>Java tutorial to **capitalize first letter of a string**. In Java, as of now, the `String`

class does not provide any built-in method to capitalize the first letter.

**Thinking like a Java Programmer | The Approach**

We have other methods to change the case of the string using

- To capitalize the whole string
`toUpperCase()`

the method is used.

for example-

```
public class Main {
public static void main(String[] args) {
String string = "hello world";
String resultString = string.toUpperCase();
System.out.print(resultString);
}
}
```

**Output on the console for the above code is**

`HELLO WORLD`

So, now we have a method to make the whole string in upper case, but our problem statement is **to capitalize only the first character of the string.**

The expected output should be `Hello world`

In order to achieve the expected result, **we need to think of some way or workaround** to get the 1st character and make it capital, and then **concatenate it with the rest of the string**. Read more about substring method.

Let’s explore how we can do that-

- Get the 1st character. (using substring method)

- Convert the first character to upper case. (using toUpperCase method)

- Get the remaining string and concatenate it with the 1st character that we already capitalized.

```
public class Main {
public static void main(String[] args) {
String string = "hello world";
String firstChar=string.substring(0,1);
String remainingString=string.substring(1);
// conatinate it with the first char and ht remaining string
String resultString = firstChar.toUpperCase()+remainingString;
System.out.print(resultString);
}
}
```

**OUTPUT**

```
Hello world
```

Hurray!! finally, we achieved it.

**The above code shows how we can capitalize the first letter of the string in Java.**

`Null`

?As the `substring()`

method takes the **beginning** and **ending** index of the string. Therefore, it will give an Exception.

`Exception in thread "main" java.lang.StringIndexOutOfBoundsException: begin 0, end 1, length 0`

at java.base/java.lang.String.checkBoundsBeginEnd(String.java:3319)

at java.base/java.lang.String.substring(String.java:1874)

We can resolve this at the first instant itself.

Also, let’s make the code reusable and modularize the code reusable.

We will make use of the power of encapsulation in java. This will make the code reusable and easy to work with.

```
// capitalize method
public static String capitalize(String str){
if(str==""|| str==null){
return str;
}else{
return str.substring(0,1).toUpperCase()+str.substring(1);
}
}
```

Alright, now we can make use of the `capitalize()`

method and use it every time to make the first letter to upper case.

For example:

```
System.out.print(capitalize("hello, welcome to "));
System.out.print(capitalize("letstacle Academy"));
```

**OUTPUT**

```
Hello, welcome to Letstacle Academy
```

Capitalizing the first letter in the Java program is most often used. We hope this tutorial helped you to achieve the same. Keep learning keep sharing. Follow us on Facebook and Instagram.

The post Java Capitalize First Letter of String appeared first on Letstacle.

]]>