Showing posts with label coding. Show all posts
Showing posts with label coding. Show all posts

Wednesday, 9 February 2022

Procedural oriented programming / structured programming - The program blog

In this post, we will be going to discuss procedural-oriented programming, which is also called structured-oriented programming in detail. So let's get started to see what is procedural-oriented programming step by step.

-It is sometimes known as modular programming.

-Programs written are more efficient and easier to understand and modify.

-The procedural/structured programming languages are similar to solving a problem by humans. In a nutshell, humans attempt a problem by adopting a sequence of operations.

-It makes use of a top-down design model in which a program developer maps out the overall program structure into separate subsections.

-Large-size programs can be developed in structured programs such as pascal and c. Programs are divided into multiple sub-modules.

-Procedural/Structured programming languages such as FORTRAN, BASIC, ALGOL, COBOL, C, etc., are divided into a number of segments called subprograms. There is the main function and it invokes subprograms. Thus, it focuses on functions apart from data. here also the programmer can observe the lack of secrecy.

procedural oriented programming


-The control of the program can be transferred using an unsafe goto statement.

-This type of programming language uses different control structures that are as follows:
  • Decision/selection control statements
  • Iteration control statement
  • Jump control statement

-Data is global and all the sub-programs share the same data, i.e. data are globally accessible to all functions. Thus, any function operates on the global data and this directs to losing some vital information. We can conclude here that a module represents a function.

-Procedural structured/programming languages permit data transfer through messages by means of function.

-Least importance is given to the data in procedural/structured programming languages.

-Compiler and interpreter construction are easy and simple with this type of programming language. Furthermore, these compilers and interpreters need low memory to run on the computers.

-It is difficult to implement simultaneous processes/parallelization.

I hope you guys understand what is procedural-oriented programming. If you find any mistakes or have any doubts then please comment in the comment section. Thank you so much for reading the article.

Recommended post:

Tuesday, 8 February 2022

Difference between C and C++ | C and C++ difference - The Program Blog

Hello readers in this post you guys will be going to see the difference between C and C++, and what are the similarity is there in C and C++. So guys let's see both differences and similarities available between C and C++.

difference between c and c++

Some differences between C and C++ is as follows:

-C is a procedure/function-oriented language and C++ language is driven by a procedure/object.

-Data is not protected in C, whereas data is secured in C++. The data hiding concept is absent in C.

-C uses a top-down approach while C++uses a bottom-up approach. The program is prepared step by step in c, and in C++ base, elements are prepared first.

-In C we cannot give the same name to two functions in a program, whereas due to the function overloading feature, the above concept is possible in C++. One can initialize a number of functions with the same name, but with different arguments. The polymorphism feature is built in C++, which supports this concept.

-C uses printf() and scanf() functions to write and read the data respectively, while C++ uses cout and cin objects for output and input operations, respectively. Further,the cout uses <<(insertion operator) and cin uses >> (extraction operator).

-C uses stdio.h file for input and output functions, whereas C++ uses iostream.h for these functions.

-Constructor and destructor are absent in C and the same are provided in C++.

-Inline functions are supported by C++, and the same is absent in C. Inline functions can be used as micros. They are stated by the word 'inline'.

I hope you guys get cleared what is the difference between C and C++. If you have any queries or any doubts regarding this then please do comment in the comment section below.


Recommended post:

Monday, 6 July 2020

conditional statements in javascript - Online Help

Conditional Statements in javascript:

Conditional statements in javascript are the set of commands used to perform different action s based on different conditions.  the conditional construct will either return a True or false depending upon how the condition is evaluated. There are two conditional statements in JavaScript:
  • if-else statement
  • switch statement

if-else statement :

Use this statement if you want to execute s set of code when a condition is true. If the condition is true the true statement is executed, otherwise, the false statement is executed.

The general format of the if-else statement is 

if (condition)
{
statement 1;                         
}           
else             
{             
statement 2;
}

The else clause allows you to specify a statement or group of statements that will be executed if the expression does not evaluate to true. Only one else clause is allowed in any if statement. Again, the statement can be used with or without the curly brackets.


Example:

<html>
<head>
<title> java script </title>
</head>
<body>
<b>RESULT</b>
<p> OPEN SOURCE SOFTWARE:
<script type=”text/java script”>
var m= 70;
if (m>=35 && m<=100)
{
document. write (“<span style=’ color: blue ‘> PASS</span>”);
}
else
{
document. write(“<span style=’color : red’>FAIL</span>”);
}
</script>
</body>
</html>


