Showing posts with label programming. Show all posts
Showing posts with label programming. Show all posts

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


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):




Wednesday 26 February 2020

Java applet | How to create applet in java | life cyle of applet - 0nline help

We are going to discuss java applet. It’s advantages and disadvantages, the life cycle of an applet and sample program, etc.

java applet

What is Java applet:

The applet is small applications that are accessed on an internet server, transported over the internet, automatically installed and run as part of a web document.

An applet is developed for internet applications. Applets are embedded in HTML documents. Applets program can be run using a web browser or applet viewer.

The applet viewer tool is one of the tools included in the JDK(Java development kit) applet viewer. For example, when you use Java to enhance a web page the Java code is embedded within HTML code. It is called an applet.

Advantages and disadvantages of the applet:

Advantages of the applet:

Following are the advantages of an applet:

  • The most important feature of an applet is, it is truly platform-independent so there is no need of making any changes in the code for the different platform i.e. it is simple to make it works on Linux, Windows and Mac OS to make it cross-platform.
  • The same applet can work on all installed versions of Java at the same time, rather than just the latest plugin version only.
  •  It can move the work from the server to the client, making a web solution more scalable with users/clients.
  • The applet naturally supports the changing user state like figure position on the chessboard.
  • An applet improves with use: after the first applet is run the JVM is already running and starts quickly.
  • It can be used to provide dynamic user interfaces and a variety of graphical effects for web pages.

 Disadvantages of applets:

 The following are the disadvantages of an applet:

  • Applets cannot run any local executable programs.
  •  It can't talk with any host other than the originating server.
  •  Applets cannot read or write to the local computer file system.
  •  It cannot find any information about the local computer.
  •  All Java created a popup window carrying a warning message.
  •  Stability depends on the stability of clients with the server.
  •  Performance directly depends on the client's machine.

Also read: Multithreading in java

How to create java applet:

The creation of an applet is present here because the applet is not structured in the same way as the Java program has been used. As you will see, applet differs from application in several key areas:

Example:
import java.awt.*;
import java.applet.*;
Public class simpleapplet extends Applet
{
Public void paint(Graphics g)
{
g.drawString(“a simple applet”,20,20);
}
}

This applet begins with two import statements. The first import the Abstract window toolkit(AWT) classes. The applet interacts with the user through the AWT. The AWT supports Windows-based, graphical interface.

 The AWT is quite large and sophisticated. So, the applet makes very limited use of the AWT.

The second statement imports the applet package which contains the class applet. Every applet that you create must be a subclass of the applet.

The next line in the program declared the class simpleapplet. This class must be declared as public because it will be accessed outside the program.

Also read: Static and fixed method in java

Inside simplapplet, paint() is declared. This method is defined by the AWT and must be overridden by the applet.

paint() is called each time that is the applet must be redisplayed its output.

For example, the window in which are the applet is running can be minimized and restored. paint() is also called when the applet begins execution. Whatever the cause, whenever the applet must redraw its output, paint() is called.

The paint() method has one parameter of type Graphics. This parameter contains the graphics context, which describes the graphics environment in which the applet is running. This context is used whenever the output of the applet is required.

Inside paint() is called to the drawString() which is a member of the Graphics class. This method outputs a string beginning at the specified X, Y location. It has the following general form:

Void drawString(string message,int x,int y);

Here the message is the string to be output beginning at the X, Y. In a java window, the upper-left corner is the location 0,0. The call to drawString() in the applet causes the message “a simple applet” to be displayed beginning at the location 20,20.

Notice:
The applet doesn't have a main() method. It does not begin execution at the main().In fact the most applets don't ever have main() method. An applet begins execution when the name of its class is passed to an applet viewer or to a net Browser.

After you enter the source code for simpleapplet, compile in the same way that you have been compiling a Java program.

However, running a simpleapplet involves a different process. There are two ways in which the applet run. They are:

-  We can execute the applet within a java compatible web browser such as Netscape navigator.

