abstract class Figure // Abstract class
{
double dim1;
double dim2;
Figure(double a, double b)
{
dim1=a;
dim2=b;
}
abstract double area(); // Abstract Method
}
//-----------
class Rectangle extends Figure
{
Rectangle(double a,double b)
{
super(a,b);
}
double area()
{
System.out.println("\nInside Area for Rectangle");
return dim1 * dim2;
}
}
//-----------
class Triangle extends Figure
{
Triangle(double a,double b)
{
super(a,b);
}
double area()
{
System.out.println("Inside Area for Triangle");
return dim1 * dim2/2;
}
}
//----------
class AbstractAreas
{
public static void main(String args[])
{
//Figure f=new Figure(10,10); //illegal now
Rectangle r=new Rectangle(9,5);
Triangle t=new Triangle(10,8);
Figure figref;
figref=r;
System.out.println("Area is "+figref.area());
figref=t;
System.out.println("Area is "+figref.area());
}
}
Output:
Monday, July 2, 2012
Abstract Class and Abstract Method
Overriding: Find the Area of Figures
class Figure
{
double dim1;
double dim2;
Figure(double a, double b)
{
dim1=a;
dim2=b;
}
double area()
{
System.out.println("Area for figure is undefined");
return 0;
}
}
class Rectangle extends Figure
{
Rectangle(double a,double b)
{
super(a,b);
}
double area()
{
System.out.println("\nInside Area for Rectangle");
return dim1 * dim2;
}
}
class Triangle extends Figure
{
Triangle(double a,double b)
{
super(a,b);
}
double area()
{
System.out.println("Inside Area for Triangle");
return dim1 * dim2/2;
}
}
class FindAreas
{
public static void main(String args[])
{
Figure f=new Figure(10,10);
Rectangle r=new Rectangle(9,5);
Triangle t=new Triangle(10,8);
Figure figref;
figref=r;
System.out.println("Area is "+figref.area());
figref=t;
System.out.println("Area is "+figref.area());
figref=f;
System.out.println("Area is "+figref.area());
}
}
-----
output:
Saturday, June 30, 2012
this() + super() method
class Base
{
public Base()
{
}
public Base(int i)
{
System.out.println("\nBase: The i Value is " + i);
}
}
public class Derived extends Base
{
public static void main(String arg[])
{
Derived mn=new Derived("FeverOfJava ", 2);
}
Derived(int i)
{
super(i);
System.out.println("Derived: The i Value is " + i);
}
Derived(String s,int i)
{
this(i);
System.out.println("The i Value is " + i);
System.out.println("The s Value is " + s);
}
}
output
Monday, February 13, 2012
Append the File
Before Append:
import java.io.*;
public class Append
{
public static void main(String[] args)
{
try
{
DataInputStream in = new DataInputStream(System.in);
BufferedWriter out = new BufferedWriter(new FileWriter("Buffered.java", true));
System.out.println("How many lines?");
int numberOfLines = Integer.parseInt(in.readLine());
String line = "";
for(int i = 0; i < numberOfLines; i++)
{
line = in.readLine();
out.write("\n"+ line ); // throws IOException
}
out.close();
}
catch (IOException e)
{
}
}
}
output:
After this check the file
Saturday, February 4, 2012
Progress Bar
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
class ProgressBarr extends JFrame implements ActionListener
{
JButton jb;
JProgressBar jpb1;
int value =0;
ProgressBarr()
{
Container contentPane=getContentPane();
contentPane.setLayout(new FlowLayout());
jb = new JButton("Click");
contentPane.add(jb);
jb.addActionListener(this);
jpb1 = new JProgressBar(0,5000);
contentPane.add(jpb1);
jpb1.setStringPainted(true);
}
public static void main(String args[])
{
ProgressBarr pb1 = new ProgressBarr();
pb1.setSize(300,80);
pb1.setTitle("Progress Bar");
pb1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pb1.setVisible(true);
}
public void actionPerformed(ActionEvent ae)
{
while(value <= 1000)
{
value = value+10;
jpb1.setValue(value);
}
}
}
Output:-
Table
import javax.swing.*;
import java.awt.*;
public class Table extends JFrame
{
Object[][] cells={{"ABC",999999},{"XYZ",999900},{"ABC",999999},{"XYZ",999900},{"ABC",999999}};
String[] columnName={"Name","Employee ID"};
JTable table=new JTable(cells,columnName);
JScrollPane pane=new JScrollPane(table);
Container con;
Table()
{
super("LOG IN");con=getContentPane();
setSize(200,200);
setLayout(null);
pane.setBounds(20,20,150,100);
con.add(pane);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String s[])
{
Table obj=new Table();
}
}
Output:-
Tree
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.tree.*;
public class Tree1 extends JFrame
{
public static void main(String args[])
{
Tree1 t1 = new Tree1("A Tree");
t1.setSize(200,200);
t1.setVisible(true);
t1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public Tree1(String title)
{
setTitle(title);
DefaultMutableTreeNode root=new DefaultMutableTreeNode ("Engineering");
DefaultMutableTreeNode style=new DefaultMutableTreeNode ("Information Technology");
root.add(style);
style=new DefaultMutableTreeNode("Electronics");
root.add(style);
style=new DefaultMutableTreeNode ("Computer Science");
root.add(style);
style=new DefaultMutableTreeNode ("Mechanical");
root.add(style);
style=new DefaultMutableTreeNode ("Electrical");
root.add(style);
style=new DefaultMutableTreeNode ("Sound");
root.add(style);
JTree jt=new JTree(root);
Container contentPane=getContentPane();
contentPane.add(new JScrollPane(jt));
}
}
Output:-
Package
import pack.*;
import javax.swing.*;
import java.awt.*;
class Main extends JFrame
{
public static void main(String[] s)
{
JFrame f1=new JFrame();
f1.setSize(200,200);
f1.setBackground(Color.blue);
f1.setLayout(null);
f1.setVisible(true);
f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Pan d1=new Pan();
f1.add(d1);
}
}
-------------------------
package pack;
import javax.swing.*;
import java.awt.*;
public class Pan extends JPanel
{
JLabel l1;
public Pan()
{
setSize(100,100);
setLayout(null);
setBackground(Color.red);
setVisible(true);
setBounds(50,50,80,40);
l1=new JLabel("PANEL");
l1.setBounds(15,15,50,10);
add(l1);
}
}
Output:-
Friday, February 3, 2012
Timer
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class JavaSimpleTimer extends JPanel implements ActionListener
{
int miliseconds=0;
int seconds=0;
int minutes=0;
Timer myTimer;
Font timerFont=new Font("Verdana",Font.BOLD,24);
public JavaSimpleTimer()
{
myTimer=new Timer(10,this);
JFrame myFrame=new JFrame("Simple Timer");
myFrame.add(this);
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setSize(200,100);
myFrame.setVisible(true);
myTimer.setInitialDelay(0);
myTimer.start();
}
public void paint(Graphics g)
{
super.paint(g);
String mili=Integer.toString(miliseconds);
String sec=Integer.toString(seconds);
String min=Integer.toString(minutes);
if(mili.length()==1)
{
mili="0"+mili;
}
if(sec.length()==1)
{
sec="0"+sec;
}
if(min.length()==1)
{
min="0"+min;
}
g.setFont(timerFont);
g.drawString(min+" :",20,20);
g.drawString(sec+" :",80,20);
g.drawString(mili,140,20);
}
public void actionPerformed(ActionEvent event)
{
miliseconds=miliseconds+1;
if(miliseconds==100)
{
miliseconds=0;
seconds=seconds+1;
}
if(seconds==60)
{
seconds=0;
minutes=minutes+1;
}
repaint();
}
public static void main(String[]args)
{
JavaSimpleTimer myTest=new JavaSimpleTimer();
}
}
Output:-
Wednesday, October 19, 2011
Class
A class is nothing but a blueprint or a template for creating different objects which defines its properties and behaviors. Java class objects exhibit the properties and behaviors defined by its class. A class can contain fields and methods to describe the behavior of an object.
class Fabonic
{
public static void main(String s[])
{
int a=0,fab=0,b=1,c,n=11,i;
System.out.println("how much element do u want of fabocci series :");
System.out.println("fabocci series : ");
System.out.println(a);
System.out.println(b);
for(i=0;i<=n;i++)
{
fab=a+b;
System.out.println(fab);
c=a;
a=b;
b=fab;
}
}
}
Monday, October 17, 2011
What is the difference between abstract class and interface?
| feature | interface | abstract class |
|---|---|---|
| multiple inheritance | A class may implement several interfaces. | A class may extend only one abstract class. |
| default implementation | An interface cannot provide any code at all, much less default code. | An abstract class can provide complete code, default code, and/or just stubs that have to be overridden. |
| constants | Static final constants only, can use them without qualification in classes that implement the interface. On the other paw, these unqualified names pollute the namespace. You can use them and it is not obvious where they are coming from since the qualification is optional. | Both instance and static constants are possible. Both static and instance intialiser code are also possible to compute the constants. |
| third party convenience | An interface implementation may be added to any existing third party class. | A third party class must be rewritten to extend only from the abstract class. |
| is-a vs -able or can-do | Interfaces are often used to describe the peripheral abilities of a class, not its central identity, e.g. An Automobile class might implement the Recyclable interface, which could apply to many otherwise totally unrelated objects. | An abstract class defines the core identity of its descendants. If you
defined a Dog abstract class then Dalmatian descendants are Dogs,
they are not merely dogable. Implemented interfaces enumerate the general things a class can do, not the
things a class is.
In a Java context, users should typically implement the Runnable interface rather than extending Thread, because they’re
not really interested in providing some new Thread functionality, they
normally just want some code to have the capability of running independently. They want to create
something that can be run in a thread, not a new kind of thread.The similar is-a vs has-a debate comes up
when you decide to inherit or delegate.
multiple inheritance for further discussion of is-a vs has-a
|
| plug-in | You can write a new replacement module for an interface that contains not one stick of code in common with the existing implementations. When you implement the interface, you start from scratch without any default implementation. You have to obtain your tools from other classes; nothing comes with the interface other than a few constants. This gives you freedom to implement a radically different internal design. | You must use the abstract class as-is for the code base, with all its attendant baggage, good or bad. The abstract class author has imposed structure on you. Depending on the cleverness of the author of the abstract class, this may be good or bad. |
| homogeneity | If all the various implementations share is the method signatures, then an interface works best. | If the various implementations are all of a kind and share a common status and behaviour, usually an abstract class works best. Another issue that’s important is what I call "heterogeneous vs. homogeneous." If implementors/subclasses are homogeneous, tend towards an abstract base class. If they are heterogeneous, use an interface. (Now all I have to do is come up with a good definition of hetero/homo-geneous in this context.) If the various objects are all of-a-kind, and share a common state and behavior, then tend towards a common base class. If all they share is a set of method signatures, then tend towards an interface. |
| maintenance | If your client code talks only in terms of an interface, you can easily change the concrete implementation behind it, using a factory method. | Just like an interface, if your client code talks only in terms of an abstract class, you can easily change the concrete implementation behind it, using a factory method. |
| speed | Slow, requires extra indirection to find the corresponding method in the actual class. Modern JVMs are discovering ways to reduce this speed penalty. | Fast |
| terseness | The constant declarations in an interface are all presumed public static final, so you may leave that part out. You can’t call any methods to compute the initial values of your constants. You need not declare individual methods of an interface abstract. They are all presumed so. | You can put shared code into an abstract class, where you cannot into an interface. If interfaces want to share code, you will have to write other bubblegum to arrange that. You may use methods to compute the initial values of your constants and variables, both instance and static. You must declare all the individual methods of an abstract class abstract. |
| adding functionality | If you add a new method to an interface, you must track down all implementations of that interface in the universe and provide them with a concrete implementation of that method. | If you add a new method to an abstract class, you have the option of providing a default implementation of it. Then all existing code will continue to work without change. |
Swing is a light weight component, and awt is a heavy weight component, why?
A heavyweight component
is one that is associated with its own native screen resource (commonly
known as a peer). A lightweight component is one that "borrows" the
screen resource of an ancestor (which means it has no native resource
of its own -- so it's "lighter").
- A lightweight component can have transparent pixels; a heavyweight is always opaque.
- A lightweight component can appear to be non-rectangular because of its ability to set transparent areas; a heavyweight can only be rectangular.
- Mouse events on a lightweight component fall through to its parent; mouse events on a heavyweight component do not fall through to its parent.
- When a lightweight component overlaps a heavyweight component, the heavyweight component is always on top, regardless of the relative z-order of the two components.
-----------
Light weight Component
takes the components from the jvm, means it does not request the
operating System for getting the components. Swings are light weight
components. thats why swing look and feel is different and same on every
operating System.
Where as, heavy weight components are depending on the O.S.
if we request a button component, then JVM ask the button to the os and
then it give to the JVM. it is very time consuming process. So awt look
and feel is depending on the os. It changes from one os to another os.
Wrapper Class
Java is an object-oriented language and as said everything in java is an object. But what about the primitives? They are sort of left out in the world of objects, that is, they cannot participate in the object activities, such as being returned from a method as an object, and being added to a Collection of objects, etc. . As a solution to this problem, Java allows you to include the primitives in the family of objects by using what are called wrapper classes.
There is a wrapper class for every primitive date type in Java. This class encapsulates a single value for the primitive data type. For instance the wrapper class for int is Integer, for float is Float, and so on. Remember that the primitive name is simply the lowercase name of the wrapper except for char, which maps to Character, and int, which maps to Integer.
The wrapper classes in the Java API serve two primary purposes:
There is a wrapper class for every primitive date type in Java. This class encapsulates a single value for the primitive data type. For instance the wrapper class for int is Integer, for float is Float, and so on. Remember that the primitive name is simply the lowercase name of the wrapper except for char, which maps to Character, and int, which maps to Integer.
The wrapper classes in the Java API serve two primary purposes:
- To provide a mechanism to “wrap” primitive values in an object so that the primitives can be included in activities reserved for objects, like as being added to Collections, or returned from a method with an object return value.
- To provide an assortment of utility functions for primitives. Most of these functions are related to various conversions: converting primitives to and from String objects, and converting primitives and String objects to and from different bases (or radix), such as binary, octal, and hexadecimal.
Sunday, September 18, 2011
3-D Matrix-II
MultiDimensional Array
MultiDimensional Array
class Matrix
{
public static void main(String args[])
{
int i,j,k;
int mat[][][]= {
{
{1,2,3},
{4,5,6},
{7,8,9}
},
{
{9,8,7},
{6,5,4},
{3,2,1}
}
};
System.out.println();
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
for(k=0;k<3;k++)
{
System.out.print(" ");
System.out.print(mat[i][j][k]);
System.out.print(" ");
}
System.out.println();
}
System.out.println();
}
}
}
output
3-D Matrix-I
Multi-Dimensional Array
Multi-Dimensional Array
class Matrix
{
public static void main(String args[])
{
int i,j,k;
int mat[][][]=new int[2][3][3];
mat[0][0][0]=1;
mat[0][0][1]=2;
mat[0][0][2]=3;
mat[0][1][0]=4;
mat[0][1][1]=5;
mat[0][1][2]=6;
mat[0][2][0]=7;
mat[0][2][1]=8;
mat[0][2][2]=9;
mat[1][0][0]=9;
mat[1][0][1]=8;
mat[1][0][2]=7;
mat[1][1][0]=6;
mat[1][1][1]=5;
mat[1][1][2]=4;
mat[1][2][0]=3;
mat[1][2][1]=2;
mat[1][2][2]=1;
System.out.println();
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
for(k=0;k<3;k++)
{
System.out.print(" ");
System.out.print(mat[i][j][k]);
System.out.print(" ");
}
System.out.println();
}
System.out.println();
}
}
}
Output
Wednesday, June 8, 2011
PHP: Date
<HTML>
<HEAD>
<TITLE>POWEREDBYPHP.COM, PHP Tutorial - Lesson 1.2</TITLE>
</HEAD>
<BODY>
<?PHP
$date = Date("l - F d, Y");
print("Hello World<>\n");
print("Today's date is: $date\n");
?>
</BODY>
</HTML>
PHP: First Program
<html>
<head>
<title>PHP Test Page</title>
</head>
<body>
<center><b>
<?php
print "I like About";
print "<br>";
print "Billy said I like About too"
?>
</b></center>
</body>
</html>
Tuesday, June 7, 2011
PHP: Comments
<?php
//A comment on a single line
/*
Multiple Line
Using this method
you can create a larger block of text
and it will all be commented out
*/
?>
PHP: Introduction
What is PHP?
- PHP is a general-purpose scripting language originally designed for web development to produce dynamic web pages.
- PHP code is embedded into the HTML source document and interpreted by a web server with a PHP processor module, which generates the web page document.
- It also has evolved to include a command-line interface capability and can be used in standalone graphical applications.
- PHP is an open-source language, used primarily for dynamic web content and server-side applications. It is often pointed to as the main competitor with:
- Microsoft's C# - Visual Basic.NET - ASP family,
- Sun's Java - JSP.
- Macromedia's ColdFusion .
- CGI - Perl.
- Start by creating a blank file using any program that can save in plain text format. Save your file as a .PHP file, for example mypage.php.
- Saving a page with the .php extension tells your server that it will need to execute the PHP code. Enter the statement to let the browser know the PHP code is done.
- Every section of PHP code starts and ends by turning on and off PHP tags to let the server know that it needs to execute the PHP in between them. Here is an example: Everything between the is read as PHP code.
<?php
code...
?>
-------------------
Sunday, June 5, 2011
First PDF
import java.io.FileOutputStream;
import java.util.Date;
import com.itextpdf.text.Anchor;
import com.itextpdf.text.BadElementException;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chapter;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.List;
import com.itextpdf.text.ListItem;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Section;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
public class FirstPdf {
private static String FILE = "c:/temp/FirstPdf.pdf";
private static Font catFont = new Font(Font.FontFamily.TIMES_ROMAN, 18,
Font.BOLD);
private static Font redFont = new Font(Font.FontFamily.TIMES_ROMAN, 12,
Font.NORMAL, BaseColor.RED);
private static Font subFont = new Font(Font.FontFamily.TIMES_ROMAN, 16,
Font.BOLD);
private static Font smallBold = new Font(Font.FontFamily.TIMES_ROMAN, 12,
Font.BOLD);
public static void main(String[] args) {
try {
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(FILE));
document.open();
addMetaData(document);
addTitlePage(document);
addContent(document);
document.close();
} catch (Exception e) {
e.printStackTrace();
}
}
// iText allows to add metadata to the PDF which can be viewed in your Adobe
// Reader
// under File -> Properties
private static void addMetaData(Document document) {
document.addTitle("My first PDF");
document.addSubject("Using iText");
document.addKeywords("Java, PDF, iText");
document.addAuthor("Lars Vogel");
document.addCreator("Lars Vogel");
}
private static void addTitlePage(Document document)
throws DocumentException {
Paragraph preface = new Paragraph();
// We add one empty line
addEmptyLine(preface, 1);
// Lets write a big header
preface.add(new Paragraph("Title of the document", catFont));
addEmptyLine(preface, 1);
// Will create: Report generated by: _name, _date
preface.add(new Paragraph(
"Report generated by: " + System.getProperty("user.name") + ", " + new Date(), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
smallBold));
addEmptyLine(preface, 3);
preface.add(new Paragraph(
"This document describes something which is very important ",
smallBold));
addEmptyLine(preface, 8);
preface.add(new Paragraph(
"This document is a preliminary version and not subject to your license agreement or any other agreement with vogella.de ;-).",
redFont));
document.add(preface);
// Start a new page
document.newPage();
}
private static void addContent(Document document) throws DocumentException {
Anchor anchor = new Anchor("First Chapter", catFont);
anchor.setName("First Chapter");
// Second parameter is the number of the chapter
Chapter catPart = new Chapter(new Paragraph(anchor), 1);
Paragraph subPara = new Paragraph("Subcategory 1", subFont);
Section subCatPart = catPart.addSection(subPara);
subCatPart.add(new Paragraph("Hello"));
subPara = new Paragraph("Subcategory 2", subFont);
subCatPart = catPart.addSection(subPara);
subCatPart.add(new Paragraph("Paragraph 1"));
subCatPart.add(new Paragraph("Paragraph 2"));
subCatPart.add(new Paragraph("Paragraph 3"));
// Add a list
createList(subCatPart);
Paragraph paragraph = new Paragraph();
addEmptyLine(paragraph, 5);
subCatPart.add(paragraph);
// Add a table
createTable(subCatPart);
// Now add all this to the document
document.add(catPart);
// Next section
anchor = new Anchor("Second Chapter", catFont);
anchor.setName("Second Chapter");
// Second parameter is the number of the chapter
catPart = new Chapter(new Paragraph(anchor), 1);
subPara = new Paragraph("Subcategory", subFont);
subCatPart = catPart.addSection(subPara);
subCatPart.add(new Paragraph("This is a very important message"));
// Now add all this to the document
document.add(catPart);
}
private static void createTable(Section subCatPart)
throws BadElementException {
PdfPTable table = new PdfPTable(3);
// t.setBorderColor(BaseColor.GRAY);
// t.setPadding(4);
// t.setSpacing(4);
// t.setBorderWidth(1);
PdfPCell c1 = new PdfPCell(new Phrase("Table Header 1"));
c1.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(c1);
c1 = new PdfPCell(new Phrase("Table Header 2"));
c1.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(c1);
c1 = new PdfPCell(new Phrase("Table Header 3"));
c1.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(c1);
table.setHeaderRows(1);
table.addCell("1.0");
table.addCell("1.1");
table.addCell("1.2");
table.addCell("2.1");
table.addCell("2.2");
table.addCell("2.3");
subCatPart.add(table);
}
private static void createList(Section subCatPart) {
List list = new List(true, false, 10);
list.add(new ListItem("First point"));
list.add(new ListItem("Second point"));
list.add(new ListItem("Third point"));
subCatPart.add(list);
}
private static void addEmptyLine(Paragraph paragraph, int number) {
for (int i = 0; i < number; i++) {
paragraph.add(new Paragraph(" "));
}
}
}
Subscribe to:
Posts (Atom)