SlideShare a Scribd company logo
1. Program to generate Fibonacci series




   import java.io.*;
   import java.util.*;
   public class Fibonacci
    {
   public static void main(String[] args)
   {
    DataInputStream reader = new DataInputStream((System.in));
      int f1=0,f2=0,f3=1;
   try
   {

      System.out.print("Enter value of n: ");
      String st = reader.readLine();
    int num = Integer.parseInt(st);

       for(int i=1;i<=num;i++)
   {
         System.out.println("tt"+f3+"tnt");
              f1=f2;
              f2=f3;
            f3=f1+f2;
     }
   }
   catch(Exception e)
   {
   System.out.println("wrong input");
   }
   }
   }

2. Program to take two numbers as input from command line interface and display their sum
Coding:
    class Sum
    {
    public void add(int a,int b)
    {
    int c;
    c=a+b;
    System.out.print("tttnnThe sum of two no is = "+c);
    System.out.println("nnn");
    }
    }

    class SMain
    {
    public static void main(String arg[])
    {
    Sum obj1=new Sum();
    int x,y;
    String s1,s2;
    s1=arg[0];
    s2=arg[1];
    x=Integer.parseInt(s1);
    y=Integer.parseInt(s2);
    obj1.add(x,y);
    }
    }




3. Use of array in java
Coding:
class Person
{
String name[];
int age[];
}
class PersonMain
{
public static void main(String arg[])
{


Person obj=new Person();


obj.name=new String[6];
obj.age=new int[6];
obj.name[0]="Neha";
obj.age[0]=19;


obj.name[1]="manpreet";
obj.age[1]=19;


obj.name[2]="rahul";
obj.age[2]=23;


obj.name[3]="yuvraj";
obj.age[3]=12;


obj.name[4]="kombe";
obj.age[4]=19;


obj.name[5]="tony";
obj.age[5]=19;
for(int i=0;i<4;i++)
System.out.println(obj.name[i]);
{
for(int j=0;j<4;j++)
System.out.println(obj.age[j]);
}
}
}




4. Create a class customer having three attributes name, bill and id. Include appropriate
     methods for taking input from customer and displaying its values
Coding: import java.io.DataInputStream;
class Customer
{
public static void main(String arf[])
{
DataInputStream myinput=new DataInputStream(System.in);
String name;
 int bill=0,id=0;
try
{
System.out.println("enter name of customer");
name=myinput.readLine();

System.out.println("enter bill");
bill=Integer.parseInt(myinput.readLine());

System.out.println("enter id");
id=Integer.parseInt(myinput.readLine());
System.out.println("name of customer is"+name);
System.out.println("bill of customer"+bill);
System.out.println("id of customer"+id);
}
catch(Exception e)
{
System.out.println("wrong input error!!!");
}
}
}




5. To show the concept of method overloading
   Coding:

   class Addition//FUNCTION OVERLOADING

   {

   public int add(int a,int b)

   {

   int c=a+b;

   return (c);

   }

   public float add(float a,float b)

   {

   float c=a+b;

   return (c);
}

   public double add(double a,double b)

   {

   double c=a+b;

   return (c);

   }

   }

   class AddMain

   {

   public static void main(String arg[])

   {

   Addition obj=new Addition();

   System.out.println(obj.add(20,30));

   System.out.println(obj.add(100.44f,20.54f));

   System.out.println(obj.add(1380.544,473.56784));

   }

   }




6. To count no. of object created of a class
   class Demo//OBJECT CREATION

   {

   private static int count=0;

   public Demo()
{

   System.out.println("i am from demo");

   count++;

   System.out.println("object created is"+count);

   }

   }

   class DemoMains

   {

   public static void main(String args[])

   {

   Demo obj1=new Demo();

   Demo obj2=new Demo();

   Demo obj3=new Demo();



   }

   }




7. To show concept of multilevel inheritance
   Coding:
   class A
   {
   private int num1,num2,sum;
   public void set(int x,int y)
   {
num1=x;
num2=y;
sum=num1+num2;
}
public int get1()
{
return(sum);
}
}
class B extends A
{
public void display()
{
System.out.println("sum of two numbers is"+get1());
}
}
class C extends B
{
private double sqr;
public void sqrs()
{
sqr=java.lang.Math.sqrt(get1());
System.out.println("square root of sum is"+sqr);
}
}
class ABCMain
{
public static void main(String args[])
{
C obj1=new C();
obj1.set(100,200);
System.out.println("first number is 100");
System.out.println("second number is 200");
obj1.display();
obj1.sqrs();
}
}
8.           To show concept of method overriding
Coding:

class Demo

{

private static int count=0;

public Demo()

{

System.out.println("i am from demo");

count++;

System.out.println("object created is"+count);

}

public String toString()

{

return("method overridding");

}

}

class MethodOverride

{

public static void main(String args[])

{

Demo obj1=new Demo();

Demo obj2=new Demo();

Demo obj3=new Demo();
System.out.println("overriding toString methodnnttoverriden message=: "+obj1.toString());

}

}




    9. Create a class that will at least import two packages and use the method defined in the
       classes of those packages.
       Coding:
       MyApplet.java:
        import java.awt.*;
       import java.applet.*;
       public class MyApplet extends Applet
       {
       public void paint(Graphics g)
       {

       g.drawLine(400,100,100,400);
       }
       }
       Ex1.html:
       <applet code="MyApplet.class"
       height="600"
       width="800"
       >
       </applet>
10. To create thread by extending thread class
    Coding:
    class T1 extends Thread
    {
    public void run()
    {
    for(int i=0;i<5;i++)
    {
    System.out.println("thread 1 created");
    }
    }
    }
    class T2 extends Thread
    {
    public void run()
    {
    for(int i=0;i<5;i++)
    {
    System.out.println("thread 2 created");
    }
    }
    }
    class TMain
    {
    public static void main(String arg[])
    {
    T1 obj1=new T1();
    obj1.start();

   T2 obj2=new T2();
   obj2.start();
   }
   }
