0% found this document useful (0 votes)
75 views

Java Programs

This document contains examples of various Java programming concepts including data types, string manipulation, inheritance, polymorphism, exception handling, interfaces, packages, and multithreading. It demonstrates how to declare and initialize variables of different data types, convert strings to characters, reverse strings, implement single, multilevel, hierarchical and multiple inheritance, method overloading and overriding for polymorphism, handle exceptions like arithmetic and file not found, use interfaces, define packages to organize code, and create multiple threads to run tasks concurrently.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
75 views

Java Programs

This document contains examples of various Java programming concepts including data types, string manipulation, inheritance, polymorphism, exception handling, interfaces, packages, and multithreading. It demonstrates how to declare and initialize variables of different data types, convert strings to characters, reverse strings, implement single, multilevel, hierarchical and multiple inheritance, method overloading and overriding for polymorphism, handle exceptions like arithmetic and file not found, use interfaces, define packages to organize code, and create multiple threads to run tasks concurrently.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

1.

Various Data Types

import java.util.*;
import java.lang.*;
import java.io.*;

class DataTypes{
public static void main(String args[]){
byte byteVar = 5;
short shortVar = 20;
int intVar = 30;
long longVar = 60;
float floatVar = 20;
double doubleVar = 20.123;
boolean booleanVar = true;
char charVar ='W';

System.out.println("Value Of byte Variable is " + byteVar);


System.out.println("Value Of short Variable is " + shortVar);
System.out.println("Value Of int Variable is " + intVar);
System.out.println("Value Of long Variable is " + longVar);
System.out.println("Value Of float Variable is " + floatVar);
System.out.println("Value Of double Variable is " + doubleVar);
System.out.println("Value Of boolean Variable is " + booleanVar);
System.out.println("Value Of char Variable is " + charVar);
}
}

Output:

Value Of byte Variable is 5


Value Of short Variable is 20
Value Of int Variable is 30
Value Of long Variable is 60
Value Of float Variable is 20.0
Value Of double Variable is 20.123
Value Of boolean Variable is true
Value Of char Variable is W

2. Manipulating String

(i) Converting String to Char

import java.util.*;
import java.lang.*;
import java.io.*;

class StringToCharDemo
{
public static void main(String args[])
{
// Using charAt() method
String str = "Hello";
for(int i=0; i<str.length();i++){
char ch = str.charAt(i);
System.out.println("Character at "+i+" Position: "+ch);
}
}
}

Output:
Character at 0 Position: H
Character at 1 Position: e
Character at 2 Position: l
Character at 3 Position: l
Character at 4 Position: o

(ii) Reversing String:

import java.util.*;
import java.lang.*;
import java.io.*;

public class Example


{
public void reverseWordInMyString(String str)
{
/* The split() method of String class splits
* a string in several strings based on the
* delimiter passed as an argument to it
*/
String[] words = str.split(" ");
String reversedString = "";
for (int i = 0; i < words.length; i++)
{
String word = words[i];
String reverseWord = "";
for (int j = word.length()-1; j >= 0; j--)
{
/* The charAt() function returns the character
* at the given position in a string
*/
reverseWord = reverseWord + word.charAt(j);
}
reversedString = reversedString + reverseWord + " ";
}
System.out.println(str);
System.out.println(reversedString);
}
public static void main(String[] args)
{
Example obj = new Example();
obj.reverseWordInMyString("Welcome to BeginnersBook");
obj.reverseWordInMyString("This is an easy Java Program");
}
}
Output:
Welcome to BeginnersBook
emocleW ot kooBsrennigeB
This is an easy Java Program
sihT si na ysae avaJ margorP

3. Various forms of inheritance

(i) Java program to illustrate the concept of single inheritance


import java.util.*;
import java.lang.*;
import java.io.*;

class one
{
public void print_geek()
{
System.out.println("Geeks");
}
}

class two extends one


{
public void print_for()
{
System.out.println("for");
}
}
// Driver class
public class Main
{
public static void main(String[] args)
{
two g = new two();
g.print_geek();
g.print_for();
g.print_geek();
}
}

Output:
Geeks
for
Geeks

(ii) Java program to illustrate the concept of Multilevel inheritance


import java.util.*;
import java.lang.*;
import java.io.*;

class one
{
public void print_geek()
{
System.out.println("Geeks");
}
}

class two extends one


{
public void print_for()
{
System.out.println("for");
}
}

class three extends two


{
public void print_geek()
{
System.out.println("Geeks");
}
}