switch statement in javascript:

The switch statement evaluates an expression and compares the value to one or more case clauses. If you need to compare a variable against more than two or three values, the switch statement is the most efficient way.

The general format of the switch statement is

 switch (expression)
{
case labe11: block1
break;
case labe12: block2 
break;
 ……………
default:     def block;
}

Evaluate an expression and attempt to match the expression’s value to a case label. If a match is found, the program executes the associated statement.

 

Example:

<html>
<head>
<title>java script</title>
</head>
<body>
<h2><font Color=”red”>SUBJECT&CODE</h2></font>
<script type=”text/java script”>
var subject code=”UCA61”;
switch (subject code)
{
case”UCA61”: subject=”Open Source Software”;
break;
case”UCA62”: subject=”Multimedia”;
break;
case”UPCA66”: subject=Open Source Laboratory”;
break;
default: subject=” UNKNOWN SUBJECT”;
}
document. write(“<h2>code=& nbsp” +subject code+”
<br> subject =&nbsp” +</h2>”);tement
</script>
</body>
</htm1>

I hope you guys understand what is a conditional statement in javascript. If you find any mistake or having any queries then please comment down below.



Sunday, 5 July 2020

Javascript data type | Primitive data type in javascript - Online Help

The data type in javascript describes the basic elements that can be used within that language. JavaScript supports four primitive data types:

Data types in JavaScript:

Javascript datatype | Primitive data type in javascript - Online Help

1. Numbers- are values that can be processed and calculated. You do not enclose them in quotation marks. The numbers can be either positive or negative. 

2. Strings- are a series of letters and numbers enclosed in quotation marks. JavaScript uses that string literally; it doesn't process it. You'll use string for the text you want to be displayed or values you want to be passed along.

3. Boolean (true/ false) - lets you evaluate whether a condition meets or doesn't meet specified criteria.

4. Null- is an empty value. Null is not the same as 0--0 is a real, calculable number, whereas null is the absence of any value.

Number:

The numbers and can be integers (such as 2, 22 & 2000) or floating point values (such as 23.42, -56.01, & 2e45).

We can represent an integer in one of the following three ways:

Decimal: The usual numbers which are having the base 10 are the decimal numbers.

Octal: octal literals begin with a leading zero, and consist of digits from 0 through 7. The following are all valid actual literals:

00 0777    024513600

Hexadecimal: hexadecimal literals begin with a leading 0x, and they consist of digits from 0 through 9 and letter A through F. The following are all valid hexadecimal literals:

0x0     0xF8f00 0x1a3C5e7

String:

String means a set of characters. In javascript, strings are enclosed in a pair of single quotes or double-quotes. The value of the can even contain space and maybe totally made from digits.

“Chris” “Chris bates” “234.56”

Boolean:

Boolean variables hold the values true and false. These are used to hold the result of conditional tests.

Null:

It consists of a single value, null, which identifies a null, empty, or nonexistent reference. Its null value is common in all JavaScript types.

I hope you guys understand what is javascript datatype and its primitive type. If you find any mistake or having any queries then please comment down below. Thank you for reading.

Saturday, 4 July 2020

Variables in javascript | Declaring a variable - Online help

In this post, we are going to talk about what is variables in javascript? and how to declare the variables in javascript. So stay tuned till the end and let's get started.

Variable in Javascript:

A variable in javascript is a name assigned to the computer memory location to store data. As the name suggests, the value of the variable can vary, as the program runs. Before you use a variable in a JavaScript program, you must declare it.  Variables are declared with the var keyword.


Variables in javascript | Declaring a variable - Online help


Rules for variable names:

  • They must begin with a letter, digit, or underscore character.
  • We can’t use spaces in names.
  • Variable names are case sensitive.
  • We can’t use a reserved word as a variable name.


Declaring JavaScript variable:

To declare the variable using the var keyword. You can declare one variable at a time or more than one. You can also assign values to the variables at the time you declare them.


Different methods of declaring JavaScript variables:

//declaring one JavaScript variable

var firstname;


//declaring multiple JavaScript variables

var firstname, lastname;


//declaring and assigning one JavaScript variable

var firstname= ’homer’;


//declaring and assigning multiple JavaScript variable

var firstname= ’homer’, lastname= ’simpson’;


JavaScript variable scope:

The scope of a variable is the region of your program in which it is defined. JavaScript variable will have only two scopes.

  • Global variables:  A global variable has a global scope which means it is defined everywhere in the JavaScript code.
  • Local variables: A local variable will be visible only within a function where it is defined. Function parameters are always local to the function.