11. Create thread by implementing runnable interface
    Coding:
    class T1 implements Runnable
    {
    public void run()
    {
    for(int i=0;i<5;i++)
    {
    System.out.println("thread 1 created");
    }
    }
    }
    class T2 implements Runnable
    {
    public void run()
    {
    for(int i=0;i<5;i++)
    {
    System.out.println("thread 2 created");
    }
    }
    }
    class RMain
    {
    public static void main(String arg[])
    {
    T1 obj1=new T1();
    Thread t1=new Thread(obj1);
    T2 obj2=new T2();
    Thread t2=new Thread(obj2);
    t1.start();
    t2.start();
}
   }




12. To create user defined exception
    class InvalidRollno extends Exception

   {

   String msg;

   public InvalidRollno()

   {

   }

   public InvalidRollno(String m)

   {

   msg=m;

   }

   public String toString()

   {

   return(msg);

   }

   }
class Student

{

private int rollno;

public void setStudent(int r) throws InvalidRollno

{

rollno=r;

if(r<1)

{

throw new InvalidRollno("invalid rollno");

}

}

}

class SMain

{

public static void main(String agf[])

{

Student obj1=new Student();

try

{

obj1.setStudent(-11);

}

catch(InvalidRollno e)

{

System.out.println(e);

}
}

          }