// Drived class
public class Main
{
public static void main(String[] args)
{
three g = new three();
g.print_geek();
g.print_for();
g.print_geek();
}
}

Output:
Geeks
for
Geeks
(iii) Java program to illustrate the concept of Hierarchical inheritance
import java.util.*;
import java.lang.*;
import java.io.*;

class one
{
public void print_geek()
{
System.out.println("Geeks");
}
}

class two extends one


{
public void print_for()
{
System.out.println("for");
}
}

class three extends one


{
/*............*/
}

// Drived class
public class Main
{
public static void main(String[] args)
{
three g = new three();
g.print_geek();
two t = new two();
t.print_for();
g.print_geek();
}
}

Output:

Geeks
for
Geeks

(iv) Java program to illustrate the concept of Multiple inheritance


import java.util.*;
import java.lang.*;
import java.io.*;
interface one
{
public void print_geek();
}

interface two
{
public void print_for();
}

interface three extends one,two


{
public void print_geek();
}
class child implements three
{
@Override
public void print_geek() {
System.out.println("Geeks");
}

public void print_for()


{
System.out.println("for");
}
}

// Drived class
public class Main
{
public static void main(String[] args)
{
child c = new child();
c.print_geek();
c.print_for();
c.print_geek();
}
}

Output:
Geeks
for
Geeks
4 (i) Polymorphism : Method overloading

import java.util.*;
import java.lang.*;
import java.io.*;

class Rectangle{

public static void printArea(int x,int y){


System.out.println(x*y);
}
public static void printArea(int x){
System.out.println(x*x);
}
public static void printArea(int x,double y){
System.out.println(x*y);
}
public static void printArea(double x){
System.out.println(x*x);
}

public static void main(String[] args){


printArea(2,4);
printArea(2,5.1);
printArea(10);
printArea(2.3);
}
}

Output:
8
10.2
100
5.289999999999999

4 (i) Polymorphism : Method overriding


import java.util.*;
import java.lang.*;
import java.io.*;

class Animals{
public void sound(){
System.out.println("This is parent class.");
}
}
class Dogs extends Animals{
public void sound(){
System.out.println("Dogs bark");
}
}
class Cats extends Animals{
public void sound(){
System.out.println("Cats meow");
}
}
class Monkeys extends Animals{
public void sound(){
System.out.println("Monkeys whoop.");
}
}
class m{
public static void main(String[] args){
Animals d = new Dogs();
Animals c = new Cats();
Animals m = new Monkeys();
d.sound();
c.sound();
m.sound();
}
}

Output:
Dogs bark
Cats meow
Monkeys whoop.

5. Exception Handling

(i) Java program to demonstrate Arithmetic Exception

import java.util.*;
import java.lang.*;
import java.io.*;

class ArithmeticException_Demo
{
public static void main(String args[])
{
try {
int a = 30, b = 0;
int c = a/b; // cannot divide by zero
System.out.println ("Result = " + c);
}
catch(ArithmeticException e) {
System.out.println ("Can't divide a number by 0");
}
}
}
Output:
Can't divide a number by 0

(ii)Java program to demonstrate FileNotFoundException


import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
class File_notFound_Demo {

public static void main(String args[]) {


try {

// Following file does not exist


File file = new File("E://file.txt");

FileReader fr = new FileReader(file);


} catch (FileNotFoundException e) {
System.out.println("File does not exist");
}
}
}

Output:

File does not exist

6. Interfaces
import java.util.*;
import java.lang.*;
import java.io.*;

interface Bank{
float rateOfInterest();
}
class SBI implements Bank{
public float rateOfInterest(){return 9.15f;}
}
class PNB implements Bank{
public float rateOfInterest(){return 9.7f;}
}
class TestInterface2{
public static void main(String[] args){
Bank b=new SBI();
System.out.println("ROI: "+b.rateOfInterest());
}}

Output:

ROI: 9.15
7. Packages