Within the body of a function, a local variable takes precedence over a global variable with the same name. if you declare a local variable or function parameter with the same name as a global variable, you effectively hide the global variable. The following example explains it:

<script type= “text/javascript”>
<!—
Var myvar=”global”; // declare a global variable
Function checkscope()
{
Var myvar=”local”; //declare a local variable 
Document.write(myvar);
}
//-->
</script>

This produces the following result:
local

I hope you guys understand what is variables in javascript. If you find any mistake or having any queries then please comment down below. Thank you for reading.


Recommended post:



Friday, 3 July 2020

Javascript functions | how to call javascript function - Online Help

Hello reader, today from this post we are going to learn about what is JavaScript functions? and how to call a function in javascript so read the article till the end and yeah let's gets started.

Javascript functions | how to call javascript function - Online Help


JavaScript functions:

Functions are a block of code that gets executed when called. Every function has a name, this name is used to call the function, which in turn result in the execution of the associate block of code. It takes zero or more parameters.

Functions can be defined both in the <head> and in <body> section of a document. However, to assure that a function is read or loaded by the browser before it’s called, it could be wise to put a function in the <head> section.


Defining functions:

A JavaScript functions definition consists of a function keyword, followed by the name of the function. A list of arguments to the function is enclosed in parentheses and separated by a comma. The statement within the function is enclosed in curly brace {}. The general format to define a function is,

Function functionname (parameter1, parameter2, …………..)
{
Statements;
}

Whereas,
  • Functionname is the name of the function.
  • parameter1, parameter2, ………….. are arguments or parameters to the function.


How to call functions in javascript:

A function is not executed before it is called. You can call functions containing arguments. The general form is:

functionname (parameter1, parameter2, …………..)


Return statement:

The return statement can be used to return any valid expression that evaluates to a sign value. A function that will return a result must use the return statement. This statement specifies the value which will be returned to where the function was called from.
A javascript function can have an optional return statement. This is required if you want to return a value from a function. The general format is,

return(); 

return(parameter);


Example:

<html>
<body>
<script type=”text/JavaScript”>
function funexample(a, b)
{
return a+b;
}
document.write (funexample(10,20));
</script>
</body>
</html>


Explanation:

The function is being called from another javascript method document.write. funexample() is a function passing two arguments 10 and 20.

Where 10 is being passed into the function funexample() as ‘a ‘ and 20 is being passed into the function as ‘b’.  

Once they are both passed in it return the sum of the two-argument. “return” simply means that we will return something back to the method or function that called our function funexample(). 

As a result, you can return sent back 30. The final statement that executed was more like document.write(30).


Example 2:

<html>
<head>
<title>example2</title>
</head>
<body>
<h2>
<script type=”text/JavaScript”>
functionsum(a, b)
{
c= a+b;
return c;
}
d= sum(12,8);
document.write (“the returned value is :” + d);
</script>
</h2>
</body>
</html>

The output of the above program is:

the returned value is: 20


Recursive function:

Recursion refers to the situation, wherein function call themselves. In other words, there is a call to specific functions from within the same function. It is called a recursive function.

Example:

<html>
<head>
<title>recursive function</title>
</head>
<body>
<script type= “text/JavaScript”>
var num=5;
function fact(num)
{
if (num>1)
{
document.write(“fact=”+num*fact(num-1));
}
else
{
document.write(“fact=”+num);
}
}
</script>
</body>
</html>

The result of the above program is,

Fact=120

I hope you guys understand what is javascript functions and how to define and call javascript functions. If you have any queries or doubt or you know more information about this article then please comment down below. Thank you for reading and visiting my blog.
.



Thursday, 2 July 2020

JavaScript operators | Types of operator in javascript - Online Help

Hello, readers today we are going to see what is javascript operators and types of the operator in detail. So let's gets started.


JavaScript operators | Types of operator in javascript - Online Help

Operators in javascript:

An operator is a symbol that tells the computer to perform certain mathematical and logical operations. Operators are used in a program to manipulate data and variables. 


Types of the operator in JavaScript:

The JavaScript language following type of operators:
  • Arithmetic operator
  • Comparison operator
  • Logical or relational operator
  • Assignment operator
  • Conditional or ternary operator
  • Bitwise operator

Let’s have a look on all operators one by one.


Arithmetical operator:

There are following arithmetical operator supported by JavaScript language:

Assume variable A holds 10 and variable B holds 20 then:

 Operator Description Example
 +  Adds two operands A+B will give 30
 - Subtract the second operand from the first  A-B will give -10
 * Multiply both operands A*B will give 200
 / Divide numerator by denominator  B/A will give 2
 %  Modulus operator and a reminder of after an integer division B%A will give 0
 ++  Increment operator, increases integer value by one.  A++ will give 11
 --  The decrement operator, decreases the integer value by one. A—will give 9

Example:

<html>
<head>
<title> Javascript</title>
</head>
<body>
<H2>
<script type=”text/javascript”>
var a=8;
var b=1;
document.write(“<h2>”+a+”+“+b+”=”+(a+b)+”<br></h2>”);
document.write(“<h2>”+a+”-“+b+”=”+(a-b)+”<br></h2>”);
document.write(“<h2>”+a+”*“+b+”=”+(a*b)+”<br></h2>”);
document.write(“<h2>”+a+”/“+b+”=”+(a/b)+”<br></h2>”);
</script>
</h2>
</body>
</html>

The output of the above program:
8+1=9
8-1=7
8*1=8
8/1=8


Javascript comparison operator:

There are following comparison operator supported by JavaScript language:

Assume variable A hold 10 and variable B holds 20 then:

 Operator Description Example
 == Checks if the value of two operands are equal or not, if yes then condition becomes true. (A==B) is not true
 != Checks if the value of two operands are equal or not, if the value is not equal then the condition becomes true.(A!=B) is true
 > Checks if the value of the left operands is greater than the value of right operand, if yes then condition becomes true.  (A>B) is not true
 < Checks if the value of the left operand is less than the value of right operand, if yes then the condition becomes true. (A<B) is true
 >= Checks if the value of the left operand is greater than or equal to the left operand, if yes then the condition is true. (A>=B) is not true
 <= Checks if the value of the right operand is less than or equal to the value of right operand, if yes then the condition is true.  (A<=B) is true

Example:

<html>
<head><title>Comparison operator</title></head>
<body>
<h2>
<script type=”text/javascript”>
var a=200;
var b=300;
if(a>b)
document.write(“A is greater than B”);
else
document.write(“B is greater than A”);
</script>
</h2>
</body>
</html>


Logical operator:

These are the following logical operators supported by javascript.

Assume that variable  A holds 10 and variable  B holds 20 then:

 Operators Description Example
 && && is called a logical AND operator. If both the operands are non-zero then the condition becomes true.  (A&&B) is true
 || || is called a logical OR operator. If any of the two operands are non zero then the condition becomes true (A||B) is true
 ! ! is called logical NOT. Use to reverse the logical state of its operands. If a condition is true then the logical NOT operator will make false. !(A&&B) is false

Example:

<html>
<head><title>Logical operator</title></head>
<body>
<h2>
<script type=”text/javascript”>
var marks1=24;
var marks2=35;
if(mark1>40 && marks2=>40)
document.write(“ pass”);
else
document.write(“fail”);
</script>
</h2>
</body>
</html>
The output is:
fail


Bitwise operator:

These are the following bitwise operator supported by the javascript language.

Assume that the variable A holds 2 and variable B holds 3 then:

 Operator Description Example
 & Called bitwise AND operator. It performs Boolean AND operation on each bit of its integer argument.

 (A&B) is 2
 |  Called bitwise OR operator. It performs Boolean OR operation on each bit of its argument. (A|B) is 3
 ^ Called bitwise XOR operator. It performs a Boolean exclusive OR operation on each biut of its integer arguments. Exclusive OR means that either operand one is true or operand two is true, but not both. (A^B) is 1
 ~ Called bitwise NOT operator. It is a unary operator and operates by reversing all bits in the operands (~B) is -4
 << Called bitwise shift left operator.it moves all bits in its first operand to the left by the number of places specified in the second operand.

New bits are filled with zero. shifting a value left by one position is equivalently multiplying by 2, shifting 2 positions is equivalent to multiplying by 4, etc.,
 (A<<1) is 4
 >> Called bitwise shift right with sign operator.it moves all the operands to the right by the number of places specified in the second operand.

The bits filled in on the left depends on the sign bit of the original operand, in order to preserve the sign of the result.

If the first operand is positive, the result has zeroes placed in the high bits; if the first operands are negative, the result has ones placed in the high bit.

 Shifting a value right one place is equivalent to dividing by 2(discarding the reminder), shift right two places is equivalent to integer division by 4, and so on
 (A>>1) is 1
 >>>  This operator is called a bitwise shift right with zero operators. This operator is just like the >> operator, except that the bits shifted in on the left are always zero,  (A>>>1) is 1


