Pageviews

Monday, 28 October 2013

Introduction to Android files

by Unknown  |  in Android at  Monday, October 28, 2013
Android files:     Android is a Linux based Operating System,it uses a big collection of files in order to develop Applications for our Android phones.Below is a small but useful overview of each and every file used in creating an Android Application:





As you see in the image ,I had created a new project named 'Kodingpoint',which has by default the following files and folders in it.

1src-- stands for Source it contains the files that contains our source code,all the java codes which we write in our project are in this folder.All the files are saved with .java extension automatically.
2.gen- stands for Generated.This contains all the java files which will be automatically generated during project,it contains the most important file of the project named R.java,this files includes all the unique Id's we assign to our textfields,button,edittext etc.If R.java is deleted or modified,you will not be able to run your project.

3.Android 4.3 and Android Private Libraries :consists of collection of all the packages of Android,we will use in our App development.It contains all the packages like Bluetooth,Wi-fi etc.

4.Assets: It is the folder in which we can keep our different types of files like we can keep our HTML,PHP,Javascript files etc. 

5.Bin- In this folder,we have our .apk file of our application,whenever we want to install any app on our file,we simply need to go to bin folder and send appname.apk to our device.
                                                                                                                        It further consists of another important files and folder like res,which will be explained later.

6. Libs: It stands for libraries,all the libraries which consists of .jar files comes under this folder.By default it consists of android-support.jar file,we can add further jar files according to the requirement of our project.

7.res: It stands for Resolution, under this folder all the resolutions supported by our app is given here,it further consists of drawable folder,values,Manifest etc.

8.Drawable: It consists of drawable resolution sizes supported by our app,it consists of :

drawable hdpi(high dots  per inch)
drawable mdpi(medium dots per inch)
drawable ldpi(lower dots per inch)
drawable xhdpi(Extra high dots per inch)
drawable xxhdpi(Extra Extra high dots per inch)


Whenever we are developing applications for multiple screens we need to draw different layouts for each screen.

9.layout: Layout consists of the designing we wish to give to our app,it consists of .xml files all the designing part comes under this folder.

10.menu: This folder also consists of xml files,here we define all the menu items,we want to get in our application.

11.values: This folder consists of three files i.e. dimens.xml,string.xml,styles.xml.

1.dimens.xml:Basically this file is used for 2 purposes:

1.If you want to use multiple layouts to use the same value,then you can paste them in this file.
2.It can also be used for assigning static dimensions,it allows you to get a scaled value in Java code.

2 strings.xml: This is the file where we define our strings of text we want to display in our application.

3.styles.xml: This file basically defines the style of your application.It includes various options such as textcolor,background color etc.

12.Android Manifest:It is one of the most important file in our project.All the classes we have created is defined in this file,if want to add Splash screen,that too is given in this file,but the problem with manifest file is that even a single word change can cost you high,so you need to carefully write code in manifest.

A sample manifest.xml file looks like:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.kodingpoint"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.kodingpoint.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>


13.Project properties :It defines your properties of the project.























Sunday, 27 October 2013

How to create a new Button shape in Android

by Unknown  |  in Android at  Sunday, October 27, 2013
Basically android give us the by default Button icon,which does not seems to look professional,so in order to make it look more attractive,we have to create a new XML file specially for its shape.So you need to follow the below steps:

Firstly right click on 'res' folder and create a new Android XML file,name it shape.
Now right the following code in your Shape.xml:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >

<corners
android:radius="15dp"
/>
<gradient
android:angle="45"
android:centerX="35%"
android:centerColor="#1E90FF"
android:startColor="#000000"
android:endColor="#000000"
android:type="linear"
/>
<padding
android:left="0dp"
android:top="0dp"
android:right="0dp"
android:bottom="0dp"
/>
<size
android:width="150dp"
android:height="40dp"
/>
<stroke
android:width="3dp"
android:color="#878787"
/>
</shape>

3.Now we have to link this file with the background of our button,so we simply write this code:

android:background="@drawable/shape"