Student.java
package p1;
public class Student
{
int regno;
String name;
public void getdata(int r,String s)
{
regno=r;
name=s;
}
public void putdata()
{
System.out.println("regno = " +regno);
System.out.println("name = " + name);
}

StudentTest.java

import p1.*;
class StudentTest
{
public static void main(String arg[])
{
student s=new student();
s.getdata(123,"xyz");
s.putdata();
}
}

Output:
regno = 123
name = xyz

8. Multithreading

import java.lang.Thread;
class A extends Thread
{
public void run()
{
System.out.println("thread A is sterted:");
for(int i=1;i<=5;i++)
{
System.out.println("\t from thread A:i="+i);
}
System.out.println("exit from thread A:");
}
}
class B extends Thread
{
public void run()
{
System.out.println("thread B is sterted:");
for(int j=1;j<=5;j++)
{
System.out.println("\t from thread B:j="+j);
}
System.out.println("exit from thread B:");
}
}
class C extends Thread
{
public void run()
{
System.out.println("thread C is sterted:");
for(int k=1;k<=5;k++)
{
System.out.println("\t from thread C:k="+k);
}
System.out.println("exit from thread C:");
}
}
class Threadtest
{
public static void main(String arg[])
{
new A().start();
new B().start();
new C().start();
}
}

Output:

thread A is sterted:
thread B is sterted:
thread C is sterted:
from thread A:i=1
from thread B:j=1
from thread C:k=1
from thread A:i=2
from thread B:j=2
from thread C:k=2
from thread A:i=3
from thread B:j=3
from thread C:k=3
from thread A:i=4
from thread B:j=4
from thread C:k=4
from thread A:i=5
from thread B:j=5
from thread C:k=5
exit from thread A:
exit from thread B:
exit from thread C:

9 (i) java program to draw a ellipse using java applets

import java.awt.*;
import javax.swing.*;

public class ellipse extends JApplet {

public void init()


{
// set size
setSize(400, 400);

repaint();
}

// paint the applet


public void paint(Graphics g)
{
// set Color for rectangle
g.setColor(Color.red);

// draw a ellipse
g.drawOval(100, 100, 150, 100);
}
}

Output:
9(ii) Java Program to Draw a rectangle

import java.awt.*;
import javax.swing.*;

public class rectangle extends JApplet {

public void init()


{
// set size
setSize(400, 400);

repaint();
}

// paint the applet


public void paint(Graphics g)
{
// set Color for rectangle
g.setColor(Color.red);

// draw a rectangle
g.drawRect(100, 100, 200, 200);
}
}

Output:
9(iii) Java program to Draw a Smiley using Java Applet
import java.applet.*;
import java.awt.*;

public class Smiley extends Applet {


public void paint(Graphics g)
{

// Oval for face outline


g.drawOval(80, 70, 150, 150);

// Ovals for eyes


// with black color filled
g.setColor(Color.BLACK);
g.fillOval(120, 120, 15, 15);
g.fillOval(170, 120, 15, 15);

// Arc for the smile


g.drawArc(130, 180, 50, 20, 180, 180);
}
}
Output:
9(iv) Handling Mouse Events Using java applet

import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class MouseApplet extends Applet implements MouseListener
{
String msg="Initial Message";
public void init()
{
addMouseListener(this);
}
public void mouseClicked(MouseEvent me)
{
msg = "Mouse Clicked";
repaint();
}
public void mousePressed(MouseEvent me)
{
msg = "Mouse Pressed";
repaint();
}
public void mouseReleased(MouseEvent me)
{
msg = "Mouse Released";
repaint();
}
public void mouseEntered(MouseEvent me)
{
msg = "Mouse Entered";
repaint();
}
public void mouseExited(MouseEvent me)
{
msg = "Mouse Exited";
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,20,20);
}
}
/*
<applet code="MouseApplet" height="300" width="500">
</applet>
*/

Output:

10. (i) Window Based application using Java Swing

import javax.swing.*;
public class HelloWorldSwing {
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Make sure we have nice window decorations.
JFrame.setDefaultLookAndFeelDecorated(true);

//Create and set up the window.


JFrame frame = new JFrame("HelloWorldSwing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Add the ubiquitous "Hello World" label.


JLabel label = new JLabel("Hello World");
frame.getContentPane().add(label);

//Display the window.


frame.pack();
frame.setVisible(true);
}

public static void main(String[] args) {


//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}

Output:

10 (ii) Java program to create a frame using Swings in main().

import javax.swing.*;
public class Swing_example
{
public static void main(String[] args)
{
// creates instance of JFrame
JFrame frame1 = new JFrame();

// creates instance of JButton


JButton button1 = new JButton("click");
JButton button2 = new JButton("again click");

// x axis, y axis, width, height


button1.setBounds(160, 150 ,80, 80);
button2.setBounds(190, 190, 100, 200);

// adds button1 in Frame1


frame1.add(button1);

// adds button2 in Frame1


frame1.add(button2);

// 400 width and 500 height of frame1


frame1.setSize(400, 500) ;

// uses no layout managers


frame1.setLayout(null);

// makes the frame visible


frame1.setVisible(true);
}
}

Output:

You might also like