Assignment operator:

These are the following assignment operators supported by the javascript language:

 Operator  Description Example
 =  A simple assignment operator assigns a value from right side operands to left side operand
C=A+B will assign the value of A+B into C
 +=  Add AND assignment operator, it adds right operands to left operands and assigns the result to the left operand. C+=A is equivalent to C=C+A
 -= Subtract AND assignment operator, it subtracts right operands to left operands and assigns the result to the left operand.C-=A is equivalent to C=C-A
 *= Multiply AND assignment operator, it multiplies right operands to left operands and assigns the result to the left operand.C*=A is equivalent to C=C*A
 /= Divide AND assignment operator, it divides right operands to left operands and assigns the result to the left operand.C/=A is equivalent to C=C/A
 %= Modulus AND assignment operator takes modulus using two operands and assigns the result to the left operand.C%=A is equivalent to C=C%A

Example:

<html>
<head><title>Assignment operator</title></head>
<body>
<script type=”text/javascript”>
var a=1980;
var b=1985;
document.write(a+”++”+b+”=”+(a==b)+”<br>”);
document.write(a+”>=”+b+”=”+(a>=b)+”<br>”);
document.write(a+”<=”+b+”=”+(a<=b)+”<br>”);
</script>
</body>
</html>

The output is:
1980==1985=false
1980>=1985=false
1980<=1985=true


Ternary operator javascript/conditional operator:

There is an operator called a conditional operator. It is also called a ternary operator. this operator first evaluates an expression for a true or false value and then execute one of the two given statement depending upon the result of the evaluation. The conditional operator has this syntax:

 Operator description Example
 ?:Conditional expression  
If the condition is true? Then value X: Otherwise value Y


Example:

<html>
<head><title>Logical operator</title></head>
<body>
<h2>
<script type=”text/javascript”>
var a=24;
var b=20;
document.write(a>b ? ”true”: “false”);
</script>
</h2>
</body>
</html>

The output is:
true

I hope you guyz understand what is javascript operators and types of operators in detail. If you have any queries or you guys find any mistake then please comment down below. Thank you for reading.


Recommended post:

Thursday, 11 June 2020

Uses of javascript | What is javascript used for - Online help

hello readers, in the last post we have discussed the javascript introduction briefly so now in this post, we'll see the uses of javascript?

Uses of javascript | What is javascript used for - Online help

Uses of JavaScript:

The JavaScript was initially introduced to provide programming capability at both the server and client ends of web connection.

JavaScript, therefore, is implemented at two ends:
  •  client end
  •  back end
The client-side JavaScript is embedded in XHTML documents and is interpreted by the web browser.

It also provides some means of computation, which serves as an alternative for some tasks done at the server-side.

Interaction with users through form elements, such as button and menus, can be conveniently described in JavaScript. Because button clicks and mouse movements are easily detected with JavaScript, they can be used to trigger computations and provide feedback to the user.

For example, when a user Moves the mouse cursor from the textbox, JavaScript can detect that moment and check the appropriateness of the textbox’s value(which presumably was just filled by the user).

Even without forms, user interaction is both possible and simple to the program in JavaScript. These interactions, which take place in the dialogue Windows, includes getting input from the user and allowing the user to make choices through the buttons. It is also easy to generate new content in the browser displays dynamically.

This transfer of tasks ensures that the server is not overloaded and performs only the required task.

But client-side JavaScript cannot replace servers side JavaScript; because server-side software supports file operation, database access, security, and networking, etc.

JavaScript is also used as an alternative to Java applets.

Programming in JavaScript is must simpler than compared to Java

JavaScript support DOM (document object model) which enables JavaScript to access and modify CSS properties and content of any element of a displayed XHTML document.

I hope you guys understand the uses of the javascript. If you have any queries or you find any mistake please comment down below. 

Wednesday, 10 June 2020

What is JavaScript used for in web design - Online Help

What is JavaScript used for in web design:

Hello, readers in this post we will gonna see what is JavaScript used for in web design. let's get started.

What is JavaScript used for in web design - Online Help

The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the document object model(DOM)of the page. Some simple examples of  this usage are:
  • Opening or popping up a new window with programmatic control over the size, position, and attributes of the new window(i.e. whether the menus, toolbar, etc are visible). 
  • Validation of web form input value to make sure that they will be accepted before they are submitted to the server.
  • Changing images as the mouse cursor moves over them: This effect is often used to draw the user's attention to important links displayed as graphical elements.