-  Using the applet viewer, such as the standard JDK tool, applet viewer. An applet viewer executes your applet in a window. This is generally the fastest and easiest way to test your applet.

Also read: Java Synchronization

To execute an applet in a web browser, you need to write a short HTML text file that contains the appropriate applet tag. Here is the  HTML file that executes a simpleapplet.

<applet code=”simpleapplet” width=200 height=60>

</applet>

Save the file(as may be simpleapplet with .html extension). To execute a simpleapplet with an applet viewer, you may also execute the HTML file. Type the following command at the DOS prompt:

C:\>appletviewer simpleapplet.html

However, a more convenient method that you can use to speed up testing simply includes the HTML code at the head of your Java source code file that contains the Applet tag.

By doing this, your code is documented with a prototype of the necessary HTML statement and you can test your compiled applet merely by starting the applet viewer with your Java source code file. If you use this method the simple applet source file look like this:

Example:

Import java.awt.*;
Import java.applet.*;
/*
<applet code=”simpleapplet” width=200 height=60>
</applet>
*/
Public class simpleapplet extends Applet
{
Public void paint(Graphics g)
{
g.drawString(“a simle applet”,20,20);
}
}

Java applet life cycle:

The class applet has four methods that constitute the applet life cycle. They are: init(0,start(),stop(), and destroy(). These are defined by the applet class java.applet.*;
1.Public void init(0
2.Public void start()
3.Public void stop()
4.Public void destroy()

Graphical representation of the life cycle of a java applet:


java applet


Another method paint() is inherited by the applet class from the component class.

1.init()- The init() method is called only when the applet begins execution.

2.start()- The start() is executed after the init() method completes execution. This method is called by the applet viewer of the web browser to resume the execution of the applet.

3.stop()- The method stop() is called by the applet viewer or the web browser to suspend the execution of an applet.

4.destroy()- The method destroy() is called before the applet is terminated by the applet viewer or the web browser.

Sample program to demonstrate the applet life cycle:

import java.awt.*;
import java.applet.*;
/*<applet code=”applettest” width=200 height=100>
</applet>
*/
public class applettest extends Applet
{
public void init()
{
System.out.println(“applet initialized…”);
setBackground(Color.cyan);
}
public void start()
{
System.out.println(“applet is started…”);
}
public void stop()
{
System.out.println(“applet is stopped…”);
}
public void destroy()
{
System.out.println(“applet is destroyed…”);
}
Public void paint(Graphics g)
{
g.drawString(“applet text”,200,400);
showStatus(“this is shown in the status”);
}
}

Applet tags in HTML:

The applet tag is used to start an applet from both HTML documents and the applet viewer. An applet viewer will execute each applet tag that is fine in a separate window, while web browsers like Netscape Navigator, Internet Explorer and hot java will allow many applets on a single page.

The <applet> tag included in the body section of the HTML file supplies the name of the applet to be loaded and tells the browser how much space the applet requires.

The <applet> tag is used to incorporate an applet into a web page. The syntax of the <applet> is

<applet code=”filename.class” width=250 height=200>

</applet>

General structure of <applet> tag is:

<applet 
code=appletname.class
alt=alternate message
width=pixels
height=pixels
align=value
vspace=value
hspace=value>
</applet>

Also read: Thread in java

Here the attributes of an <applet> are

code: Name of the applet class file
Alt: alternate message
width: width of the applet window
height: height of the applet window
align: it aligns the applet window. Commonly used values are left,right,top,bottom,middle.
vspace: specifies the vertical blank space
hspace: specifies the horizontal blank space

Passing arguments to the applet:

Java allows users to pass user-defined parameters to applets with the help of <param> tags. Every applet has a built-in way of reading parameters from the <applet> tag.

The <param> tag is used within the <applet> tag pair t pass input as a parameter to an applet.

The <param> tag has a name attribute which defines the name of the parameter and a value attribute which specifies the value of the parameter.


The syntax of the <param> tag is:

<applet>
<param name=parameter1_name value=parameter1_value>
<param name=parameter2_name value=parameter2_value>
.
.
.
<param name=parametern_name value=parametern_value>
</applet>

For example, consider the following statement to set the text attribute to the applet:

<applet>
<param name=text value=This is an example of parameter>
</applet>

Accessing parameter:

Note that the <param> tags must be included between the <applet> and </applet> tags. The init() method in the applet retrieves user-defined value of the parameters defined in the <param> tag by using the getParameter() method.

This method accepts one string argument that holds the name of the parameter and returns a string that contains the value of that parameter.

The following program demonstrates the <param> tag i.e. passing parameters to an applet:

import.java.awt.*;
Import java.applet.*;
/*
<applet code=” passing.class” width=200 height=200>
<param name=”college” value=”neha”>
</applet>
*/
Public class passing extends applet
{
String str=” hi”;
public void init()
{
str+=getParameter(“college”);
}
public void paint(Graphics g)
{
g.drawString(str,50,50);
}
}

Also read: DeadLock in java

I hope you guys understand what is java applet? how can we create it and also get to know the life cycle of an applet? If you have any doubt or information regarding this, then please do comment.

Saturday 22 February 2020

Java I/O tutorial | I/O stream class | Java file handling - Online Help

Java I/O tutorial:

In this post, we are going to discuss Java I/O tutorial. It is also known as Java file handling. Java I/O means input and output file which we can be used to read or write in a program. So to use the I/O file then we have to import the java.io package which is used for all the file handling tasks in Java.

The main concept of the Java I/O tutorial is' 'Stream''. It is a sequence of data composed in bytes. Java defines two types of the stream:

  • byte stream 
  • character stream

The topic that we will discuss in this post is:


Java I/O tutorial - Online Help

What is Byte stream:

Byte stream handles input and output of bytes. It is defined by 2 hierarchy classes. They are the InputStream and OutputStream classes.

Each of these classes is having its own several subclasses. The most commonly used method of InputStream and OutputStream is read() and write() method, which is used to read and write bytes of data.

The InputStream and OutputStream classes are the most commonly used classes of byte stream class.


 Byte stream classes in Java:

 The important classes defined by InputStream and OutputStream are as follow:


Classes
Meaning



Input stream class
1.BufferedInputStream
Buffers input from a byte stream.
2.ByteArrayInputStream
An input stream that reads from a byte array.
3.DataInputStream
Reads the standard java datatype from a byte input stream.
4.FileInputStream
Reads binary data from a file.
5.FilterInputStream
Filters an input stream.
6.PipedInputStream
Inputs pipe.
7.SequenceInputStream
Reads sequentially one after the other.
8.PushBackInputStream
Return a byte to the input stream.




Output stream class
1.BufferedOutputStream
Buffers output to a byte stream.
2.ByteArrayOutputStream
Output streams that write a byte array
3.DataOutputStream
Writes the standard java  datatype from a byte output stream.
4.FileOutputStream
Writes binary data to a file
5.FilterOutputStream
Filters an output stream
6.PipedOutputStream
Outputs pipe
7.PrintStream
Output stream that contains print() and println()
8.PushBackOutputStream
Returns bytes to the output stream.

Methods for byte stream classes:

The important method defined by the InputStream and OutputStream classes are as follow:


Methods
Meaning



Input stream method
1.int available()
Returns the number of bytes currently  available for reading
2.int read()
Reads one byte from the input stream
3.int read(byte buf[])
Reads an array of bytes into the buffer
4.int read( byte buf[],int n,int numbytes)
Reads the number of bytes into the buffer starting from an nth byte.
5.void close()
Close the input stream.
6.void mark(int numbytes)
Places the mark at the current point in the input stream.
7.void reset()
Resets the input pointer to the previously set mark.
8.void skip()
Returns the number of bytes actually skipped.

Output stream method
1.void write(int b)
Writes the single bytes to the output stream
2.void write(byte buf[])
Writes the complete bytes in the array buffer to the output stream.
3.void close()
Closes the output stream.
4.void flush()
Clears the output buffer.

What is Character stream:

Character stream handles input and output of character. It is used to define the hierarchy of classes. They are Reader and Writer class. These classes handle the Unicode characters stream.

The two important methods of Reader and Writer class is read() and write(), which reads and writes the character data respectively

 Character stream classes in Java:

The most commonly used  subclasses of reader and writer class are listed below:


Classes
Meaning




Reader class
1.BufferedReader
Buffered input character stream.
2.CharArrayReader
Reads from a character array.
3.FileReader
An input stream that reads from a file.
4.FilterReader
Filtered reader.
5.PipedReader
Inputs pipe.
6.PushbackReader
Allows character to be refused to the input stream.
7.StringReader
Reads from a string.
8.InputStreamReader
Translates bytes to a character stream.
9.LineNumberReader
An input stream that counts lines.




Writer class
1.BufferedWriter
Buffered output character stream.
2.CharArrayWriter
Writes to a character array.
3.FileWriter
Output stream that writes to a file.
4.FilterWriter
Filtered writer.
5.PipedWriter
Output pipes.
6.StringWriter
Writes to a string.
7.OutputStreamWriter
Translates character to a byte stream.
8.PrintWriter
Output stream that contains print() and println().

Character stream methods:

The various important methods defined by The Reader and writer class is as follow:


Method
Meaning



Reader class
1.void close()
Closes the input stream.
2.int read()
Reads a character from the stream.
3.int read(char buf[])
Reads an array of character into buffer.
4.int read(char buf[],int n, int numchars)
Read the number of character into the buffer starting from the nth number.
5.void mark(int numchars[])
Places the mark at the current point in the input stream.
6.void reset()
Resets the input pointer to previously set mark.
7.void skip(long numchar)
Returns the number of character actually skipped.

Writer class
1.void write(int c)
Writes the lower 2 bytes of c to the stream.
2.void write(char buff[])
Writes the characters in the buffer to the stream.
3.void close()
Closes the output stream.

4.void flush()
Writes any buffered data that is represented by the stream.

Predefined streams in java:

All Java programs automatically import the java.lang package. This package defines a class called system which encapsulates several aspects of the Runtime environment. There are basically three types of stream consoles present in Java. They are:

  • System.in
  • System.out
  • System.err


System.out: Refers to standard output stream by default this is the console.

System.in: Refers to the standard input which is the keyboard by default.

System.err: Refers to standard error stream which also is the console by default. However, these streams may be redirected to any compatible I/O device.

System.in is an object of type InputStream. System.out and System.in is an object of type PrintSystem.

These are byte stream even though they can be used to read and write characters from one console to the other console.

Reading console input

In Java, the input console is accomplished by reading from System.in. To obtain a character-based Stream that is attached to the console, we have to wrap system.in in a BufferReader object, to create a character stream. BufferedReader supports your buffered input stream. The most commonly used constructor is:

BufferedReader(Reader inputReader)

here inputReader is the stream that is linked to the instance of BufferedReader that is being created. The reader is an abstract class. its subclass is InputStreamReader, which converts bytes to the character. To obtain an InputStreamReader object that is linked to System.in, uses the following constructor:

InputStreamReader(InputStream inputStream)

because of System.in refers to an object of the type Input system, it can be used for InputStream. Putting it all together to create a BufferedReader that is connected to the keyboard is,

BufferedReader br= new BufferedReader(new InputStreamReader(System.in))

after this stream executes, br is a character-based stream that is linked to the console through system.in

-Reading characters:

To read a character from BufferedReader, use read(). The syntax will be

int read()throw IOException

each time that read() is called, it reads a character from the input stream and returns it as an integer value. It returns -1 when the end of Stream is encountered. It can throw an IOException.

Example:
class brread
{
public static void main(String args[]) throws IOException
{
char c,
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter character,q to quit");
do{
c=(char)br.read();
System.out.println(c);
}while(c!='q');
}
}

-Reading string:

To read a string from BufferedReader, use readLine(). The general format is,

String readLine() throws IOException

each time that readLine() is called, it reads a line of text from, store each line in the array. It reads until you enter stop. It can throw an IOException.

Example:
import java.io.*;
class brread{
public static void main(String args[]) throws IOException
{
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
String str;
System.out.println("enter lines of text");
System.out.println("enter stop to exit");
do
{
str=br.readLine();
System.out.println(str);
}
while(!str.Equals("stop");
}
}

Writing console output:

These methods are defined by the class PrintStream(which is the type of object reference by even though system.out). Even though System.out is a byte stream, using it for simple program output is still acceptable. For a character-based program, the method is described below.

Printstream is an output stream derived from OutpuStream. it also implements the low-level method to write(). Thus write() can be used to write to the console. The simplest form of write() defined by PrintStream is shown here,

void write(int byteval) throws IOException

This method writes to the file the bytes specified by the byteval. although the byteval is declared as an integer, only the lower level eight bits are written. Here is an example that uses write() to output the character "A" followed by the new line to the screen:

class writedemo
{
public static void main(String args[])
{
int b;
b='A';
System.out.write(b);
System.out.write('\n');
}
}

PrintWriter Class:

PrintWriter is one of the character-based classes. It displays the string equivalents of standard types(int, char, float). It has four constructors are as follows:

  • PrintWriter(Writer w)
  • PrintWriter(Writer w, boolean flushonNewline)
  • PrintWriter(OutputStream os)
  • PrintWriter(OutputStream os, boolean flushonNewline)


Here, flushOnNewline controls whether java flushes the output stream. If flushonNewLine is true, flushing automatically takes place, otherwise, flushing is not automatic.

PrintWriter supports the print() and println() method for all types including the object. To create a PrintWriter that is connected to the console output as follow:

PrintWriter pw=new PrintWriter(System.out);

The following program illustrates using a PrintWriter to handle console output:

import java.io.*;
class printwriterdemo
{
public static void main(String args[])
{
PrintWriter pw=new PrintWriter(System.out);
pw.println('x');
pw.println(400);
int i=10;
pw.println(i);
double d=4329.683596;
pw.println(d);
float f= 3.14f;
pw.println(f);
pw.println("java");
}
}


FileInputStream and FileOutputStream in java (File streams):

Java provides the number of class and method that allows you to read and write files. In Java all files are byte-oriented and Java provides methods to read and write bytes from a file to a file.

Two of the most often used stream classes are FileInputStream and FileOutputStream, which create a byte stream link to a file.

To open your file you simply create an object of one of these classes, specifying the name of the file as an argument to the constructor.

While both FileInputStream and FileOutputStream classes support constructor. The format is,

-FileInputStream(String filename) throws FileNotFoundException

-FileOutputStream(String filename)throws FileNotFoundException

here, filename specified the name of the file that you want to open. when you create an input stream if the file doesn't exist then FileNotFoundException is thrown. For output stream, if the file cannot be created then FileNotFoundException has thrown. When an output file is open any pre-existing file by the same name is destroyed.

When you are done with the file you should close it by calling close() method it is defined by both as FileInputStream and FileOutputStream as shown here:

void close() throws IOException

To read a file, you can use the read() method that is defined within FileInputStream. The general form is,

int read() throws IOException

Each time the read() is called it reads a single byte from the file and returns the byte as an integer value, read() returns -1 when the end of file is encountered. It can throw an IOException.

The following program uses read() to input and displays the content of the text file. The name of which is specified as a command-line argument.

Note the try-catch block that handles the two errors that might occur when this program is used- the specified file not being found or the user forgetting to include the name of the file.

You can use this same approach whenever you use common line arguments.

import java.io.*;
class showfile
{
public static void main(String args[]) throws IOException
{
int i;
FileInputStream fin;
try
{
fin=new FileInputStream(args[0])'
}
catch(FileNotFoundException e)
{
System.out.println("file not found");
return;
}
catch(ArrayIndexOutOfBoundException e)
{
System.out.println("usage: showfile file");
return;
}
do
{
}
while(i!=-1)'
}
}