4.Now we are done with changing the look of our button,compare the shapes of button,now and before:















Tuesday, 27 August 2013

Sorting program in Java

by Unknown  |  in Source Codes at  Tuesday, August 27, 2013
Sorting: Sorting is the most basic program required by many software.Sorting means to sort the list of given elements in format as required by the user.Sorting has many application areas,sorting does not mean sorting in increasing or decreasing order but as according to the requirement of the program

Here is the source code of the program in Java to sort the elements in increasing order.

Java Sorting program

import java.util.Scanner;
class sorting
{
public static void main(String args[])
{
int a,b,c,temp,i;

Scanner s=new Scanner(System.in);
System.out.println("\n\t\t\t***  SORTING IN JAVA  ***\n");
System.out.println("Enter the no of elements");
int n=s.nextInt();
int []pr=new int[n];
System.out.println("Enter the list");
for( i=0;i<pr.length;i++)
{
pr[i]=s.nextInt();
}
for(i=0;i<n-1;i++)
{
for(int k=i+1;k<n;k++)
{
if(pr[i]>pr[k])
{
temp=pr[i];
pr[i]=pr[k];
pr[k]=temp;
}
}
}
System.out.println("The sorted list is");
for( i=0;i<n;i++)
{
System.out.println(pr[i]+"\t");
}
}
}

Output of the program is:

Sorting in Java


Saturday, 24 August 2013

Binary search program in Java

by Unknown  |  in Source Codes at  Saturday, August 24, 2013
Binary search:It is the advanced and efficient searching technique as compared to Linear search.In this technique the elements are entered in sorted form.It does not compare each and every element,it firstly calculates the mid of the list and if the element is less than mid then it refines searches only to the left of the mid,if the element is greater than the mid then the search is done only from the elements present at the right of the mid.

Java program code :

import java.util.Scanner;
class binary
{
public static void main(String args[])
{
int i,mid=0;
Scanner k=new Scanner(System.in);
System.out.println("Enter number of elements you want to insert");
int n=k.nextInt();
int first=0,last=n-1;
mid=last-first/2;
int []ar=new int[n];
System.out.println("Enter elements of the list in sorted form");
for(i=0;i<ar.length;i++)
{
ar[i]=k.nextInt();
}
System.out.println("Enter element you want to search");
int item=k.nextInt();
int flag=0;
for(i=0;i<n;i++)
{
if(ar[i]==item)
{
flag=1;
break;
}
if(ar[i]<item)
{
last=mid+1;
}
else
{
first=mid-1;
}
}
if(flag==1) 
{System.out.println("Item found at " + i + " location");   } 
else
{
System.out.println("Item not found");}
}

}

Output of the program:

Binary search

Advantages of Binary search:


  • It is fast,time saving and efficient searching technique.











Linear search program in Java

by Unknown  |  in Source Codes at  Saturday, August 24, 2013
Linear search:It is one of the most simplest searching technique,in this search it is checked whether a given element is present in the list or not.Linear search compare each and every element of the list with the given value,if it is presented it is returned,else the list does not contains the element we are searching.

Java program code:

import java.util.Scanner;
class linear
{
public static void main(String args[]) 
{
int i,flag=0;
Scanner r=new Scanner(System.in);
System.out.println("Enter number of elements");
int n=r.nextInt();
System.out.println("Enter elements of the list");
int[] ar=new int[n];
for(i=0;i<ar.length;i++)
{
ar[i]=r.nextInt();
}
System.out.println("Enter the element you want to search");
int k=r.nextInt();
for(i=0;i<n;i++)
{
if(ar[i]==k)
{
flag=1;
break;
}
}
if(flag==1)
{
System.out.println("Item found at "+i+" location");
}
else
{
System.out.println("Item not found");
}
}


Output of the program:


Linear search


Advantages of Linear Search:


  • You need not to enter elements in sorted form.
  • It is the simplest searching technique.



Disadvantages of Linear Search:


  • This search is inefficient because it compares elements of the list with the searched element from start to end of the list,this method does not holds good if number of elements in the list are large.


Sunday, 18 August 2013

How to get user Input in Java

by Unknown  |  in Source Codes at  Sunday, August 18, 2013
We can get the user specified input in Java using the Scanner class.For using the Scanner class in our program,we need to import the following header file:

import java.util.Scanner;

Here in the below program we are using Scanner class for addition of numbers and display the result.For example if you enter number 4 then result would be 4+3+2+1=10.

How to get user Input in Java:

import java.util.Scanner;                                 // import statement
public class Addall 
{
 public static void main(String args[])  
{      
int s=0;     
System.out.println("Enter  number ");      
Scanner q = new Scanner(System.in);          //q= Scanner object
int a = q.nextInt();
for(int i=1;i<=a;i++)
{
s=s+i;
}
System.out.println("Sum is"+s);   
}
}

User input



Java program to print table of a number

by Unknown  |  in Source Codes at  Sunday, August 18, 2013
This program displays the table of the number entered by the user using the Scanner class.

Java program to print the multiplication table of a number


import java.util.Scanner;
public class Table {


    
    public static void main(String args[])  {
     
      
        System.out.println("Enter  number ");
      
        Scanner inputReader = new Scanner(System.in);
       
      
  int a = inputReader.nextInt();
int n,b;
for( n=1;n<=10;n++)
{

b=n*a;
System.out.println("Table is"+b);
}
}
}

Output of the program is:

Table



Java Program to print alphabets

by Unknown  |  in Source Codes at  Sunday, August 18, 2013
This program will print all the character from a,b,c... upto z.

Java Program to print all alphabets(using for loop):

class alphabets
{
public static void main(String args[])
{
char ch;
for(ch='a';ch<='z';ch++)
{
System.out.println(ch);
}

}

Java Program to print all alphabets(using while loop):

class alphabets
{
public static void main(String args[])
{
char ch='a';
while(ch<='z')
{
System.out.println(ch);
ch++;
}

}



Java Program to print all alphabets(using do while loop):

class alphabets
{
public static void main(String args[])
{
char ch='a';
do
{
System.out.println(ch);
ch++;
}
while(ch<='z');

}

Output of the program is:

Alphabets

Hello World Program in JAVA

by Unknown  |  in Source Codes at  Sunday, August 18, 2013
This is the first program which is always taught to every Programmer,so here we are also continuing the same tradition,here is the source code of displaying "Hello World" in Java.

Java Hello World Program:

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

Output of the program:

HelloWorld


You can add anything in the doubles quotes of the println statement to display text of your own choice.

Sunday, 7 July 2013

Event handling in Java

by Unknown  |  in Java at  Sunday, July 07, 2013
Event handling is the heart of successful applet programming.Applets are event driven programs.Event is an object that describes a change of state.This change of state is generated by the user interacting with the Graphical User Interface(GUI) by pressing a button,entering a character via keyboard,dragging the mouse,selecting an item in Combo box,selecting an item in a list. Mostly,the events to which our applet will respond are generated by the user. These events are passed to our applets in a variety of ways. There are several types of events. The most commonly handled events are generated by the following:


  • Mouse
  • Keyboard 


and various controls, such as a push button,submit buttons or login buttons.Event handling in Java is supported by the java.awt.event package.

Event handling
Table 1:   Main Event classes in java.awt.event package


Event Listener Interfaces:

Event Listener receives notifications of events.Listeners are created by implementing one or more interfaces.Whenever an event occurs,the event source invokes the appropriate method defined by the listener and provides an event object as its argument.The commonly used listener interfaces are:

Event handling

Table 2: Interface classes for Event handling
Source code for creating a simple Form in Java

import java.awt.*;
import java.io.*;

class Form1 extends Frame
{
int i;
Label lbl1,lbl2,lbl3,lbl4,lbl5,lbl6,lbl7,lbl8,lbl9;
TextField  txt1,txt2,txt3,txt4,txt5,txt6,txt7,txt8,txt9;
GridLayout gl1;

Form1()
{
gl1=new GridLayout(12,2);
setLayout(gl1);
lbl1=new Label("First Name");
txt1=new TextField(8);
lbl2=new Label("Second Name");
txt2=new TextField(8);
lbl3=new Label("Last Name");
txt3=new TextField(8);
lbl4=new Label("Father's Name");
txt4=new TextField(8);
lbl5=new Label("Father's Occupation");
txt5=new TextField(8);
lbl6=new Label("Mother's Name");
txt6=new TextField(8);
lbl7=new Label("Mother's Occupation");
txt7=new TextField(8);
lbl8=new Label("LL.No");
txt8=new TextField(8);
lbl9=new Label("Mobile.No");
txt9=new TextField(8);

add(lbl1);
add(txt1);

add(lbl2);
add(txt2);

add(lbl3);
add(txt3);

add(lbl4);
add(txt4);

add(lbl5);
add(txt5);

add(lbl6);
add(txt6);

add(lbl7);
add(txt7);

add(lbl8);
add(txt8);

add(lbl9);
add(txt9);

}
public static void main(String arg[])
{
try{
Form1 obj=new Form1();
obj.setSize(500,400);
obj.setTitle("Personal details");
obj.setVisible(true);
}
catch(NullPointerException ae)
{
}
}
}

The output of the program is as below:

Event handling




We had used Text Editor to write our code,after this we will move onto IDE(Integrated Development Environment).We had used Text editors till now just to perfect our coding part,because in IDE most part of the code is written automatically by the IDE.













Playing audio in Java Applet

by Unknown  |  in Java at  Sunday, July 07, 2013
Applets provide GUI,which is preferred by all users.Java applet supports another good feature of playing music files within the applet.Here are the easy steps,you need to follow in order to run your music files in your Applets.

1.Firstly create a Applet,or you can use the applet code used in the previous post.Then you need to declare the audio you like to output from your Applet using keyword 'AudioClip'.The syntax will be like this;

AudioClip variable_name;

2.Now within the start(),you need to declare your AudioClip using its variable and define its path,where it is located.The syntax will be;

sound=getAudioClip(getCodeBase(),"AudioFile_Path.wav");       //sound-variable name

3.If the audio which you want to play lies within the folder,where you are writing the code,then you need not to specify the path,just simply write its name in " ".But,if you are importing your audio from another drive or folder,then you need to specify its path.

4.In the next step,we need to play our audio clip using play().

Source code for playing audio in Java Applet:

import java.applet.*;
import java.awt.*;

public class applet4 extends Applet
{
AudioClip soundFile1;
Image p;
public void init()
{
p=getImage(getDocumentBase(),"6.jpg");
}
public void start()
{
soundFile1 = getAudioClip (getCodeBase()," 123.wav ");
soundFile1.loop();
soundFile1.play();
}
public void paint(Graphics g)
{
g.drawImage(p,10,10,this);
g.drawString("Music Player",20,20);
}
}

Then you need to compile your java file like this:

Applet

The output will be like this:

Applet music



The work is all done,now you can play your audio files in your Applets.You will not be able to hear anything from this applet,since Java is not installed on our blog,but you will definately hear audio in your device.  The most important point to remember is that,you can only play .wav files in Applets,if you want to play another format,then you can convert it first,then you can play.

Display images in Java Applets

by Unknown  |  in Java at  Sunday, July 07, 2013
Displaying background images is the another powerful functionality provided by Java Applets.You can choose any of your favorite wallpapers as your background screen in Applets.So,here are some easy steps to display background images in Applets.