13. Program for showing the concept of sleep method in multithreading.

    public class DelayExample{

    public static void main(String[] args)

{

    System.out.println("Hi");

    for (int i = 0; i < 10; i++)

    {

    System.out.println("Number of itartion = " + i);

    System.out.println("Wait:");

    try

    {
Thread.sleep(4000);

    }

catch (InterruptedException ie)

 {

 System.out.println(ie.getMessage());

}}}




14. Program to demonstrate a basic applet.

import java.awt.*;

import java.applet.*;

/*

<applet code="sim" width=300 height=300>

</applet>

*/

public class sim extends Applet

{

String msg=" ";

public void init()
{

msg+="init()--->";

setBackground(Color.orange);

}

public void start()

{

msg+="start()--->";

setForeground(Color.blue);

}

public void paint(Graphics g)

{

msg+="paint()--->";

g.drawString(msg,200,50);

}}




15. Program for drawing various shapes on applets.

import java.awt.*;

import java.applet.*;

/*
<applet code="Sujith" width=200 height=200>

</applet>

*/

public class Sujith extends Applet

{

public void paint(Graphics g)

{

for(int i=0;i<=250;i++)

{

Color c1=new Color(35-i,55-i,110-i);

g.setColor(c1);

g.drawRect(250+i,250+i,100+i,100+i);

g.drawOval(100+i,100+i,50+i,50+i);

g.drawLine(50+i,20+i,10+i,10+i);

}

}

}
16. Program for filling various objects with colours.

import java.awt.*;

public class GradientPaintExample extends ShapeExample {

private GradientPaint gradient =

new GradientPaint(0, 0, Color.red, 175, 175, Color.yellow,

true);

public void paintComponent(Graphics g)

{

clear(g)

Graphics2D g2d = (Graphics2D)g;

drawGradientCircle(g2d);

}

protected void drawGradientCircle(Graphics2D g2d)
g2d.setPaint(gradient);

g2d.fill(getCircle());

g2d.setPaint(Color.black);

g2d.draw(getCircle());

 }

public static void main(String[] args) {

WindowUtilities.openInJFrame(new GradientPaintExample(),

380, 400);

 }




17. Program of an applet which respond to mouse motion listener interface method.

import javax.swing.*;

import java.awt.Color;
import java.awt.FlowLayout;

import java.awt.Graphics;

import java.awt.Container;

import java.awt.event.*;

public class MovingMessage

{

public static void main (String[] s)

{ HelloJava f = new HelloJava();}

}

class HelloJava extends JFrame implements MouseMotionListener, ActionListener

{

int messageX = 25, messageY = 100;

String theMessage;

JButton theButton;

int colorIndex = 0;

static Color[] someColors = { Color.black, Color.red,Color.green, Color.blue, Color.magenta };

HelloJava()

{

theMessage = "Dragging Message";

setSize(300, 200);

Container contentPane = getContentPane();

contentPane.setLayout(new FlowLayout());

theButton = new JButton("Change Color");

contentPane.add(theButton);

theButton.addActionListener(this);
addMouseMotionListener(this);

setVisible(true);

}

private void changeColor()

{

if (++colorIndex == someColors.length)

colorIndex = 0;

setForeground(currentColor());

repaint();

}

private Color currentColor()

{ return someColors[colorIndex]; }

public void paint(Graphics g)

{

super.paint(g);

g.drawString(theMessage, messageX, messageY);

}

public void mouseDragged(MouseEvent e)

{

messageX = e.getX();

messageY = e.getY();

repaint();

}

public void mouseMoved(MouseEvent e) { }

public void actionPerformed(ActionEvent e)
{

if (e.getSource() == theButton)

changeColor();

}

}




18. Program of an applet which uses the various methods defined in the key listener
interface.

import java.awt.*;

import java.awt.event.*;

public class KeyListenerTester extends Frame implements KeyListener{

TextField t1;

Label l1;

public KeyListenerTester(String s ) {

super(s);

Panel p =new Panel();

l1 = new Label ("Key Listener!" ) ;

p.add(l1);

add(p);

addKeyListener ( this ) ;
setSize ( 200,100 );

setVisible(true);

addWindowListener(new WindowAdapter(){

public void windowClosing(WindowEvent e){

System.exit(0);

}

});

}

public void keyTyped ( KeyEvent e ){

l1.setText("Key Typed");

}

public void keyPressed ( KeyEvent e){

l1.setText ( "Key Pressed" ) ;

}

public void keyReleased ( KeyEvent e ){

l1.setText( "Key Released" ) ;

}

public static void main (String[]args ){

new KeyListenerTester ( "Key Listener Tester" ) ;

}

}
19. program to change the background colour of applet by clicking on command button.

import java.applet.Applet;

import java.awt.Button;

import java.awt.Color;

public class ChangeButtonBackgroundExample extends Applet{

public void init()

{

Button button1 = new Button("Button 1");

Button button2 = new Button("Button 2");

button1.setBackground(Color.red);

button2.setBackground(Color.green);

add(button1);

add(button2);

}

}
20. Program of an applet that will demonstrate a basic calculator.

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

import javax.swing.event.*;

class Calculator extends JFrame {

private final Font BIGGER_FONT = new Font("monspaced",

Font.PLAIN, 20);

private JTextField textfield;

private boolean number = true;

private String equalOp = "=";

private CalculatorOp op = new CalculatorOp();

public Calculator() {

textfield = new JTextField("0", 12);

textfield.setHorizontalAlignment(JTextField.RIGHT);
textfield.setFont(BIGGER_FONT);

ActionListener numberListener = new NumberListener();

String buttonOrder = "1234567890 ";

JPanel buttonPanel = new JPanel();

buttonPanel.setLayout(new GridLayout(4, 4, 4, 4));

for (int i = 0; i < buttonOrder.length(); i++) {

String key = buttonOrder.substring(i, i+1);

if (key.equals(" ")) {

buttonPanel.add(new JLabel(""));

} else {

JButton button = new JButton(key);

button.addActionListener(numberListener);

button.setFont(BIGGER_FONT);

buttonPanel.add(button);

}

}

ActionListener operatorListener = new OperatorListener();

JPanel panel = new JPanel();

panel.setLayout(new GridLayout(4, 4, 4, 4));

String[] opOrder = {"+", "-", "*", "/","=","C"};

for (int i = 0; i < opOrder.length; i++) {

JButton button = new JButton(opOrder[i]);

button.addActionListener(operatorListener);

button.setFont(BIGGER_FONT);

panel.add(button);
}

JPanel pan = new JPanel();

pan.setLayout(new BorderLayout(4, 4));

pan.add(textfield, BorderLayout.NORTH );

pan.add(buttonPanel , BorderLayout.CENTER);

pan.add(panel , BorderLayout.EAST );

this.setContentPane(pan);

this.pack();

this.setTitle("Calculator");

this.setResizable(false);

}

private void action() {

number = true;

textfield.setText("0");

equalOp = "=";

op.setTotal("0");

}

class OperatorListener implements ActionListener {

public void actionPerformed(ActionEvent e) {

if (number) {

action();

textfield.setText("0");

} else {

number = true;

String displayText = textfield.getText();
if (equalOp.equals("=")) {

op.setTotal(displayText);

} else if (equalOp.equals("+")) {

op.add(displayText);

} else if (equalOp.equals("-")) {

op.subtract(displayText);

} else if (equalOp.equals("*")) {

op.multiply(displayText);

} else if (equalOp.equals("/")) {

op.divide(displayText);

}

textfield.setText("" + op.getTotalString());

equalOp = e.getActionCommand();

}

}

}

class NumberListener implements ActionListener {

public void actionPerformed(ActionEvent event) {

String digit = event.getActionCommand();

if (number) {

textfield.setText(digit);

number = false;

} else {

textfield.setText(textfield.getText() + digit);

}
}

}

public class CalculatorOp {

private int total;

public CalculatorOp() {

total = 0;

}

public String getTotalString() {

return ""+total;

}

public void setTotal(String n) {

total = convertToNumber(n);

}

public void add(String n) {

total += convertToNumber(n);

}

public void subtract(String n) {

total -= convertToNumber(n);

}

public void multiply(String n) {

total *= convertToNumber(n);

}

public void divide(String n) {

total /= convertToNumber(n);

}
private int convertToNumber(String n) {

return Integer.parseInt(n);

}

}

}




21. Program for showing the use of various method of URL class.

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.net.MalformedURLException;

import java.net.URL;

public class GetURL {

static protected void getURL(String u) {

URL url;

InputStream is;

InputStreamReader isr;

BufferedReader r;
String str;

try {

System.out.println("Reading URL: " + u);

url = new URL(u);

is = url.openStream();

isr = new InputStreamReader(is);

r = new BufferedReader(isr);

do {

str = r.readLine();

if (str != null)

System.out.println(str);

} while (str != null);

} catch (MalformedURLException e) {

System.out.println("Must enter a valid URL");

} catch (IOException e) {

System.out.println("Can not connect");

}

}

static public void main(String args[]) {

if (args.length < 1)

System.out.println("Usage: GetURL ");

else

getURL(args[0]);

}

}
22. Program to print concentric circles

import java.awt.*;

import java.applet.*;

import java.util.*;



public class c_cir extends Applet

{

public void paint(Graphics g)

{

Random rg = new Random();



for (int i=1; i<=3; i++)

{

int r = rg.nextInt(255);

int gr = rg.nextInt(255);

int b = rg.nextInt(255);

Color c = new Color(r,gr,b);

g.setColor(c);
g.fillOval(100+i*5,100+i*5,100-i*10,100-i*10);

}

}

}




23. Program to illustrate the use of methods of vector class

import java.util.*;
class vvect
{
        public static void main(String a[])
        {
Vector a1 = new Vector();

                 int l = a.length;
                 int i;
                 for(i=0;i<l;i++)
                 {
                          a1.addElement(a[i]);
                 }
                 a1.insertElementAt("Vatan",2);
                 int s = a1.size();
                 String r[] = new String[s];
                 a1.copyInto(r);
                 System.out.println("n Different Font Styles:n");
                 for(i=0;i<s;i++)
                 {
                          System.out.println(r[i]);
                 }
       }
}




24. Program for showing the use ‘for’ in each statement.

package loops;

public class Forloops

{

public static void main(string[] args) {

int loopval;
int end_value=11;

for (loopval=0; loopval<end_value;loopval++) {

system.out.printin("loop value="+ loopval);

}

}

}




25. Program for showing a use of jdp programming in java.

import java.lang.*;
import java.sql.*;
class bca
{
public static void main(String arg[]) throws Exception
{
        String stdrollno,stdname,stdclass;
        Connection conn;
Statement stmt;
    ResultSet rs;
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    conn=DriverManager.getConnection("jdbc:odbc:pctedsn","bca","bca");

    stmt=conn.createStatement();
    rs=stmt.executeQuery("select id,stdname,class from try");

    System.out.println("Roll No Student Name Class");

    while(rs.next())
    {

    stdclass = rs.getString(1);
    stdname = rs.getString(2);
    stdrollno = rs.getString(3);

    System.out.println(stdrollno+"      "+stdname+" "+stdclass);

    }

    //stmt.close();
    //rs.close();
}
}

More Related Content

What's hot

Java 8 - CJ
Java 8 - CJJava 8 - CJ
Java 8 - CJ
Sunil OS
 
C# Loops
C# LoopsC# Loops
C# Loops
Hock Leng PUAH
 
Java Methods
Java MethodsJava Methods
Java MethodsOXUS 20
 
Exception Handling
Exception HandlingException Handling
Exception Handling
Sunil OS
 
C++
C++C++
Java Foundations: Objects and Classes
Java Foundations: Objects and ClassesJava Foundations: Objects and Classes
Java Foundations: Objects and Classes
Svetlin Nakov
 
Java IO Streams V4
Java IO Streams V4Java IO Streams V4
Java IO Streams V4
Sunil OS
 
Data Structures Using C Practical File
Data Structures Using C Practical File Data Structures Using C Practical File
Data Structures Using C Practical File
Rahul Chugh
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
Hamid Ghorbani
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/Servlet
Sunil OS
 
Java Fundamentals
Java FundamentalsJava Fundamentals
Java Fundamentals
Shalabh Chaudhary
 
A Basic Django Introduction
A Basic Django IntroductionA Basic Django Introduction
A Basic Django IntroductionGanga Ram
 
Constructors in C++
Constructors in C++Constructors in C++
Constructors in C++
RubaNagarajan
 
Unary operator overloading
Unary operator overloadingUnary operator overloading
Unary operator overloading
Md. Ashraful Islam
 
Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File Handling
Sunil OS
 
Java multi threading
Java multi threadingJava multi threading
Java multi threading
Raja Sekhar
 
Arrays in Java | Edureka
Arrays in Java | EdurekaArrays in Java | Edureka
Arrays in Java | Edureka
Edureka!
 
Java Basics
Java BasicsJava Basics
Java Basics
Sunil OS
 
Java Programming
Java ProgrammingJava Programming
Java Programming
Anjan Mahanta
 

What's hot (20)

Java 8 - CJ
Java 8 - CJJava 8 - CJ
Java 8 - CJ
 
Java programming-examples
Java programming-examplesJava programming-examples
Java programming-examples
 
C# Loops
C# LoopsC# Loops
C# Loops
 
Java Methods
Java MethodsJava Methods
Java Methods
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
C++
C++C++
C++
 
Java Foundations: Objects and Classes
Java Foundations: Objects and ClassesJava Foundations: Objects and Classes
Java Foundations: Objects and Classes
 
Java IO Streams V4
Java IO Streams V4Java IO Streams V4
Java IO Streams V4
 
Data Structures Using C Practical File
Data Structures Using C Practical File Data Structures Using C Practical File
Data Structures Using C Practical File
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/Servlet
 
Java Fundamentals
Java FundamentalsJava Fundamentals
Java Fundamentals
 
A Basic Django Introduction
A Basic Django IntroductionA Basic Django Introduction
A Basic Django Introduction
 
Constructors in C++
Constructors in C++Constructors in C++
Constructors in C++
 
Unary operator overloading
Unary operator overloadingUnary operator overloading
Unary operator overloading
 
Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File Handling
 
Java multi threading
Java multi threadingJava multi threading
Java multi threading
 
Arrays in Java | Edureka
Arrays in Java | EdurekaArrays in Java | Edureka
Arrays in Java | Edureka
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Java Programming
Java ProgrammingJava Programming
Java Programming
 

Viewers also liked

Java PRACTICAL file
Java PRACTICAL fileJava PRACTICAL file
Java PRACTICAL file
RACHIT_GUPTA
 
Advanced Java Practical File
Advanced Java Practical FileAdvanced Java Practical File
Advanced Java Practical FileSoumya Behera
 
Most Asked Java Interview Question and Answer
Most Asked Java Interview Question and AnswerMost Asked Java Interview Question and Answer
Most Asked Java Interview Question and Answer
TOPS Technologies
 
Java codes
Java codesJava codes
Java codes
Hussain Sherwani
 
Basic java important interview questions and answers to secure a job
Basic java important interview questions and answers to secure a jobBasic java important interview questions and answers to secure a job
Basic java important interview questions and answers to secure a job
Garuda Trainings
 
Interview questions(programming)
Interview questions(programming)Interview questions(programming)
Interview questions(programming)
sunilbhaisora1
 
Classical programming interview questions
Classical programming interview questionsClassical programming interview questions
Classical programming interview questions
Gradeup
 
Bank account in java
Bank account in javaBank account in java
Bank account in java
Programming Homework Help
 
Java classes and objects interview questions
Java classes and objects interview questionsJava classes and objects interview questions
Java classes and objects interview questionsDhivyashree Selvarajtnkpm
 
Bank management system with java
Bank management system with java Bank management system with java
Bank management system with java
Neha Bhagat
 
20 most important java programming interview questions
20 most important java programming interview questions20 most important java programming interview questions
20 most important java programming interview questions
Gradeup
 
Java Code for Sample Projects Inheritance
Java Code for Sample Projects InheritanceJava Code for Sample Projects Inheritance
Java Code for Sample Projects Inheritancejwjablonski
 
Java questions for viva
Java questions for vivaJava questions for viva
Java questions for viva
Vipul Naik
 
31911477 internet-banking-project-documentation
31911477 internet-banking-project-documentation31911477 internet-banking-project-documentation
31911477 internet-banking-project-documentationSwaroop Mane
 
Brochure rafael velásquez
Brochure rafael velásquezBrochure rafael velásquez
Brochure rafael velásquez
rafaelhvv
 
Mgceu presentation
Mgceu presentationMgceu presentation
Mgceu presentationOlena Ursu
 
Cushion Butterfield Collection - February 2015
Cushion Butterfield Collection - February 2015Cushion Butterfield Collection - February 2015
Cushion Butterfield Collection - February 2015
Steve Wilkinson
 
Smart practices rev
Smart practices   revSmart practices   rev
Smart practices revOlena Ursu
 
Literatura catalana de postguerra
Literatura catalana de postguerraLiteratura catalana de postguerra
Literatura catalana de postguerraIgnacio Martinez
 
Bawse Legacy 2.4
Bawse Legacy 2.4Bawse Legacy 2.4
Bawse Legacy 2.4
ChanPear
 

Viewers also liked (20)

Java PRACTICAL file
Java PRACTICAL fileJava PRACTICAL file
Java PRACTICAL file
 
Advanced Java Practical File
Advanced Java Practical FileAdvanced Java Practical File
Advanced Java Practical File
 
Most Asked Java Interview Question and Answer
Most Asked Java Interview Question and AnswerMost Asked Java Interview Question and Answer
Most Asked Java Interview Question and Answer
 
Java codes
Java codesJava codes
Java codes
 
Basic java important interview questions and answers to secure a job
Basic java important interview questions and answers to secure a jobBasic java important interview questions and answers to secure a job
Basic java important interview questions and answers to secure a job
 
Interview questions(programming)
Interview questions(programming)Interview questions(programming)
Interview questions(programming)
 
Classical programming interview questions
Classical programming interview questionsClassical programming interview questions
Classical programming interview questions
 
Bank account in java
Bank account in javaBank account in java
Bank account in java
 
Java classes and objects interview questions
Java classes and objects interview questionsJava classes and objects interview questions
Java classes and objects interview questions
 
Bank management system with java
Bank management system with java Bank management system with java
Bank management system with java
 
20 most important java programming interview questions
20 most important java programming interview questions20 most important java programming interview questions
20 most important java programming interview questions
 
Java Code for Sample Projects Inheritance
Java Code for Sample Projects InheritanceJava Code for Sample Projects Inheritance
Java Code for Sample Projects Inheritance
 
Java questions for viva
Java questions for vivaJava questions for viva
Java questions for viva
 
31911477 internet-banking-project-documentation
31911477 internet-banking-project-documentation31911477 internet-banking-project-documentation
31911477 internet-banking-project-documentation
 
Brochure rafael velásquez
Brochure rafael velásquezBrochure rafael velásquez
Brochure rafael velásquez
 
Mgceu presentation
Mgceu presentationMgceu presentation
Mgceu presentation
 
Cushion Butterfield Collection - February 2015
Cushion Butterfield Collection - February 2015Cushion Butterfield Collection - February 2015
Cushion Butterfield Collection - February 2015
 
Smart practices rev
Smart practices   revSmart practices   rev
Smart practices rev
 
Literatura catalana de postguerra
Literatura catalana de postguerraLiteratura catalana de postguerra
Literatura catalana de postguerra
 
Bawse Legacy 2.4
Bawse Legacy 2.4Bawse Legacy 2.4
Bawse Legacy 2.4
 

Similar to Java practical

Core java pract_sem iii
Core java pract_sem iiiCore java pract_sem iii
Core java pract_sem iii
Niraj Bharambe
 
Java practical
Java practicalJava practical
Java practical
william otto
 
Java Simple Programs
Java Simple ProgramsJava Simple Programs
Java Simple Programs
Upender Upr
 
Java file
Java fileJava file
Java file
simarsimmygrewal
 
Java Programs
Java ProgramsJava Programs
Java Programs
vvpadhu
 
Java oops features
Java oops featuresJava oops features
Java oops features
VigneshManikandan11
 
Problem1 java codeimport java.util.Scanner; Java code to pr.pdf
 Problem1 java codeimport java.util.Scanner; Java code to pr.pdf Problem1 java codeimport java.util.Scanner; Java code to pr.pdf
Problem1 java codeimport java.util.Scanner; Java code to pr.pdf
anupamfootwear
 
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...
Ayes Chinmay
 
Advanced Java - Practical File
Advanced Java - Practical FileAdvanced Java - Practical File
Advanced Java - Practical File
Fahad Shaikh
 
Java programming lab_manual_by_rohit_jaiswar
Java programming lab_manual_by_rohit_jaiswarJava programming lab_manual_by_rohit_jaiswar
Java programming lab_manual_by_rohit_jaiswar
ROHIT JAISWAR
 
JAVAPGMS.docx
JAVAPGMS.docxJAVAPGMS.docx
JAVAPGMS.docx
Mgm Mallikarjun
 
Java and j2ee_lab-manual
Java and j2ee_lab-manualJava and j2ee_lab-manual
Java and j2ee_lab-manual
hanumanthu mothukuru
 
Object Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsObject Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ Exams
MuhammadTalha436
 
Java practice programs for beginners
Java practice programs for beginnersJava practice programs for beginners
Java practice programs for beginners
ishan0019
 

Similar to Java practical (20)

Core java pract_sem iii
Core java pract_sem iiiCore java pract_sem iii
Core java pract_sem iii
 
Java practical
Java practicalJava practical
Java practical
 
Java Simple Programs
Java Simple ProgramsJava Simple Programs
Java Simple Programs
 
Java file
Java fileJava file
Java file
 
Java file
Java fileJava file
Java file
 
Java Programs
Java ProgramsJava Programs
Java Programs
 
Java oops features
Java oops featuresJava oops features
Java oops features
 
Problem1 java codeimport java.util.Scanner; Java code to pr.pdf
 Problem1 java codeimport java.util.Scanner; Java code to pr.pdf Problem1 java codeimport java.util.Scanner; Java code to pr.pdf
Problem1 java codeimport java.util.Scanner; Java code to pr.pdf
 
Awt
AwtAwt
Awt
 
Thread
ThreadThread
Thread
 
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...
 
Advanced Java - Practical File
Advanced Java - Practical FileAdvanced Java - Practical File
Advanced Java - Practical File
 
Java programming lab_manual_by_rohit_jaiswar
Java programming lab_manual_by_rohit_jaiswarJava programming lab_manual_by_rohit_jaiswar
Java programming lab_manual_by_rohit_jaiswar
 
JAVAPGMS.docx
JAVAPGMS.docxJAVAPGMS.docx
JAVAPGMS.docx
 
Java and j2ee_lab-manual
Java and j2ee_lab-manualJava and j2ee_lab-manual
Java and j2ee_lab-manual
 
Object Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsObject Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ Exams
 
Sam wd programs
Sam wd programsSam wd programs
Sam wd programs
 
54240326 (1)
54240326 (1)54240326 (1)
54240326 (1)
 
54240326 copy
54240326   copy54240326   copy
54240326 copy
 
Java practice programs for beginners
Java practice programs for beginnersJava practice programs for beginners
Java practice programs for beginners
 

More from shweta-sharma99 (13)

Biometrics
BiometricsBiometrics
Biometrics
 
Biometrics
BiometricsBiometrics
Biometrics
 
Testing
TestingTesting
Testing
 
Sql commands
Sql commandsSql commands
Sql commands
 
Rep on grid computing
Rep on grid computingRep on grid computing
Rep on grid computing
 
Graphics file
Graphics fileGraphics file
Graphics file
 
Vbreport
VbreportVbreport
Vbreport
 
Software re engineering
Software re engineeringSoftware re engineering
Software re engineering
 
Simplex
SimplexSimplex
Simplex
 
Grid computing
Grid computingGrid computing
Grid computing
 
Cyborg
CyborgCyborg
Cyborg
 
Smartphone
SmartphoneSmartphone
Smartphone
 
Instruction cycle
Instruction cycleInstruction cycle
Instruction cycle
 

Recently uploaded

PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
g2nightmarescribd
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
Product School
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
DianaGray10
 

Recently uploaded (20)

PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 

Java practical

  • 1. 1. Program to generate Fibonacci series import java.io.*; import java.util.*; public class Fibonacci { public static void main(String[] args) { DataInputStream reader = new DataInputStream((System.in)); int f1=0,f2=0,f3=1; try { System.out.print("Enter value of n: "); String st = reader.readLine(); int num = Integer.parseInt(st); for(int i=1;i<=num;i++) { System.out.println("tt"+f3+"tnt"); f1=f2; f2=f3; f3=f1+f2; } } catch(Exception e) { System.out.println("wrong input"); } } } 2. Program to take two numbers as input from command line interface and display their sum
  • 2. Coding: class Sum { public void add(int a,int b) { int c; c=a+b; System.out.print("tttnnThe sum of two no is = "+c); System.out.println("nnn"); } } class SMain { public static void main(String arg[]) { Sum obj1=new Sum(); int x,y; String s1,s2; s1=arg[0]; s2=arg[1]; x=Integer.parseInt(s1); y=Integer.parseInt(s2); obj1.add(x,y); } } 3. Use of array in java Coding: class Person { String name[]; int age[]; }
  • 3. class PersonMain { public static void main(String arg[]) { Person obj=new Person(); obj.name=new String[6]; obj.age=new int[6]; obj.name[0]="Neha"; obj.age[0]=19; obj.name[1]="manpreet"; obj.age[1]=19; obj.name[2]="rahul"; obj.age[2]=23; obj.name[3]="yuvraj"; obj.age[3]=12; obj.name[4]="kombe"; obj.age[4]=19; obj.name[5]="tony"; obj.age[5]=19;
  • 4. for(int i=0;i<4;i++) System.out.println(obj.name[i]); { for(int j=0;j<4;j++) System.out.println(obj.age[j]); } } } 4. Create a class customer having three attributes name, bill and id. Include appropriate methods for taking input from customer and displaying its values Coding: import java.io.DataInputStream; class Customer { public static void main(String arf[]) { DataInputStream myinput=new DataInputStream(System.in); String name; int bill=0,id=0; try { System.out.println("enter name of customer"); name=myinput.readLine(); System.out.println("enter bill"); bill=Integer.parseInt(myinput.readLine()); System.out.println("enter id"); id=Integer.parseInt(myinput.readLine());
  • 5. System.out.println("name of customer is"+name); System.out.println("bill of customer"+bill); System.out.println("id of customer"+id); } catch(Exception e) { System.out.println("wrong input error!!!"); } } } 5. To show the concept of method overloading Coding: class Addition//FUNCTION OVERLOADING { public int add(int a,int b) { int c=a+b; return (c); } public float add(float a,float b) { float c=a+b; return (c);
  • 6. } public double add(double a,double b) { double c=a+b; return (c); } } class AddMain { public static void main(String arg[]) { Addition obj=new Addition(); System.out.println(obj.add(20,30)); System.out.println(obj.add(100.44f,20.54f)); System.out.println(obj.add(1380.544,473.56784)); } } 6. To count no. of object created of a class class Demo//OBJECT CREATION { private static int count=0; public Demo()
  • 7. { System.out.println("i am from demo"); count++; System.out.println("object created is"+count); } } class DemoMains { public static void main(String args[]) { Demo obj1=new Demo(); Demo obj2=new Demo(); Demo obj3=new Demo(); } } 7. To show concept of multilevel inheritance Coding: class A { private int num1,num2,sum; public void set(int x,int y) {
  • 8. num1=x; num2=y; sum=num1+num2; } public int get1() { return(sum); } } class B extends A { public void display() { System.out.println("sum of two numbers is"+get1()); } } class C extends B { private double sqr; public void sqrs() { sqr=java.lang.Math.sqrt(get1()); System.out.println("square root of sum is"+sqr); } } class ABCMain { public static void main(String args[]) { C obj1=new C(); obj1.set(100,200); System.out.println("first number is 100"); System.out.println("second number is 200"); obj1.display(); obj1.sqrs(); } }
  • 9. 8. To show concept of method overriding Coding: class Demo { private static int count=0; public Demo() { System.out.println("i am from demo"); count++; System.out.println("object created is"+count); } public String toString() { return("method overridding"); } } class MethodOverride { public static void main(String args[]) { Demo obj1=new Demo(); Demo obj2=new Demo(); Demo obj3=new Demo();
  • 10. System.out.println("overriding toString methodnnttoverriden message=: "+obj1.toString()); } } 9. Create a class that will at least import two packages and use the method defined in the classes of those packages. Coding: MyApplet.java: import java.awt.*; import java.applet.*; public class MyApplet extends Applet { public void paint(Graphics g) { g.drawLine(400,100,100,400); } } Ex1.html: <applet code="MyApplet.class" height="600" width="800" > </applet>
  • 11. 10. To create thread by extending thread class Coding: class T1 extends Thread { public void run() { for(int i=0;i<5;i++) { System.out.println("thread 1 created"); } } } class T2 extends Thread { public void run() { for(int i=0;i<5;i++) { System.out.println("thread 2 created"); } } } class TMain { public static void main(String arg[]) { T1 obj1=new T1(); obj1.start(); T2 obj2=new T2(); obj2.start(); } }
  • 12. 11. Create thread by implementing runnable interface Coding: class T1 implements Runnable { public void run() { for(int i=0;i<5;i++) { System.out.println("thread 1 created"); } } } class T2 implements Runnable { public void run() { for(int i=0;i<5;i++) { System.out.println("thread 2 created"); } } } class RMain { public static void main(String arg[]) { T1 obj1=new T1(); Thread t1=new Thread(obj1); T2 obj2=new T2(); Thread t2=new Thread(obj2); t1.start(); t2.start();
  • 13. } } 12. To create user defined exception class InvalidRollno extends Exception { String msg; public InvalidRollno() { } public InvalidRollno(String m) { msg=m; } public String toString() { return(msg); } }
  • 14. class Student { private int rollno; public void setStudent(int r) throws InvalidRollno { rollno=r; if(r<1) { throw new InvalidRollno("invalid rollno"); } } } class SMain { public static void main(String agf[]) { Student obj1=new Student(); try { obj1.setStudent(-11); } catch(InvalidRollno e) { System.out.println(e); }
  • 15. } } 13. Program for showing the concept of sleep method in multithreading. public class DelayExample{ public static void main(String[] args) { System.out.println("Hi"); for (int i = 0; i < 10; i++) { System.out.println("Number of itartion = " + i); System.out.println("Wait:"); try {
  • 16. Thread.sleep(4000); } catch (InterruptedException ie) { System.out.println(ie.getMessage()); }}} 14. Program to demonstrate a basic applet. import java.awt.*; import java.applet.*; /* <applet code="sim" width=300 height=300> </applet> */ public class sim extends Applet { String msg=" "; public void init()
  • 17. { msg+="init()--->"; setBackground(Color.orange); } public void start() { msg+="start()--->"; setForeground(Color.blue); } public void paint(Graphics g) { msg+="paint()--->"; g.drawString(msg,200,50); }} 15. Program for drawing various shapes on applets. import java.awt.*; import java.applet.*; /*
  • 18. <applet code="Sujith" width=200 height=200> </applet> */ public class Sujith extends Applet { public void paint(Graphics g) { for(int i=0;i<=250;i++) { Color c1=new Color(35-i,55-i,110-i); g.setColor(c1); g.drawRect(250+i,250+i,100+i,100+i); g.drawOval(100+i,100+i,50+i,50+i); g.drawLine(50+i,20+i,10+i,10+i); } } }
  • 19. 16. Program for filling various objects with colours. import java.awt.*; public class GradientPaintExample extends ShapeExample { private GradientPaint gradient = new GradientPaint(0, 0, Color.red, 175, 175, Color.yellow, true); public void paintComponent(Graphics g) { clear(g) Graphics2D g2d = (Graphics2D)g; drawGradientCircle(g2d); } protected void drawGradientCircle(Graphics2D g2d)
  • 20. g2d.setPaint(gradient); g2d.fill(getCircle()); g2d.setPaint(Color.black); g2d.draw(getCircle()); } public static void main(String[] args) { WindowUtilities.openInJFrame(new GradientPaintExample(), 380, 400); } 17. Program of an applet which respond to mouse motion listener interface method. import javax.swing.*; import java.awt.Color;
  • 21. import java.awt.FlowLayout; import java.awt.Graphics; import java.awt.Container; import java.awt.event.*; public class MovingMessage { public static void main (String[] s) { HelloJava f = new HelloJava();} } class HelloJava extends JFrame implements MouseMotionListener, ActionListener { int messageX = 25, messageY = 100; String theMessage; JButton theButton; int colorIndex = 0; static Color[] someColors = { Color.black, Color.red,Color.green, Color.blue, Color.magenta }; HelloJava() { theMessage = "Dragging Message"; setSize(300, 200); Container contentPane = getContentPane(); contentPane.setLayout(new FlowLayout()); theButton = new JButton("Change Color"); contentPane.add(theButton); theButton.addActionListener(this);
  • 22. addMouseMotionListener(this); setVisible(true); } private void changeColor() { if (++colorIndex == someColors.length) colorIndex = 0; setForeground(currentColor()); repaint(); } private Color currentColor() { return someColors[colorIndex]; } public void paint(Graphics g) { super.paint(g); g.drawString(theMessage, messageX, messageY); } public void mouseDragged(MouseEvent e) { messageX = e.getX(); messageY = e.getY(); repaint(); } public void mouseMoved(MouseEvent e) { } public void actionPerformed(ActionEvent e)
  • 23. { if (e.getSource() == theButton) changeColor(); } } 18. Program of an applet which uses the various methods defined in the key listener interface. import java.awt.*; import java.awt.event.*; public class KeyListenerTester extends Frame implements KeyListener{ TextField t1; Label l1; public KeyListenerTester(String s ) { super(s); Panel p =new Panel(); l1 = new Label ("Key Listener!" ) ; p.add(l1); add(p); addKeyListener ( this ) ;
  • 24. setSize ( 200,100 ); setVisible(true); addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e){ System.exit(0); } }); } public void keyTyped ( KeyEvent e ){ l1.setText("Key Typed"); } public void keyPressed ( KeyEvent e){ l1.setText ( "Key Pressed" ) ; } public void keyReleased ( KeyEvent e ){ l1.setText( "Key Released" ) ; } public static void main (String[]args ){ new KeyListenerTester ( "Key Listener Tester" ) ; } }
  • 25. 19. program to change the background colour of applet by clicking on command button. import java.applet.Applet; import java.awt.Button; import java.awt.Color; public class ChangeButtonBackgroundExample extends Applet{ public void init() { Button button1 = new Button("Button 1"); Button button2 = new Button("Button 2"); button1.setBackground(Color.red); button2.setBackground(Color.green); add(button1); add(button2); } }
  • 26. 20. Program of an applet that will demonstrate a basic calculator. import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; class Calculator extends JFrame { private final Font BIGGER_FONT = new Font("monspaced", Font.PLAIN, 20); private JTextField textfield; private boolean number = true; private String equalOp = "="; private CalculatorOp op = new CalculatorOp(); public Calculator() { textfield = new JTextField("0", 12); textfield.setHorizontalAlignment(JTextField.RIGHT);
  • 27. textfield.setFont(BIGGER_FONT); ActionListener numberListener = new NumberListener(); String buttonOrder = "1234567890 "; JPanel buttonPanel = new JPanel(); buttonPanel.setLayout(new GridLayout(4, 4, 4, 4)); for (int i = 0; i < buttonOrder.length(); i++) { String key = buttonOrder.substring(i, i+1); if (key.equals(" ")) { buttonPanel.add(new JLabel("")); } else { JButton button = new JButton(key); button.addActionListener(numberListener); button.setFont(BIGGER_FONT); buttonPanel.add(button); } } ActionListener operatorListener = new OperatorListener(); JPanel panel = new JPanel(); panel.setLayout(new GridLayout(4, 4, 4, 4)); String[] opOrder = {"+", "-", "*", "/","=","C"}; for (int i = 0; i < opOrder.length; i++) { JButton button = new JButton(opOrder[i]); button.addActionListener(operatorListener); button.setFont(BIGGER_FONT); panel.add(button);
  • 28. } JPanel pan = new JPanel(); pan.setLayout(new BorderLayout(4, 4)); pan.add(textfield, BorderLayout.NORTH ); pan.add(buttonPanel , BorderLayout.CENTER); pan.add(panel , BorderLayout.EAST ); this.setContentPane(pan); this.pack(); this.setTitle("Calculator"); this.setResizable(false); } private void action() { number = true; textfield.setText("0"); equalOp = "="; op.setTotal("0"); } class OperatorListener implements ActionListener { public void actionPerformed(ActionEvent e) { if (number) { action(); textfield.setText("0"); } else { number = true; String displayText = textfield.getText();
  • 29. if (equalOp.equals("=")) { op.setTotal(displayText); } else if (equalOp.equals("+")) { op.add(displayText); } else if (equalOp.equals("-")) { op.subtract(displayText); } else if (equalOp.equals("*")) { op.multiply(displayText); } else if (equalOp.equals("/")) { op.divide(displayText); } textfield.setText("" + op.getTotalString()); equalOp = e.getActionCommand(); } } } class NumberListener implements ActionListener { public void actionPerformed(ActionEvent event) { String digit = event.getActionCommand(); if (number) { textfield.setText(digit); number = false; } else { textfield.setText(textfield.getText() + digit); }
  • 30. } } public class CalculatorOp { private int total; public CalculatorOp() { total = 0; } public String getTotalString() { return ""+total; } public void setTotal(String n) { total = convertToNumber(n); } public void add(String n) { total += convertToNumber(n); } public void subtract(String n) { total -= convertToNumber(n); } public void multiply(String n) { total *= convertToNumber(n); } public void divide(String n) { total /= convertToNumber(n); }
  • 31. private int convertToNumber(String n) { return Integer.parseInt(n); } } } 21. Program for showing the use of various method of URL class. import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; public class GetURL { static protected void getURL(String u) { URL url; InputStream is; InputStreamReader isr; BufferedReader r;
  • 32. String str; try { System.out.println("Reading URL: " + u); url = new URL(u); is = url.openStream(); isr = new InputStreamReader(is); r = new BufferedReader(isr); do { str = r.readLine(); if (str != null) System.out.println(str); } while (str != null); } catch (MalformedURLException e) { System.out.println("Must enter a valid URL"); } catch (IOException e) { System.out.println("Can not connect"); } } static public void main(String args[]) { if (args.length < 1) System.out.println("Usage: GetURL "); else getURL(args[0]); } }
  • 33. 22. Program to print concentric circles import java.awt.*; import java.applet.*; import java.util.*; public class c_cir extends Applet { public void paint(Graphics g) { Random rg = new Random(); for (int i=1; i<=3; i++) { int r = rg.nextInt(255); int gr = rg.nextInt(255); int b = rg.nextInt(255); Color c = new Color(r,gr,b); g.setColor(c);
  • 34. g.fillOval(100+i*5,100+i*5,100-i*10,100-i*10); } } } 23. Program to illustrate the use of methods of vector class import java.util.*; class vvect { public static void main(String a[]) {
  • 35. Vector a1 = new Vector(); int l = a.length; int i; for(i=0;i<l;i++) { a1.addElement(a[i]); } a1.insertElementAt("Vatan",2); int s = a1.size(); String r[] = new String[s]; a1.copyInto(r); System.out.println("n Different Font Styles:n"); for(i=0;i<s;i++) { System.out.println(r[i]); } } } 24. Program for showing the use ‘for’ in each statement. package loops; public class Forloops { public static void main(string[] args) { int loopval;
  • 36. int end_value=11; for (loopval=0; loopval<end_value;loopval++) { system.out.printin("loop value="+ loopval); } } } 25. Program for showing a use of jdp programming in java. import java.lang.*; import java.sql.*; class bca { public static void main(String arg[]) throws Exception { String stdrollno,stdname,stdclass; Connection conn;
  • 37. Statement stmt; ResultSet rs; Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); conn=DriverManager.getConnection("jdbc:odbc:pctedsn","bca","bca"); stmt=conn.createStatement(); rs=stmt.executeQuery("select id,stdname,class from try"); System.out.println("Roll No Student Name Class"); while(rs.next()) { stdclass = rs.getString(1); stdname = rs.getString(2); stdrollno = rs.getString(3); System.out.println(stdrollno+" "+stdname+" "+stdclass); } //stmt.close(); //rs.close(); } }