Because JavaScript code can run locally in the user's browser(rather than on the remote server) it can respond to user action quickly, making an application feel more responsive.

Furthermore, JavaScript code can detect user actions with HTML alone cannot, such as individual keystrokes.

An application such as Gmail takes advantage of this: much of the user interface logic is written in JavaScript, and Javascript dispatches requests for the information(such as the content of an email message) to the server.

So guys let's see what can a Javascript do.

Also read:  Multithreading in java

what can a JavaScript do:

JavaScript gives web developers a programming language for the use in the web pages and allows them to do the following:

JavaScript gives HTML designer a programming tool: 

HTML authors are normally not programmers, but JavaScript is a scripting language with a very simple Syntax! almost anyone can put simple "snippets" of code into their HTML pages.


JavaScript can put dynamic text into HTML pages:   

A JavaScript statement like this: document.write("<h3>"+name+"</h3>") can write a variable text into HTML page.


JavaScript can react to events:

A JavaScript can be set to execute when something happens like when a page has finished loading or when a user clicks on the HTML element.


JavaScript can read and write HTML elements:

A JavaScript can read and change the content of the HTML element.

Also Read: Thread in java

JavaScript can be used to validate data:

A JavaScript can be used to validate form data before it is submitted to the server. This saves the server from extra processing.


JavaScript can be used to detect the visitor's Browser:

A JavaScript can be used to detect the visitor's browser and depending on the Browser-load another page specifically designed for that browser.


JavaScript can be used to create cookies:

A JavaScript can be used to store and retrieve information on the visitor's computer.

Also read: Exception handling in java

So guys here I had briefly explained what is JavaScript used for in web design. I hope you guys understand the uses of JavaScript in web design if you have any doubts please comment in the comment section below. Thank you for visiting and reading my site.

Posts you may like:


Tuesday, 9 June 2020

Javascript introduction| what is Javascript| History of javascript -Online Help

Javascript Introduction:

The important topic of web technology is JavaScript. Now, what is JavaScript let's see the JavaScript introduction?


Javascript introduction| what is Javascript| History of javascript -Online Help


JavaScript is a client-side scripting language and connected to the server.

It is widely used in tasks ranging from validation of form data to the creation of complex user interfaces.

Javascript is a dynamic computer programming language and powerful client-side scripting language. It is mainly designed for enhancing the interaction of the user with the web pages.

JavaScript not only used in web pages but also used in many desktop and server programs as well as in-game development and mobile application development.

Dynamic HTML is a combination of the content formatted using HTML, CSS, scripting language, and DOM by combining all of these technologies we can create an interesting and interactive website.

History of JS:

Netscape initially introduced the language under the name LiveScript in an early beta release of navigator 2.0 in 1995, and the focus was on form validation. After that, the language was renamed JavaScript.

After Netscape introduced JavaScript in version 2.0 of their browser, Microsoft introduced a clone of JavaScript call JS script in internet explorer 3.0.

Also read: Java string | string classes in java

What is JavaScript?

  • JavaScript was designed to add interactivity to the HTML pages.
  • JavaScript is a scripting language.
  • It is the lightweight programming language.
  • JavaScript is usually embedded directly into HTML pages.
  • JavaScript is an interpreted language that means which executes without preliminary completion.
  • Everyone can use JavaScript without purchasing a license.

Are Java and JavaScript the same?

No, Java and JavaScript are not the same. In fact, they are completely different languages in both concepts and designs.

Java {developed by Sun Microsystem} is a powerful and much more Complex program - in the same category as C and C++.

Let's see the comparison between Java and Javascript:

Java

JavaScript

  • Java is a programming language
  • JavaScript is a scripting language
  • It is strongly typed language
  • It is dynamically typed language
  • Types on own at the compile time
  • Compile-time type checking is impossible
  • The objects in Java is static
  • Javascript Object are dynamic
  • Collection of data member and the method is fixed at the compilation time
  • The number of data member and methods of an object can change during execution
  • Object-oriented programming language
  • Object-based language

I hope you guys understand what is JavaScript and the introduction briefly. Let's see the uses and advantages of it in the next post if you have any queries please comment down below. Thank you for visiting my site.

Monday, 9 March 2020

Java String | String class in java | java string methods - Online Help

In this post, we are discussing what is java string? that is what is a string class in java.let's see the string constructors and methods available in java. The topic which we will be going to cover in this post is

Java String | String class in java - Online Help