  • Firstly create your Applet.
  • In the declaration section,you need to declare a variable for your image,like;


Image variable_name;

In the init(),you need to initialize your image and define its path,where it is located in you system,using the following syntax;

p=getImage(getDocumentBase(),"Image_path.jpg");

If your image is located within the folder,where you are writing the codes,then you need not to specify the path of the image just need to mention its name,but if your image located in the another folder/drive,then you need to specify the path within the double quotes(" ").

Now we need to invoke our image in the paint(),where your image will be displayed using below syntax;

g.drawImage(p,10,10,this);                                        //g-object of Graphics class.

Here is the complete code for displaying a image in your Applet.

import java.applet.*;
import java.awt.*;

public class applet4 extends Applet
{
Image p;
public void init()
{
p=getImage(getDocumentBase(),"4.png");
}
public void paint(Graphics g)
{
g.drawImage(p,10,10,this);
}
}

Applet


The output of the applet is :





Now you are all done with the coding part,now you can display your defined images as background image in your Applet.

Tuesday, 25 June 2013

Graphics in Java Applets

by Unknown  |  in Java at  Tuesday, June 25, 2013
Graphics class in Applets helps us to draw different shapes in Applets,for drawing these shapes each shape has its own method.These methods are as follows:

Most Common Graphic class methods:


  • drawString(String Str,int x,int y): This method is used to draw the required String.
  • drawOval(int x,int y,int width,int height): It is used to draw Oval of the specified width and the height.
  • drawRect(int x,int y,int width,int height): It is used to draw Rectangle of the specified height and width.
  • drawLine(int x1,int y1,int x2,int y2): It is used to draw line between the points(x1,y1) and (x2,y2).
  • drawArc(int x,int y,int width,int height,int start angle,int arc angle ): It is used to draw an arc of the specified angle.
  • drawImage(Image img,int x,int y,Image observer): It is used to draw an Image of the specified parameters.
  • fillOval(int x,int y,int width,int height): It is used to fill the Oval with specified Color and the parameters specified.
  • fillRect(int x,int y,int width,int height): It is used to fill the Rectangle with specified Color and the parameters specified.
  • fillArc(int x,int y,int width,int height): It is used to fill the Arc with specified Color and the parameters specified.
  • setColor(Color c): This method is used to set the Color specified by the User.
  • setFont(Font font): This method is used to set the Font type and size according to the specified parameters.


Now,to implement these functions,we had created a simple program which will not use these functions fully,but will cover most of them.

WAP to implement the use of Graphics class in Java Applets:

import java.awt.*;
import java.applet.*;
public class Applet3 extends Applet
{
Thread t;                                                                                           //Thread is declared
AudioClip soundFile1;

public void start()
{
soundFile1 = getAudioClip (getCodeBase()," 123.wav ");                 //Audio file

soundFile1.loop();


soundFile1.play();

}
public void paint(Graphics g)
{
g.setFont(new Font("VERDANA",2,50));
g.drawString("Keep Smiling!!!",50,50);
g.setColor(Color.yellow);
g.fillOval(70,200,230,230);
g.setColor(Color.black);
try

{
g.drawOval(170,320,55,55);
for(int i=0;i<30;i+=2)
{
g.setColor(Color.black);
g.drawOval(110,250,30,i);
g.drawOval(210,250,30,i);
t.sleep(50);
g.setColor(Color.yellow);
}
g.setColor(Color.black);
g.drawOval(110,250,30,30);

g.drawOval(210,250,30,30);

g.drawArc(100,230,50,50,0,180);//main arc
g.drawArc(101,231,50,50,0,180);
g.drawArc(102,232,50,50,0,180);
g.drawArc(200,230,50,50,0,180);//main arc
g.drawArc(201,231,50,50,0,180);
g.drawArc(202,232,50,50,0,180);

g.fillOval(110,250,30,30);
g.fillOval(210,250,30,30);
}
catch(InterruptedException e)
{
}
}
}

This is the output of our program:



Here is the Applet design:





Note: We had also used Audio file in our Applet,using Audio in Applet will be discussed in later posts.You just need to see the Graphic methods used.




Sunday, 23 June 2013

Applets in Java

by Unknown  |  in Java at  Sunday, June 23, 2013
Applets: Applets are Window-based programs.They are a special type of Java programs that are designed for the transmission over the Internet,Applets can run on Web browsers as well as they can be used for developing Console based applications.From the Applets,we enter into the GUI(Graphical User Interface) environment.

Applets initialization and Termination methods:

1.init(): it is the first method to be called.In init(),our applet will initialize variables and perform other startup activities.

2.start():The Start() method is called after init().It is also called to restart an applet after it has been stopped,start can be called more than once during the life of an applet.

3.paint(): This method is called each time our applet's output must be redrawn

4.stop(); This method is used to suspend any child threads created by the applet and to perform any other activities required to put the applet in safe state.

5. destroy(); This method is called when the applet is no longer required.It is basically used to perform the Shutdown operations required of the applet.

Now we are going to make our first applet,to build your own applet you can try the below code,for executing Applet you must have a Java browser.

WAP in JAVA to print String in Applet

import java.applet.*;
import java.awt.*;
public class Applet1 extends Applet                             //Applet class is inherited
{
public void paint(Graphics g)
{
g.setFont(new Font("VERDANA",2,30));                        //Method to change Font size and type
g.drawString("Coding Garage!!!",150,150);                     //Method to draw String
}
}

As our applet run in browser so we need to provide a HTML file which will make it run in browser.So,here is the HTML code we need to write in our Text editor and save it in .html extension.

<html>
<body>
<applet code="Applet1.class" width="300", height="300">
</applet>
</body>
</html>

How to run Applets in Java?

1.Firstly we need to compile our code,after compiling Filename.class file will be created which we will use in .html file.
2.Secondly,we need to write the following command i.e on the cmd to run our Applet

appletviewer Filename.html

3.You can also directly open Filename.html to open your Applet.



Applets

Here is the output of our first Applet:

Applets

  

Thursday, 20 June 2013

Wrapper Classes in Java

by Unknown  |  in Wrapper class at  Thursday, June 20, 2013
Wrapper Classes:The primitive data types in Java such as Int,Char,Float etc has a class dedicated to it.Sometimes it is required to create an Object for these data types.The classes which provided this functionality in Java are known as 'Wrapper classes' in Java,because basically they 'wrap' the data type of the class to an Object.The wrapper classes are present in Java.lang package.

Advantages of Wrapper Classes in Java:


  • They provide mechanism to wrap primitive data types,so that primitives can do the activities reserved for the objects like being added to Array lists,Hash sets,Hash Maps etc.
  • They provide utilities functions for primitives like converting them to and from String objects,converting them to various bases like Binary,Hexadecimal and comparing various objects.
  • They are used basically for Type Casting.


Following statements illustrate the use of Wrapper classes:

int x=10;
Integer y=new Integer(x);

The first statement declares an int variable x,initialized with value 10,whereas the second statement creates an object for Integer y.The object initializes and reference to the object is assigned to the variable y.

In the above two statements,we had wrapped the data type Integer and now we are going to unwrap it,it is illustrated by following statements:

int k=y.intValue();
System.out.println(k*k); // Result is100



In the above codes,we had used Wrapping and Un-Wrapping of data types in Java.Each data type has a wrapper class associated to it,the picture shows the list

Wrappler class



The wrapper classes perform wrapping and un-wrapping of data types,here is the program of implementing wrapper classes in Java.

WAP to implement Wrapper classes in Java

class wrappler
{
public static void main(String args[])
{
byte grade=2;                                               //Byte data type
int marks=50;                                               //Integer data type
float pric=5.6f;                                             //Float data type
double rate=50.6;                                        //Double data type

Byte g1=new Byte(grade);                          //Object created for Byte data type
Integer m1=new Integer(marks);                // Object created for Integer data type
Float f1=new Float(pric);                            //Object created for Float data type
Double r1=new Double(rate);                      //Object created for Double data type

System.out.println("Values are");
System.out.println("Byte object g1:"+g1);
System.out.println("Integer object m1:"+m1);
System.out.println("Byte object f1:"+f1);
System.out.println("Double object r1:"+r1);

}
}

The output for the program is:

Wrapper class




Wrapper classes are not basically used in programs these days,because Type Casting is also supported by Java.But still,we can use Wrapper class according to our requirement.















Multi-threading in Java

by Unknown  |  in Threading at  Thursday, June 20, 2013
Multi-threading is a conceptual programming technique where a program is divided into smaller sub programs which can be implemented at the same time in parallel.It is basically used in programs where several parts work together,we can take example of Animation,using Multi-threading one sub-program can display an animation on the screen,while the other thread is built by the another sub program,so the lighter parts of the program are loaded first and heavier later.
Threading



What is a Thread ?:

 A Thread is a smaller part of a process that has single flow of control,it has a beginning,a body and an end.
  Java supports Multi-threading programming i.e Java enables us to use multiple flow of control in developing programs.Each flow of control may be thought of as a single separate program which is known as thread,so a program containing multiple flow of control is known as Multi-threaded program.

States of a Thread: Like a process,a thread also have states,these are as follows:


  • New Born State
  • Runnable State
  • Running State
  • Blocked State
  • Dead State 


1.New Born State: Whenever we create an object of thread,a thread is born and is said to be in new born state.

2.Runnable State: In this state,thread is ready  for execution,but it is waiting for the availability of the processor i.e. the thread has joined the queue of threads waiting for the execution.

3.Running State: The thread is provided the processor control,and is currently executing.

4. Blocked State: When a thread is suspended,sleeping or waiting ,then it is in Blocked state.

5.Dead State:When a thread is executed completely,then it goes to the Dead state.


So,here is the example of a simple program of Multi-threading in Java:

WAP to implement Multi-threading in Java:

class First extends Thread                                          //Thread is a in-built class in Java
{
public  void run()                                                       //in-built function-run()
{

for(int i=0;i<10;i++)
{
System.out.println("Value of i is");
}
}
}
class Second extends Thread
{
public void run()
{

for(int j=0;j<10;j++)
{
System.out.println("Value of j is");
}
}
}
class Third extends Thread
{
public void run()
{

for(int k=0;k<10;k++)
{
System.out.println("Value of k is");
}
}
}
class Test
{
public static void main(String arg[])
{
First Thread1=new First();
Second Thread2=new Second();
Third Thread3=new Third();
Thread1.start();                                                                   //Inbuilt function -start()
Thread2.start();
Thread3.start();
}
}


Threading



NOTE: The output of your program may go different because threading is based on scheduler and processor of your System.






Wednesday, 19 June 2013

Keywords used in Exception handling in Java

by Unknown  |  in Exception handling at  Wednesday, June 19, 2013
Exception handling in Java uses five keywords,unlike C++ which uses 3 keywords i.e. try,catch,throw.Java uses 5 following keywords to handle all types of Exceptions.


  • try
  • catch
  • throw
  • throws
  • finally


1.try block:In the try block,the code which we know that would create exceptions are written in try block.It must be used within the method and it must be followed by finally or catch block.

Syntax:           
            try
      {
       The code that may generate an exception is placed in this block.
        } 


 2.catch : A exception which is thrown by try block must be brought either in catch block or finally block.Once the exception is found in the try block,it is always by the Catch block.

        Syntax:            


 catch(Exception_name objectname)
{
 Statements/ error to display to user when exception occour.
  }


3 throw: Whenever an exception occur,throw block throws the exception to the catch block. Each exception that occur must be caught, the type of exception generated is caught by the catch block of that particular exception, catch block is declared below the try block.

           Syntax:       