String class in Java:

A combination of characters is a string. Strings are instances of the class string. They are real objects and enable combination, testing, and modification. When a string literal is used in the program, Java automatically creates an instance of the String class. 

The string is a sequence of characters enclosed within double quotes “ “. This class is used to represent the constant string.it is fixed size. These classes are contained in the package java.lang that represents a string in Java that provides two fundamental classes that represent a string in Java. They are:


String declaration in Java:

Before we use a string in our program we have to declare it. so the java string Syntax is,

String stringname;

Where,

  • String is the java literal
  • Stringname is the name of the string

Example:
String s;

String initialization in Java:

The string can be initialized at the time of the string declaration. The value which we assign to the string should be enclosed with the double quotes " ''. so the initialization of the string is,

String strname=” variables”;

Example:

String s=” Sania”;

We can use an array in the declaration and initialization of string. let’s pass the array of values to the string,

String name[]={“Rohit”,” Rahul”,” Rohan”,” pooja”,” Sneha”};

Accessing the string:

In order to access the string, we have to create an instance for the string class. With the help of instance, we can access the string.

In the next section, let's see how to create Constructors and what are the different ways available in constructors so that we can understand the topics on how to create and access the instance.

Drawbacks of string class:


  • String class objects are immutable because once it is created the content of the string cannot be modified.
  • Because it is immutable it needs more memory space.

String program in Java:

Declaration and access of strings
Class strings
{
int i;
String name[]={“aaaa”,”bbbb”,”cccc”,”dddd”};
Void show()
{
System.out.println(“my favourite names are”);
for(i=0;i<5;i++)
System.out.println(name[i]);
}
}
Public static void main(String args[])
{
Strings s=new strings();
s.show();
}
}

The output is:

aaaa
bbbb
cccc
dddd

String constructors in Java:

Different types of String constructors are available in Java so that you can use the string in different ways as per your requirement. With these constructors, you will go through with different types of string declaration and initialization. The different types of the constructor are:

Empty string:

Let's see how empty string is created using the class string. It is the default constructor with no parameter.

The general form is,

String stringname;
Stringname=new String();

In the above statement is equivalent to the following statement:

String stringname=new string();

Example:

String str1;
str1=new String();

Is equivalent to

String str1=new String();

Or

String str=” ”; // empty string

The example will create an instance of a string with no characters in it.

String with character:

In order to create a string initialized with the character, we need to pass an array of characters to the constructor. let's see how the string is created with the character.

The general format is,

String strname=new String(character);

where the string and new are keywords. Strname is the name of the string. The String(character) is the constructor character in which the character is to assign.

Example:
Char chars[]={‘z’,’u’,’h’,’a’};
String s=new String(name);
System.out.println(s);

The above example creates a string instance with the four characters from the char as the initial value of the string s.

String with another string:

let's see how a string is created with another string. The general format to create a string with another string is,

String strname1=new String(strname2);

Where,

  • The string and new are keywords
  • The strname1,2 is the name of the string. 
  • In the string(), strname1 is assigned to the strname2

Example:
String str1=”sneha”;
String str2=new String(str1);
System.out.println(str2);

String with substring:

A string is created using the substring that allowed the specification of the starting index and the number of characters that have to be used. The general format is,

String strname=new String(char chars[],int startIndex, int numberofchar);

Where,

  • The String and new are keywords
  • char chars[] is the original string of character
  • startIndex is the starting index of the substring
  • Numberofchar is the ending number of substring.

Example:
char name[]={‘s’,’n’,’e’,’h’,’a’}
String str=new String(name,1,4);
System.out.println(str);

The example given above will print neha because when ‘n’ was at the index at 1 and we specified the count of 4 characters to be used to construct the string.

String with an array of ASCII:

let's see how a string is created with the array of ASCII parameters. The general format is,

String strname=new String(ASCIInum);

Where,

  • String and new are keywords. 
  • strname is the name of the string 
  • ASCII num is the ASCII value.

Example:

int value[]={77,65,78};
String str1=new String(value);
System.out.println(str1);

it will return the output as MAN.

string methods in Java:

The string class contains a number of methods that allow you to perform string manipulation. Most commonly used string methods are as follow:

Methods
Description
General format
length()
Number of character in string
Stringobject.length()
charAt()
The char at a location in the string
Stringobject.charAt(int indexvalue);
getChars(),getBytes()
Copy chars or bytes into a external array
Stringobject.getChars();
toCharArray()
Produces a char[]contains the character in the string
Stringobject.toCharArray()
equals(),equalsIgnoreCase()
An equality check on the content of the two strings
Stringobject.equals(string);
compareTo()
Results is negative,0 or + depending on the lexicographical ordering of the string and the argument. Uppercase and the lower case are not equal.
Stringobject.compareTo(string1);
regionMatches()
Boolean result indicates whether the region matches
 boolean regionMatches()
startWith()
Boolean result indicating whether the region matches
 boolean startWith()
endsWith()
The boolean result indicates if the argument is a suffix
boolean endsWith()
indexOf(),lastIndexOf()
Return -1 if the argument is not found within the string,otherwise returns the index where the arguments start. lastIndexOf() searches backward from the end.
Stringobject.indexOf(char);
Stringobject.lastIndexOf(char);
Substring()
Return a new string object contains the specified character set.
1.   Stringobject.substring(int beginindex);
2.   Stringobject.substring(int indexbegin,int endindex);
Concat()
Return a new string object contain the original strings character followed by the characters in the argument.
Stringobject.concat(string);
Replace()
Return a new string object with the replacements made.uses the old string if no matches found.
Stringobject.replace(oldstring,newstring);
toLowerCase(),toUpperCase()
Return a new string object with the case of all letter changed.uses the old string if no changes need to be made.
Stringobject.toLowerCase();
Stringobject.toUpperCase();
Trim()
Return the new string object with the whitespace removed from each end.uses the old string if no changes need to be made.
Stringobject.trim();
valueOf()
It returns a string containing a character representation of the argument.
String valueOf();
Intern()
Produces one and only string handle for each unique character sequence.
 String intern()


It is seen that every string method returns a new string object when it is necessary to change the contents. Also noticed that if the content does not require any change, the method will just return a handle to the original string. This saves storage and overhead.

Java String method example:

equal():

Class equaldemo
{
Public static void main(String args[])
{
String s1=”welcome”;
String s2=”welcome”;
String s3=”good morning”;
String s4=”welcome”
System.out.println(s1+”equals”+s2+”is”+s1.equals(s2));
System.out.println(s1+”equals”+s3+”is”+s1.equals(s3));
System.out.println(s1+”equals”+s4+”is”+s1.equals(s4));
}
}

The output is:

Welcome equals welcome is true
Welcome equals good morning is false
Welcome equals welcome is false

Sample program for :
length(),toLowerCase(),toUpperCase(),charAt(),concat(),indexOf(),lastIndexOf(),substring(),replace(),and trim()


Class st
{
Public static void main(String args[])
{
String s=”johny johny yes papa”+”eating sugar no papa”+”telling lies no papa”;
String s1=”hello world”;
String s2=”hello”;
String s3=”HELLO”;
String s4=”monkey”;
String s5=”don”
System.out.println(“index of e=”+s.indexOf(‘e’));
System.out.println(“last index of e=”+s.lastIndexOf(‘e’));
System.out.println(s1.substring(6));
System.out.println(s1.length());
System.out.println(s1.substring(3,8));
System.out.println(s2.concat(“world”));
System.out.println(s2.replace(‘l’,’w’));
System.out.println(s2.toUpperCase());
System.out.println(s3.toLowerCase());
System.out.println(s3.charAt(3));
System.out.println(s1.trim());
System.out.println(s4.compareTo(s5);
}
}

The output will be

johny johny yes papa eating sugar no papa telling lies no papa
index of e:14
11
last index of e: 62
world
lo wo
helloworld
hewwo
HELLO
Hello
l
hello world
6

String arithmetic:

The ‘+’ sign doesn't mean “addition” when it is used with the string object. The Java string class has something called operator overloading”, in another word the ‘+’ sign, when used with the string object, behave differently that does with everything else.

For string, it means: “concatenate these two strings”. when it is used with the strings and other objects creates a single string that contains the concatenation of all its operands.

When a numerical value is added to a string, the compiler calls the method that turns the numerical value( int, float, etc) into a string which can then be added with the Plus sign.

Any object or type you can convert to the string if the method to string() is implemented. To create a string, add all the parts together and output them. The +=operator will also work for the strings.

Example:
class sample
{
String fname=”rohit”;
String lname=”sharma”;
void show()
{
System.out.println(“The full name is+” “+fname+” “+lname);
}
Public static void main(String args[])
{
sample s1=new sample();
s1.show();
}
}

The output is;

The full name is rohit sharma

I hope you find this article useful. if you have any queries regarding this or something went wrong. Then please do comment.

Recommended post(you may like):