 try
 {
 The code which may generate an exception is placed in this block.
 } 
 catch(Exception_name objectname)
{
 Statements to display to the user when an exception will occur.

  }   

4 throwsthrows keyword gives a method flexibility of throwing an Exception rather than handling it. with throws keyword in method


5 finally : This block executes in every situation even the exception occur or not.finally create a block of code that will be executed after a try catch block is executed completely. If an exception is thrown, finally block will execute even if no catch statement matches exception.


Syntax: finally
{
Block of statements which are to be executed
}

Here is the simple program to explain these keywords:

WAP in Java to implement Exception handling

import java.io.*;    //This package is imported when we use Exception handling
class excep2{
public static void main(String args[])
{
try                                                                      //try block
{
int r[]=new int[5];
r[7]=10;
System.out.println("The array is"+r[7]);
}
catch(ArrayIndexOutOfBoundsException exc )                //catch block
{
System.out.println("You are specifying an Array Index which is out of Bound");
}
finally                                                                             //finally block
{
System.out.println("Please check your array size");
}
}
}


The output goes here:


Exception handling























Monday, 17 June 2013

Exception handling in Java

by Unknown  |  in Exception handling at  Monday, June 17, 2013
Exception handling is one of the most powerful features supported by high level programming languages.Java also support exception handling by providing 5 keywords to handle all kinds of exceptions.

Exception handling






Error:An Error is a condition in the program which may produce undesirable result or it may hinder the normal execution of the program.Errors,basically are of 3 types:

1.Compile time errors:The errors which ccurs during thecompilation of the program are called as Compile time errors.Eg:Variable not declared,Loop not initialized etc.

2.Run Time errors:The errors which occurs during the run time of a program are known as Run time errors.These errors interrupts the normal flow of execution of the program. Eg:divide by 0,Array index out of bound.

3.Logical errors:These types of errors are produced by the programmer itself,because our program gets compiled and run smoothly,but the error is in the logic of the program.Eg:If we used < insted of > or used / instead of \.

Exception handling in Java:Exceptions are the unwanted entities in our program,that interrupt the normal flow of program.Example:

Statement1;
Statement2;
Statement3;
Statement4;
Statement5;
Statement6;
Statement7;
Statement8;
Statement9;
Statement10;

Our program consists of 10 statements,if the error is in the statement 5,then the rest of the statements will not be executed,the program flow will be halted.Java supports Exception handling to control these exceptions.Some exceptions are automatically handled,but some are handled using the special keywords used in Exception handling.

Types of Exception handling:


  • Built in Classes
  • User defined exeptions


Built in Classes: The classes which are already defined in the Java are called as Built in exception classes.The root class for exceptions is Exception.All the exception classes are defined in the class exception.

User defined Exceptions:The exception classes which are defined by the user by inheriting the root exception class are known as User defined exception classes in Java. 

Sunday, 16 June 2013

startsWith() and endsWith() in Java

by Unknown  |  in Strings at  Sunday, June 16, 2013
startsWith():This function returns result in Boolean expression. If the given value matches with the value specified as argument then the result is true otherwise false.

Syntax:Stringname.startsWith(Value);

 endsWith():This function also returns result in Boolean.If the given value  matches with the value specified as argument then the result is true otherwise false.

Syntax:Stringname.endsWith(Value);

WAP in Java to show the use of startsWith() and endsWith() String functions in Java:

class dony{
public static void main(String args[])
{
String str=new String("Hello to all");
System.out.println(str.startsWith("to"));
System.out.println(str.endsWith("all"));
System.out.println(str);
}
}

The output is:

Strings

equals() and equalsIgnoreCase() in Java

by Unknown  |  in Strings at  Sunday, June 16, 2013
Java- Strings provides us the facility to compare the Strings using equals() and equalsIgnoreCase() functions :

1. equals(): This function gives result in Boolean.If the two strings,which are going to be matched, are equal on the basis of characters then the result is true otherwise false.It also checks the Case sensitivity i.e.upper and lower case of the characters.

Syntax: Stringname.equals(Name of the String you want to compare);

2. equalsIgnoreCase(): This function gives result in Boolean.If the two string are equals on the basis of characters and it also ignore upper and lower case of the characters then the result is true otherwise false.

Syntax:Stringname.equalsIgnoreCase(Name of the String you want to compare);

WAP to show the use of equals() and equalsIgnoreCase() String functions in Java

class Equal
{
public static void main(String arg[])
{
String a="Koding";
String b="POINT";
String c="Koding";

String d="KODING";
System.out.println(a.equals(c));
System.out.println(a.equals(d));
System.out.println(a.equalsIgnoreCase(d));
}
}


The output goes here:
Strings


    Popular Posts

Proudly Powered by Blogger.