> December 2011 ~ Online tutorial

variables in c++

Variable

A variable is a symbolic name for a memory location in which data can be stored
and subsequently recalled. Variables are used for holding data values so that they
can be utilized in various computations in a program.
All variables have two important attributes:

  • A type which is established when the variable is defined (e.g., integer, real,
    character). Once defined, the type of a C++ variable cannot be changed.
  • A value which can be changed by assigning a new value to the variable. The
    kind of values a variable can assume depends on its type. For example, an
    integer variable can only take integer values

How C++ Compilation Works

Compiling a C++ program involves a number of steps :
  • First, the C++ preprocessor goes over the program text and carries out the
    instructions specified by the proprocessor directives (e.g., #include). The
    result is a modified program text which no longer contains any directives.
  • Then, the C++ compiler translates the program code. The compiler may be a
    true C++ compiler which generates native (assembly or machine) code, or just
    a translator which translates the code into C. In the latter case, the resulting C
    code is then passed through a C compiler to produce native object code. In
    either case, the outcome may be incomplete due to the program referring to
    library routines which are not defined as a part of the program.
  • Finally, the linker completes the object code by linking it with the object code
    of any library modules that the program may have referred to. The final result
    is an executable file.
Buy It Now



Compiling C++ Program


Compiling C++ Program

$ CC hello.cc

$ a.out

Hello World

$
Annotation
  • The command for invoking the AT&T C++ translator in a UNIX environment
    is CC. The argument to this command (hello.cc) is the name of the file which
    contains the program. As a convention, the file name should end in .c, .C, or
    .cc. (This ending may be different in other systems.)
  • The result of compilation is an executable file which is by default named
    a.out. To run the program, we just use a.out as a command.
  • This is the output produced by the program.
  • The return of the system prompt indicates that the program has completed its
    execution.
Buy It Now





Simple C++ Program

A Simple C++ Program

#include <iostream.h>

int main (void)

{

cout << "Hello World\n";

}
Annotation
  • This line uses the preprocessor directive #include to include the contents
    of the header file iostream.h in the program. Iostream.h is a standard
    C++ header file and contains definitions for input and output.
  • This line defines a function called main. A function may have zero or more
    parameters; these always appear after the function name, between a pair of
    brackets. The word void appearing between the brackets indicates that main
    has no parameters. A function may also have a return type; this always
    appears before the function name. The return type for main is int (i.e., an
    integer number). All C++ programs must have exactly one main functions.
    Program execution always begins from main.
  • This brace marks the beginning of the body of main.
  • This line is a statement. A statement is a computation step which may
    produce a value. The end of a statement is always marked with a semicolon
    (;). This statement causes the string "Hello World\n" to be sent to the
    cout output stream. A string is any sequence of characters enclosed in
    double-quotes. The last character in this string (\n) is a newline character
    which is similar to a carriage return on a type writer. A stream is an object
    which performs input or output. Cout is the standard output stream in C++
    (standard output usually means your computer monitor screen). The symbol
    << is an output operator which takes an output stream as its left operand and an expression as its right operand, and causes the value of the latter to be sent to the former. In this case, the effect is that the string "Hello World\n" is sent to cout, causing it to be printed on the computer monitor screen.
  • This brace marks the end of the body of main.
Buy It Now



exceptions in java

Exceptions
  • Programmers in any language endeavor to write bug-free programs, programs that never
    crash, programs that can handle any circumstance with grace and recover from unusual
    situations without causing a user any undue stress. Good intentions aside, programs like
    this don’t exist.
  • In real programs, errors occur because programmers didn’t anticipate possible problems,
    didn’t test enough, or encountered situations out of their control—bad data from users,
    corrupt files that don’t have the correct data in them, network connections that don’t connect,
    hardware devices that don’t respond, sun spots, gremlins, and so on.
  • In Java, the strange events that might cause a program to fail are called exceptions. Java defines a number of language features that deal with exceptions:
  • How to handle exceptions in your code and recover gracefully from potential
    problems
  • How to tell Java and users of your classes that you’re expecting a potential
    exception
  • How to create an exception if you detect one
  • How your code is limited, yet made more robust by exceptions
    With most programming languages, handling error conditions requires much more work
    than handling a program that is running properly.
Here’s the structure of one possible solution:

int status = loadTextFile();
if (status != 1) {
// something unusual happened, describe it
switch (status) {
case 2:
System.out.println(“File not found”);
break;
case 3:
System.out.println(“Disk error”);
break;
case 4:
System.out.println(“File corrupted”);
break;
default:
System.out.println(“Error”);
}
} else {
// file loaded OK, continue with program
}


This code tries to load a file with a method call to loadTextFile(), which presumably
has been defined elsewhere in the class. The method returns an integer that indicates
whether the file loaded properly (a value of 1) or an error occurred (anything other
than 1).

Buy It Now




java.io package

An overview of the java.io package
Introduction
This section introduces the java.iopackage.
Here are some basic points about I/O:

* Data in files on your system is called persistent data because it persists after the
program runs.
* Files are created through streams in Java code.
* A stream is a linear, sequential flow of bytes of input or output data.
* Streams are written to the file system to create files.
* Streams can also be transferred over the Internet.
* Three streams are created for us automatically:

Syst*em.out - standard output stream
Syst*em.in - standard input stream
Syst*em.err - standard error


* Input/output on the local file system using applets is dependent on the browser's
security manager. Typically, I/O is not done using applets. On the other hand,
stand-alone applications have no security manager by default unless the developer has
added that functionality.


Buy It Now




Java2D Shapes

Java2D Shapes
  • Next, we present several java2D shapes from package java.awt.geom, including
    Ellipse2D.Double, Rectangle2D.Double, RoundRectangle2D.Double,
    Arc2D.Double and Line2D.Double.
  • Note the syntax of each class name. Each of these classes represents a shape with dimensions specified as double-precision floatingpoint
    values.
  • There is a separate version of each represented with single-precision floatingpoint values (such as Ellipse2D.Float).
  • In each case, Double is a static inner
    class of the class to the left of the dot operator (e.g., Ellipse2D).
  • To use the static inner class, we simply qualify its name with the outer class name.

Program

2 // Demonstrating some Java2D shapes
3 import javax.swing.*;
4 import java.awt.event.*;
5 import java.awt.*;
6 import java.awt.geom.*;
7 import java.awt.image.*;
89
public class Shapes extends JFrame {
10 public Shapes()
11 {
12 super( "Drawing 2D shapes" );
13
14 setSize( 425, 160 );
15 show();
16 }
17
18 public void paint( Graphics g )
19 {
20 // create 2D by casting g to Graphics2D
21 Graphics2D g2d = ( Graphics2D ) g;
22
23 // draw 2D ellipse filled with a blue-yellow gradient
24 g2d.setPaint(
25 new GradientPaint( 5, 30, // x1, y1
26 Color.blue, // initial Color
27 35, 100, // x2, y2
28 Color.yellow, // end Color
29 true ) ); // cyclic
30 g2d.fill( new Ellipse2D.Double( 5, 30, 65, 100 ) );
31
32 // draw 2D rectangle in red
33 g2d.setPaint( Color.red );
34 g2d.setStroke( new BasicStroke( 10.0f ) );
35 g2d.draw(
36 new Rectangle2D.Double( 80, 30, 65, 100 ) );
37
38 // draw 2D rounded rectangle with a buffered background
39 BufferedImage buffImage =
40 new BufferedImage(
41 10, 10, BufferedImage.TYPE_INT_RGB );
42
43 Graphics2D gg = buffImage.createGraphics();
44 gg.setColor( Color.yellow ); // draw in yellow
45 gg.fillRect( 0, 0, 10, 10 ); // draw a filled rectangle
46 gg.setColor( Color.black ); // draw in black
47 gg.drawRect( 1, 1, 6, 6 ); // draw a rectangle
48 gg.setColor( Color.blue ); // draw in blue
49 gg.fillRect( 1, 1, 3, 3 ); // draw a filled rectangle
50 gg.setColor( Color.red ); // draw in red
51 gg.fillRect( 4, 4, 3, 3 ); // draw a filled rectangle
53 // paint buffImage onto the JFrame
54 g2d.setPaint(
55 new TexturePaint(
56 buffImage, new Rectangle( 10, 10 ) ) );
57 g2d.fill(
58 new RoundRectangle2D.Double(
59 155, 30, 75, 100, 50, 50 ) );
60
61 // draw 2D pie-shaped arc in white
62 g2d.setPaint( Color.white );
63 g2d.setStroke( new BasicStroke( 6.0f ) );
64 g2d.draw(
65 new Arc2D.Double(
66 240, 30, 75, 100, 0, 270, Arc2D.PIE ) );
67
68 // draw 2D lines in green and yellow
69 g2d.setPaint( Color.green );
70 g2d.draw( new Line2D.Double( 395, 30, 320, 150 ) );
71
72 float dashes[] = { 10 };
73
74 g2d.setPaint( Color.yellow );
75 g2d.setStroke(
76 new BasicStroke( 4,
77 BasicStroke.CAP_ROUND,
78 BasicStroke.JOIN_ROUND,
79 10, dashes, 0 ) );
80 g2d.draw( new Line2D.Double( 320, 30, 395, 150 ) );
81 }
82 public static void main( String args[] )
84 {
85 Shapes app = new Shapes();
86
87 app.addWindowListener(
88 new WindowAdapter() {
89 public void windowClosing( WindowEvent e )
90 {
91 System.exit( 0 );
92 }
93 }
94 );
95 }
96 }


Buy It Now



Java2D

The Java2D API
  • The java2D API provides advanced two-dimensional graphics capabilities for programmers
    who require detailed and complex graphical manipulations.
  • The API includes features for processing line art, text and images in packages
  •  java.awt,
  •  java.awt.image,
    java.awt.color,
  •  java.awt.font, 
  • java.awt.geom, 
  • java.awt.print and
    java.awt.image.renderable.
  • The capabilities of the API are far too broad to cover
    in this textbook. In this section, we present an overview of several Java2D capabilities.
  • Drawing with the Java2D API is accomplished with an instance of class
    Graphics2D (package java.awt). Class Graphics2D is a subclass of class
    Graphics
  • In fact, the actual object we have used to draw in every paint method is a Graphics2D
    object that is passed to method paint and accessed via the superclass Graphics reference
    g.
  • To access the Graphics2D capabilities, we must downcast the Graphics reference
    passed to paint to a Graphics2D reference with a statement such as
    Graphics2D g2d = ( Graphics2D ) g;
    The programs of the next several sections use this technique.
Buy It Now




drawing polygons in java

Drawing Polygons and Polylines
  • polygen are multisided shapes. Polylines are a series of connected points.
  • Graphics methods for drawing polygons and polylines
  • The program of draws polygons and polylines using the methods and constructors
    Lines 18 through 20 create two int arrays and use them to specify the points for
    Polygon poly1.
  • The Polygon constructor call at line 20 receives array xValues,
    which contains the x-coordinate of each point, array yValues, which contains the y-coordinate
    of each point, and 6 (the number of points in the polygon). Line 22 displays poly1
    by passing it as an argument to Graphics method drawPolygon.
public void drawPolygon( int xPoints[], int yPoints[],
int points )
Draws a polygon. The x-coordinate of each point is specified in the xPoints
array and the y-coordinate of each point is specified in the yPoints array. The
last argument specifies the number of points. This method draws a closed polygon—
even if the last point is different from the first point.

public void drawPolygon( Polygon p )
Draws the specified closed polygon.

public void fillPolygon( int xPoints[], int yPoints[],
int points )
Draws a solid polygon. The x-coordinate of each point is specified in the
xPoints array and the y-coordinate of each point is specified in the yPoints
array. The last argument specifies the number of points. This method draws a
closed polygon—even if the last point is different from the first point.

public void fillPolygon( Polygon p )
Draws the specified solid polygon. The polygon is closed.

public Polygon()
// Polygon class Constructs a new polygon object. The polygon does not contain any points.

public Polygon( int xValues[], int yValues[], // Polygon class
int numberOfPoints )
Constructs a new polygon object. The polygon has numberOfPoints sides,
with each point consisting of an x-coordinate from xValues and a y-coordinate from yValues

public void drawPolyline( int xPoints[], int yPoints[],
int points )
Draws a series of connected lines. The x-coordinate of each point is specified in
the xPoints array and the y-coordinate of each point is specified in the
yPoints array. The last argument specifies the number of points. If the last
point is different from the first point, the polyline is not closed.

Program

2 // Drawing polygons

3 import java.awt.*;
4 import java.awt.event.*;
5 import javax.swing.*;
67
public class DrawPolygons extends JFrame {
8 public DrawPolygons()
9 {
10 super( "Drawing Polygons" );
11
12 setSize( 275, 230 );
13 show();
14 }
15
16 public void paint( Graphics g )
17 {
18 int xValues[] = { 20, 40, 50, 30, 20, 15 };
19 int yValues[] = { 50, 50, 60, 80, 80, 60 };
20 Polygon poly1 = new Polygon( xValues, yValues, 6 );
21
22 g.drawPolygon( poly1 );

24 int xValues2[] = { 70, 90, 100, 80, 70, 65, 60 };
25 int yValues2[] = { 100, 100, 110, 110, 130, 110, 90 };
26
27 g.drawPolyline( xValues2, yValues2, 7 );
28
29 int xValues3[] = { 120, 140, 150, 190 };
30 int yValues3[] = { 40, 70, 80, 60 };
31
32 g.fillPolygon( xValues3, yValues3, 4 );
33
34 Polygon poly2 = new Polygon();
35 poly2.addPoint( 165, 135 );
36 poly2.addPoint( 175, 150 );
37 poly2.addPoint( 270, 200 );
38 poly2.addPoint( 200, 220 );
39 poly2.addPoint( 130, 180 );
40
41 g.fillPolygon( poly2 );
42 }
43
44 public static void main( String args[] )
45 {
46 DrawPolygons app = new DrawPolygons();
47
48 app.addWindowListener(
49 new WindowAdapter() {
50 public void windowClosing( WindowEvent e )
51 {
52 System.exit( 0 );
53 }
54 }
55 );
56 }
57 }











Buy It Now


drawing arcs in java

Drawing Arcs

  • An arc is a portion of a oval. Arc angles are measured in degrees. Arcs sweep from a starting angle the number of degrees specified by their arc angle.
  • The starting angle indicates in degrees where the arc begins.
  • The arc angle specifies the total number of degrees through which the arc sweeps.
  • The left set of axes shows an arc sweeping from zero degrees to approximately 110 degrees.
  • Arcs that sweep in a counterclockwise direction are measured in positive degrees.
  • The right set of axes shows an arc sweeping from zero degrees to approximately –110 degrees.
  • Arcs that sweep in a clockwise
    direction are measured in negative degrees.
public void drawArc( int x, int y, int width, int height,
int startAngle, int arcAngle )
Draws an arc relative to the bounding rectangle’s top-left coordinates (x, y)
with the specified width and height. The arc segment is drawn starting at
startAngle and sweeps arcAngle degrees.

public void fillArc( int x, int y, int width, int height,
int startAngle, int arcAngle )
Draws a solid arc (i.e., a sector) relative to the bounding rectangle’s top-left
coordinates (x, y) with the specified width and height. The arc segment
is drawn starting at startAngle and sweeps arcAngle degrees.

Program

2 // Drawing arcs
3 import java.awt.*;
4 import javax.swing.*;
5 import java.awt.event.*;
67
public class DrawArcs extends JFrame {
8 public DrawArcs()
9 {
10 super( "Drawing Arcs" );
11
12 setSize( 300, 170 );
13 show();
14 }
15
16 public void paint( Graphics g )
17 {
18 // start at 0 and sweep 360 degrees
19 g.setColor( Color.yellow );
20 g.drawRect( 15, 35, 80, 80 );
21 g.setColor( Color.black );
22 g.drawArc( 15, 35, 80, 80, 0, 360 );
23
24 // start at 0 and sweep 110 degrees
25 g.setColor( Color.yellow );
26 g.drawRect( 100, 35, 80, 80 );
27 g.setColor( Color.black );
28 g.drawArc( 100, 35, 80, 80, 0, 110 );
29
30 // start at 0 and sweep -270 degrees
31 g.setColor( Color.yellow );
32 g.drawRect( 185, 35, 80, 80 );
33 g.setColor( Color.black );
34 g.drawArc( 185, 35, 80, 80, 0, -270 );
35
36 // start at 0 and sweep 360 degrees
37 g.fillArc( 15, 120, 80, 40, 0, 360 );
38
39 // start at 270 and sweep -90 degrees
40 g.fillArc( 100, 120, 80, 40, 270, -90 );
41
42 // start at 0 and sweep -270 degrees
43 g.fillArc( 185, 120, 80, 40, 0, -270 );
44 }
45
46 public static void main( String args[] )
47 {
48 DrawArcs app = new DrawArcs();
49
50 app.addWindowListener(
51 new WindowAdapter() {
52 public void windowClosing( WindowEvent e )

53System.exit( 0 );
55 }
56 }
57 );
58 }
59 }


Buy It Now




drawing lines,Rectangles and Ovals in java

Drawing Lines, Rectangles and Ovals
  • This section presents a variety of Graphics methods for drawing lines, rectangles and
    ovals.
  • For each drawing method that requires a width and height parameter, the width and height must be
    nonnegative values.
  • Otherwise, the shape will not display.
    public void drawLine( int x1, int y1, int x2, int y2 ) Draws a line between the point (x1, y1) and the point (x2, y2).
    public void drawRect( int x, int y, int width, int height ) Draws a rectangle of the specified width and height. The top-left corner of the rectangle has the coordinates (x, y).
    public void fillRect( int x, int y, int width, int height ) Draws a solid rectangle with the specified width and height. The top-left corner of the rectangle has the coordinate (x, y).
    public void clearRect( int x, int y, int width, int height ) Draws a solid rectangle with the specified width and height in the current background color. The top-left corner of the rectangle has the coordinate (x, y).
    public void drawRoundRect( int x, int y, int width, int height, int arcWidth, int arcHeight )
    Draws a rectangle with rounded corners in the current color with the specifiedwidth and height. The arcWidth and arcHeight determine the rounding of the corners 
    public void fillRoundRect( int x, int y, int width, int height, int arcWidth, int arcHeight )
    Draws a solid rectangle with rounded corners in the current color with the specified width and height. The arcWidth and arcHeight determine the rounding of the corners 
    public void draw3DRect( int x, int y, int width, int height, boolean b ) Draws a three-dimensional rectangle in the current color with the specified width and height. The top-left corner of the rectangle has the coordinates (x, y). The rectangle appears raised when b is true and is lowered when b is false.
Program


3 import java.awt.*;
4 import java.awt.event.*;
5 import javax.swing.*;
67
public class LinesRectsOvals extends JFrame {
8 private String s = "Using drawString!";
9
10 public LinesRectsOvals()
11 {
12 super( "Drawing lines, rectangles and ovals" );
13
14 setSize( 400, 165 );
15 show();
16 }
17
18 public void paint( Graphics g )
19 {
20 g.setColor( Color.red );
21 g.drawLine( 5, 30, 350, 30 );
22
23 g.setColor( Color.blue );
24 g.drawRect( 5, 40, 90, 55 );
25 g.fillRect( 100, 40, 90, 55 );
26
27 g.setColor( Color.cyan );
28 g.fillRoundRect( 195, 40, 90, 55, 50, 50 );
29 g.drawRoundRect( 290, 40, 90, 55, 20, 20 );
30
31 g.setColor( Color.yellow );
32 g.draw3DRect( 5, 100, 90, 55, true );
33 g.fill3DRect( 100, 100, 90, 55, false );
34
35 g.setColor( Color.magenta );
36 g.drawOval( 195, 100, 90, 55 );
37 g.fillOval( 290, 100, 90, 55 );
38 }
39
40 public static void main( String args[] )
41 {
42 LinesRectsOvals app = new LinesRectsOvals();
43
44 app.addWindowListener(
45 new WindowAdapter() {
46 public void windowClosing( WindowEvent e )
47 {
48 System.exit( 0 );
49 }
50 }
51 );
52 }
53 }




Buy It Now




font controller pattern in java

Font Control

  • Most font methods and font constants are part of class Font. Some methods of class Font and class Graphics are Class Font’s constructor takes three arguments—the font name, font style and font size.
  • The font name is any font currently supported by the system where the program is running, such as standard Java fonts Monospaced, SansSerif and Serif.
  • The font style is Font.PLAIN, Font.
  • ITALIC or Font.BOLD (static constants of class Font).

public final static int PLAIN 
// Font class A constant representing a plain font style.

public final static int BOLD
// Font class A constant representing a bold font style.
public final static int ITALIC
// Font class A constant representing an italic font style.
public Font( String name, int style, int size )
Creates a Font object with the specified font, style and size.

public int getStyle() 
// Font class Returns an integer value indicating the current font style.
public int getSize()
// Font class Returns an integer value indicating the current font size.
public String getName()
// Font class Returns the current font name as a string.
public String getFamily()
// Font class Returns the font’s family name as a string.
public boolean isPlain()
// Font class Tests a font for a plain font style. Returns true if the font is plain.
public boolean isBold()
// Font class Tests a font for a bold font style. Returns true if the font is bold.
public boolean isItalic() 
// Font class Tests a font for an italic font style. Returns true if the font is italic.
public Font getFont()
// Graphics class Returns a Font object reference representing the current font.
public void setFont(Font f)
// Graphics class Sets the current font to the font, style and size specified by the Font

Program


3 import java.awt.*;
4 import javax.swing.*;
5 import java.awt.event.*;
67
public class Fonts extends JFrame {
8 public Fonts()
9 {
10 super( "Using fonts" );
11
12 setSize( 420, 125 );
13 show();
14 }
15
16 public void paint( Graphics g )
17 {
18 // set current font to Serif (Times), bold, 12pt
19 // and draw a string
20 g.setFont( new Font( "Serif", Font.BOLD, 12 ) );
21 g.drawString( "Serif 12 point bold.", 20, 50 );
22
23 // set current font to Monospaced (Courier),
24 // italic, 24pt and draw a string
25 g.setFont( new Font( "Monospaced", Font.ITALIC, 24 ) );
26 g.drawString( "Monospaced 24 point italic.", 20, 70 );
27
28 // set current font to SansSerif (Helvetica),
29 // plain, 14pt and draw a string
30 g.setFont( new Font( "SansSerif", Font.PLAIN, 14 ) );
31 g.drawString( "SansSerif 14 point plain.", 20, 90 );
32
33 // set current font to Serif (times), bold/italic,
34 // 18pt and draw a string
35 g.setColor( Color.red );
36 g.setFont(
37 new Font( "Serif", Font.BOLD + Font.ITALIC, 18 ) );

38 g.drawString( g.getFont().getName() + " " +
39 g.getFont().getSize() +
40 " point bold italic.", 20, 110 );
41 }
42
43 public static void main( String args[] )
44 {
45 Fonts app = new Fonts();
46
47 app.addWindowListener(
48 new WindowAdapter() {
49 public void windowClosing( WindowEvent e )
50 {
51 System.exit( 0 );
52 }
53 }
54 );
55 }
56 }

Output






Buy It Now




color control java

Color Control



colors  enhance the appearance of a program and help convey meaning.
For example, a traffic light has three different color lights—red indicates stop, yellow indicates caution and
green indicates go.
Class Color defines methods and constants for manipulating colors in a Java program.


Color Constant Color RGB value
public final static Color orange orange 255, 200, 0
public final static Color pink pink 255, 175, 175
public final static Color cyan cyan 0, 255, 255
public final static Color yellow yellow 255, 0, 255
public final static Color black black 255, 255, 0
public final static Color white white 0, 0, 0
public final static Color gray gray 255, 255, 255
public final static Color lightGray lightGray 128, 128, 128
public final static Color darkGray darkGray 192, 192, 192




public Color( int r, int g, int b )
Creates a color based on red, green and blue contents expressed as integers
from 0 to 255.
public Color( float r, float g, float b )
Creates a color based on red, green and blue contents expressed as floatingpoint
values from 0.0 to 1.0.
public int getRed()  // Color class
Returns a value between 0 and 255 representing the red content.
public int getGreen()  // Color class
Returns a value between 0 and 255 representing the green content.
public int getBlue() // Color class
Returns a value between 0 and 255 representing the blue content.
public Color getColor() // Graphics class
Returns a Color object representing the current color for the graphics context.
public void setColor( Color c ) // Graphics class
Sets the current color for drawing with the graphics context



Buy It Now

paint method in java

paint method
  • The Paint is seldom called directly by the programmer because drawing
    graphics is an event-driven process.
  • When an applet executes, the paint method is automatically called (after calls to the JApplet’s init and start methods).
  • For paint to be called again, an event must occur (such as covering and uncovering the applet).
  • Similarly, when any Component is displayed, that Component’s paint method is called.
  • If the programmer needs to call paint, a call is made to the paint class repaint
    method.
  • Method repaint requests a call to the Component class update method as
    soon as possible to clear the Component’s background of any previous drawing, then
    update calls paint directly.
  • The repaint method is frequently called by the programmer to force a paint operation.
  • Method repaint should not be overridden because it performs some system-dependent tasks.
  • The update method is seldom called directly and sometimes overridden. Overriding the update method is useful for “smoothing” animations
  • public void repaint() public void update( Graphics g )
    Method update takes a Graphics object as an argument, which is supplied automatically by the system when update is called.

Buy It Now




graphics in java

Graphics Contexts and Graphics Objects
  • A Java graphics context enables drawing on the screen.
  • A Graphics object manages agraphics context by controlling how information is drawn.
  • Graphics objects contain methods for drawing, font manipulation, color manipulation and the like.
  • Every applet we
    have seen in the text that performs drawing on the screen has used the Graphics object
    g (the argument to the applet’s paint method)  to manage the applet’s graphics context.
  • we demonstrate drawing in applications. However, every technique shown
    here can be used in applets.
  • The Graphics class is an abstract class (i.e., Graphics objects cannot be
    instantiated). This contributes to Java’s portability. Because drawing is performed differently
  • on each platform that supports Java, there cannot be one class that implements
    drawing capabilities on all systems.
  • For example, the graphics capabilities that enable a PC running Microsoft Windows to draw a rectangle are different from the graphics capabilities that enable a UNIX workstation to draw a rectangle—and those are both different from the graphics capabilities that enable a Macintosh to draw a rectangle.
  • When Java is implemented on each platform, a derived class of Graphics is created that actually implements all the drawing capabilities.
  • This implementation is hidden from us by the Graphics class, which supplies the interface that enables us to write programs that use graphics in a platform-independent manner.
  • Class Component is the superclass for many of the classes in the java.awt
    package .

     public void paint( Graphics g )
  • The paint object paint receives a reference to an object of the system’s derived
    Graphics class.
  • The preceding method header should look familiar to you—it is the same one we have been using in our applet classes. Actually, the Component class is an indirect base class of class JApplet—the superclass of every applet in this book.
  • Many capabilities
    of class JApplet are inherited from class Component.
  • The paint method defined in class Component does nothing by default—it must be overridden by the programmer.

  • Buy It Now 

prepared statements java

Using Prepared Statements

Sometimes it is more convenient or more efficient to use a PreparedStatement object for
sending SQL statements to the database. This special type of statement is derived from
the more general class, Statement, that you already know.

When to Use a PreparedStatement Object:
  • If you want to execute a Statement object many times, it will normally reduce execution
    time to use a PreparedStatement object instead.
  • The main feature of a PreparedStatement object is that, unlike a Statement object, it is given an SQL statement when it is created.
  • The advantage to this is that in most cases, this SQL statement will be sent to the DBMS right away, where it will be compiled.
  • As a result, the PreparedStatement object contains not just an SQL statement, but an SQL statement that has been precompiled.
  • This means that when the PreparedStatement is executed, the DBMS can just run the PreparedStatement 's SQL statement without having to compile it first.
  • Although PreparedStatement objects can be used for SQL statements with no parameters, you will probably use them most often for SQL statements that take parameters.
  • The advantage of using SQL statements that take parameters is that you can use the same
    statement and supply it with different values each time you execute it.
    Creating a PreparedStatement Object :
    As with Statement objects, you create PreparedStatement objects with a Connection method. Using our open connection con from previous examples, you might write code such as the following to create a PreparedStatement object that takes two input parameters: 
    PreparedStatement updateSales = con.prepareStatement( "UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ?"); 
     The variable updateSales now contains the SQL statement,
     "UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ?" , 
    which has also, in most cases, been sent to the DBMS and been precompiled 
      Buy It Now

creating jdbc statements

Creating JDBC Statements

  • A Statement object is what sends your SQLstatement to the DBMS.
  • You simply create a Statement object and then execute it, supplying the appropriate execute method with the SQL statement you want to send.
  • For a SELECT statement, the method to use is
    executeQuery .
  • For statements that create or modify tables, the method to use is executeUpdate .

It takes an instance of an active connection to create a Statement object. In the following
example, we use our Connection object con to create the Statement object stmt :

Statement stmt = con.createStatement();


At this point stmt exists, but it does not have an SQL statement to pass on to the DBMS.
We need to supply that to the method we use to execute stmt . For example, in the
following code fragment, we supply executeUpdate with the SQL statement from the
example above:

stmt.executeUpdate("CREATE TABLE COFFEES " +
"(COF_NAME VARCHAR(32), SUP_ID INTEGER, PRICE FLOAT, " +
"SALES INTEGER, TOTAL INTEGER)");

Since we made a string out of the SQL statement and assigned it to the variable
createTableCoffees , we could have written the code in this alternate form:
stmt.executeUpdate(createTableCoffees);

Buy It Now








creating tables in java

Creating a Table



First, we will create one of the tables in our example database. This table, COFFEES ,
contains the essential information about the coffees sold at The Coffee Break, including
the coffee names, their prices, the number of pounds sold the current week, and the
number of pounds sold to date. The table COFFEES , which we describe in more detail
later, is shown here:
COF_NAME SUP_ID PRICE SALES SALES TOTAL
AA 10 20 30
BB 30 20 50
The column storing the coffee name is COF_NAME, and it holds values with an SQL
type of VARCHAR and a maximum length of 32 characters. Since we will use different
names for each type of coffee sold, the name will uniquely identify a particular coffee
and can therefore serve as the primary key. The second column, named SUP_ID , will
hold a number that identifies the coffee supplier; this number will be of SQL type
INTEGER . The third column, called PRICE,
Syntax
CREATE TABLE COFFEES
(COF_NAME VARCHAR(32),
SUP_ID INTEGER,
PRICE FLOAT,
SALES INTEGER,
TOTAL INTEGER)


Example

String createTableCoffees = "CREATE TABLE COFFEES " +
"(COF_NAME VARCHAR(32), SUP_ID INTEGER, PRICE FLOAT, " +
"SALES INTEGER, TOTAL INTEGER)";


Buy It Now

establishing a connection to sql server

Establishing a Connection
The first thing you need to do is establish a connection with the DBMS you want to use.
This involves two steps:

(1) loading the driver and
(2) making the connection.

Loading Drivers
Loading the driver or drivers you want to use is very simple and involves just one line of
code. If, for example, you want to use the JDBC-ODBC Bridge driver, the following
code will load it:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Your driver documentation will give you the class name to use.
For instance, if the class name is jdbc.DriverXYZ ,
you would load the driver with the following line of code:
Class.forName("jdbc.DriverXYZ");
You do not need to create an instance of a driver and register it with the DriverManager
because calling Class.forName will do that for you automatically. If you were to create
your own instance, you would be creating an unnecessary duplicate, but it would do no
harm.
When you have loaded a driver, it is available for making a connection with a DBMS.
Making the Connection
The second step in establishing a connection is to have the appropriate driver connect to
the DBMS. The following line of code illustrates the general idea:
Connection con = DriverManager.getConnection(url,
"myLogin", "myPassword");


This step is also simple, with the hardest thing being what to supply for url .
If you are using the JDBC-ODBC Bridge driver, the JDBC URL will start with jdbc:odbc: .
 The rest of the URL is generally your data source name or database system. So, if you are using
ODBC to access an ODBC data source called " Fred, " for example, your JDBC URL
could be jdbc:odbc:Fred . In place of " myLogin " you put the name you use to log in to
the DBMS; in place of " myPassword " you put your password for the DBMS. So if you
log in to your DBMS with a login name of " Fernanda " and a password of " J8, " just
these two lines of code will establish a connection:

String url = "jdbc:odbc:Fred";
Connection con = DriverManager.getConnection(url, "Fernanda", "J8");



If you are using a JDBC driver developed by a third party, the documentation will tell
you what subprotocol to use, that is, what to put after jdbc: in the JDBC URL.


Buy It Now





jdbc settings oracle

Setting Up a Database

  • We will assume that the database COFFEE BREAK already exists. (Creating a database is
    not at all difficult, but it requires special permissions and is normally done by a database
    administrator.)
  • When you create the tables used as examples in this tutorial, they will be
    in the default database. We purposely kept the size and number of tables small to keep
    things manageable.
  • Suppose that our sample database is being used by the proprietor of a small coffee house called The Coffee Break, where coffee beans are sold by the pound and brewed coffee is sold by the cup.
  • To keep things simple, also suppose that the proprietor needs only two
    tables, one for types of coffee and one for coffee suppliers.
  • First we will show you how to open a connection with your DBMS, and then, since what
    JDBC does is to send your SQL code to your DBMS, we will demonstrate some SQL
    code.
  • After that, we will show you how easy it is to use JDBC to pass these SQL
    statements to your DBMS and process the results that are returned.
  • This code has been tested on most of the major DBMS products. However, you may
    encounter some compatibility problems using it with older ODBC drivers with the JDBCODBC
    Bridge.


Buy It Now




jdbc get started

Getting Started
The first thing you need to do is check that you are set up properly. This involves the
following steps:
1. Install Java and JDBC on your machine.

To install both the Java tm platform and the JDBC API, simply follow the
instructions for downloading the latest release of the JDK tm (Java
Development Kit tm ). When you download the JDK, you will get JDBC as
well. The sample code demonstrating the JDBC 1.0 API was written for
JDK1.1 and will run on any version of the Java platform that is compatible
with JDK1.1, including JDK1.2. Note that the sample code illustrating the
JDBC 2.0 API requires JDK1.2 and will not run on JDK1.1.
You can find the latest release (JDK1.2 at the time of this writing) at the
following URL:
Download It Now

2. Install a driver on your machine.
Your driver should include instructions for installing it. For JDBC
drivers written for specific DBMSs, installation consists of just
copying the driver onto your machine; there is no special
configuration needed.
The JDBC-ODBC Bridge driver is not quite as easy to set up. If
you download either the Solaris or Windows versions of JDK1.1,
you will automatically get the JDBC-ODBC Bridge driver, which
does not itself require any special configuration. ODBC, however,
does. If you do not already have ODBC on your machine, you will
need to see your ODBC driver vendor for information on
installation and configuration.
3. Install your DBMS if needed.
If you do not already have a DBMS installed, you will need to
follow the vendor's instructions for installation. Most users will
have a DBMS installed and will be working with an established
database.


Buy It Now








jdbc tutorial

JDBC Basics
In this lesson you will learn the basics of the JDBC API. We start by giving you set up
instructions in Getting Started , Setting Up a Database , and Establishing a Connection .
The next sections discuss how to create and update tables, use joins, transactions and
stored procedures. The final sections give instructions on how to complete your JDBC
application and how to convert it to an applet.


Note: Most JDBC drivers available at the time of this printing are for JDBC 1.0.
More drivers will become available for JDBC 2.0 as it gains wider acceptance.
Getting Set Up to Use the JDBC 2.0 API


If you want to run code that employs any of the JDBC 2.0 features, you will need to do
the following:
  • Download JDK 1.2, following the download instructions
  • Install a JDBC driver that implements the JDBC 2.0 features used in the code
  • Access a DBMS that implements the JDBC 2.0 features used in the code
    If your driver does not bundle the JDBC 2.0 Standard Extension API (the javax.sql package,
you can download it from the JDBC home page .

The JDBC 2.0 API enables you to do the following:
• Scroll forward and backward in a result set or move to a specific row.
• Make updates to database tables, using methods in the Java programming
language instead of using SQL commands.
• Send multiple SQL statements to the database as a unit, or a batch.


Buy It now








Generics java

Defining Simple Generics
Here is a small excerpt from the definitions of the interfacesList and Iterator in package
java.util:
public interface List
{
void add(E x);
Iterator iterator();
}
public interface Iterator
{
E next();
boolean hasNext();
}

  • This should all be familiar, except for the stuff in angle brackets.
  • Those are the declarations of the formal type parameters of the interfaces List and Iterator.
  • Type parameter can be used throughout the generic declaration, pretty much where
    you would use ordinary types (though there are some important restrictions;
  • In the introduction, we saw invocations of the generic type declaration List, such as List.
  • In the invocation (usually called a parameterized type), all occurrences of the formal type parameter (E in this case) are replaced by the actual type argument (in this case, Integer).
Buy It now





Inheriting Instance Fields and Methods

Inheriting Instance Fields and Methods
When you form a subclass of a given class, you can specify additional instance fields
and methods. In this section we will discuss this process in detail.
When defining the methods for a subclass, there are three possibilities.
1. You can Override methods from the superclass. If you specify a method with
the same signature (that is, the same name and the same parameter types), it
overrides the method of the same name in the superclass. Whenever the method
is applied to an object of the subclass type, the overriding method, and not the
original method, is executed. For example, CheckingAccount.deposit
overrides BankAccount.deposit.
2. You can inherit methods from the superclass. If you do not explicitly override a
superclass method, you automatically inherit it. The superclass method can be
applied to the subclass objects. For example, the SavingsAccount class
inherits the BankAccount.getBalance method.
3. You can define new methods. If you define a method that did not exist in the
superclass, then the new method can be applied only to subclass objects. For
example, SavingsAccount.addInterest is a new method that does not
exist in the superclass BankAccount.

Buy It now


inheritance in java

Inheritance
  • Inheritance is a mechanism for enhancing existing classes.
  • If you need to implement a new class and a class representing a more general concept is already available, then the new class can inherit from the existing <a href="http://573120-9-kcfw4skv8zbsfteak.hop.clickbank.net/" target="_top">class</a>.
For example, suppose you need to define a class SavingsAccount to model an account that pays a fixed interest rate on deposits. You already have a class BankAccount, and a savings account is a special case of a bank account. In this case, it makes sense to use the language construct of inheritance.
Inheritance is a mechanism for extending existing classes by adding methods and fields.
Syntax:
class SavingsAccount extends BankAccount
{
new methods
new instance fields
}
1)In the SavingsAccount class definition you specify only new methods and
instance fields.
2)The SavingsAccount class automatically inherits all methods and
instance fields of the BankAccount class.
For example, the deposit method automatically applies to savings accounts:

SavingsAccount collegeFund = new SavingsAccount(10);
// Savings account with 10% interest
collegeFund.deposit(500);
// OK to use BankAccount method with SavingsAccount object




Program

class SubclassName extends SuperclassName

{

methods

instance fields

}

Example:

public class SavingsAccount extends BankAccount

{

public SavingsAccount(double rate)

{

interestRate = rate;

}

public void addInterest()

{

double interest = getBalance() *

interestRate / 100;

deposit(interest);

}

private double interestRate;

}

Purpose:

To define a new class that inherits from an existing class, and define the methods

and instance fields that are added in the new class

Buy It now




return statement in java

 return statement

returns control to the invoker of a method or constructor .
ReturnStatement:

return Expressionopt ;
  • A return statement with no Expression must be contained in the body of a
    method that is declared, using the keyword void, not to return any value , or
    in the body of a constructor .
  • A compile-time error occurs if a return statement appears within an instance initializer or a static initializer .
  • A return
    statement with no Expression attempts to transfer control to the invoker of the
    method or constructor that contains it.
  • To be precise, a return statement with no Expression always completes
    abruptly, the reason being a return with no value.
  • A return statement with an Expression must be contained in a method declaration
    that is declared to return a value or a compile-time error occurs.
  • The
    Expression must denote a variable or value of some type T, or a compile-time
    error occurs.
  • The type T must be assignable to the declared result type of
    the method, or a compile-time error occurs.

Buy It now




continue Statement in java

The continue Statement
“Your experience has been a most entertaining one,” remarked Holmes
as his client paused and refreshed his memory with a huge pinch of snuff.
Pray continue your very interesting statement.”
A continue statement may occur only in a while, do, or for statement; statements
of these three kinds are called iteration statements. Control passes to the
loop-continuation point of an iteration statement.

ContinueStatement:
continue Identifieropt ;

  • A continue statement with no label attempts to transfer control to the innermost
    enclosing while, do, or for statement of the immediately enclosing methodor initializer block; this statement, which is called the continue target, then immediately

ends the current iteration and begins a new one.
Program

class Graph
 {


public Graph loseEdges(int i, int j) 
{
int n = edges.length;
int[][] newedges = new int[n][];
edgelists: for (int k = 0; k < n; ++k) 
{
int z;
search: 
{
if (k == i) 
{

else if (k == j) 
{
}
newedges[k] = edges[k];
continue edgelists;
}
 // search
} // edgelists
return new Graph(newedges);
}
}
Which to use, if either, is largely a matter of programming style.





Buy It Now



Break statement in java

The break Statement
A break statement transfers control out of an enclosing statement.
BreakStatement:
break Identifieropt ;
  • A break statement with no label attempts to transfer control to the innermost
    enclosing switch, while, do, or for statement of the immediately enclosing
    method or initializer block; this statement, which is called the break target, then
    immediately completes normally.
  • To be precise, a break statement with no label always completes abruptly, the
    reason being a break with no label.
  • If no switch, while, do, or for statement in
    the immediately enclosing method, constructor or initializer encloses the break
    statement, a compile-time error occurs.
  • A break statement with label Identifier attempts to transfer control to the
    enclosing labeled statement that has the same Identifier as its label; thisstatement, which is called the break target, then immediately completes normally.
  • In this case, the break target need not be a while, do, for, or switch statement.
  • A break statement must refer to a label within the immediately enclosing method
    or initializer block. There are no non-local jumps.
Prorgam


class Graph
{
int edges[][];
public Graph(int[][] edges)
{
 this.edges = edges;
}
public Graph loseEdges(int i, int j)
 {
int n = edges.length;
int[][] newedges = new int[n][];
for (int k = 0; k < n; ++k)
{
 edgelist:
 {
int z;
 search:
 {
if (k == i)
{
for (z = 0; z < edges[k].length; ++z)
 if (edges[k][z] == j)
break search;
 }
else if (k == j)
{
 for (z = 0; z < edges[k].length; ++z)
 if (edges[k][z] == i) break search;
}
 // No edge to be deleted;
share this list. newedges[k] = edges[k]; break edgelist;
 }
//search // Copy the list, omitting the edge at position z.
int m = edges[k].length - 1;
int ne[] = new int[m];
System.arraycopy(edges[k], 0, ne, 0, z);
 System.arraycopy(edges[k], z+1, ne, z, m-z);
 newedges[k] = ne; 

//edgelist
}
 return new Graph(newedges); 
}
 }


buy it now





For Statement in java

for Statement
ForStatement:

1)BasicForStatement
2)EnhancedForStatement

The for statement has two forms:

• The basic for statement.
• The enhanced for statement

The basic for Statement

The basic for statement executes some initialization code, then executes an
Expression, a Statement, and some update code repeatedly until the value of the
Expression is false.

BasicForStatement:


for ( ForInitopt ; Expressionopt ; ForUpdateopt ) Statement

ForStatementNoShortIf:


for ( ForInitopt ; Expressionopt ; ForUpdateopt )
StatementNoShortIf
ForInit:


StatementExpressionList
LocalVariableDeclaration

ForUpdate:


StatementExpressionList
StatementExpressionList:


StatementExpression
StatementExpressionList , StatementExpression
The Expression must have type boolean or Boolean, or a compile-time error
occurs.



The following example, which calculates the sum of an integer array, shows how enhanced
for works for arrays:


int sum(int[] a) 
{
int sum = 0;
for (int i : a)
sum += i;
return sum;
}


Here is an example that combines the enhanced for statement with auto-unboxing to translate
a histogram into a frequency table:


Map histogram = ...;
double total = 0;
for (int i : histogram.values())
total += i;
for (Map.Entry e : histogram.entrySet())
System.out.println(e.getKey() + "" + e.getValue() / total);

do statement java

The do Statement
“She would not see it,” he said at last, curtly,
feeling at first that this statement must do without explanation.
The do Statement  executes a Statement and an Expression repeatedly until the
value of the Expression is false.

Syntax:


do Statement while ( Expression ) ;


The Expression must have type boolean or Boolean, or a compile-time error
occurs.
A do statement is executed by first executing the Statement. Then there is a
choice:
• If execution of the Statement completes normally, then the Expression is evaluated.
If the result is of type Boolean, it is subject to unboxing conversion
• If evaluation of the Expression or the subsequent unboxing conversion
(if any) completes abruptly for some reason, the do statement completes
abruptly for the same reason. Otherwise, there is a choice based on the resulting
value:
• If the value is true, then the entire do statement is executed again.
• If the value is false, no further action is taken and the do statement completes
normally.
• If execution of the Statement completes abruptly,.1 below.
Executing a do statement always executes the contained Statement at least once.

Program

public static String toHexString(int i) 
{
StringBuffer buf = new StringBuffer(8);
do
 {
buf.append(Character.forDigit(i & 0xF, 16));
i >>>= 4;
}
 while (i != 0);
return buf.reverse().toString();
}




C Tutorial

Buy 1 Get 1 Free Xmas Sale


c tutorial for beginner .this site can be providing basic lesson for beginner


Lesson 1


Identifiers

Under Line


Comments  

Formatting Text

Expression



Lesson 2


reserved words

printf conversion specifiers

primitive data types

preprocessor directives

Input and Output function

Constant in c

Character Utilities

Directive


#ifndef
#ifdef

#if
#include

#line

#error

#define

Lesson 3

Comparison and Logic operator Arthimetic operator
Operator Precedence cast Operator
Special operator

Lesson 4


int type

signed type

char type

real type

Lesson 5


Parameter

Declaration

Lesson 6


While Loops

For Loops

Do While Loops

If Condition


Else-If Condition

Switch Statement

Goto

Nested if statement



Up to 85% OFF, Pugster Fashion Wedding Jewelry !



Lesson 8


Function Introduction

Preprocessor

Function declaration

Function definition

No argument and no return type
argument and no return type


Math Function

Math Error



Lesson 9



Array Introduction

Use of Array

Initializing Arrays

Arrays as parameter

Arrays as pointer

Lesson 10


File Position

Read And Write In files

File Function

Lesson 11


Structure

Declaring Structure
Initialization Of Structure
Struct keyword
Copying Structure

math.h

math.h
sizeof() abort()
fmod() modf()
atoi() sqrt()
scanf pow()
log() atan()
asin() atan()

Stdio.h

clearerr() fdopen()
fflush() ferror()
rewind() putchar()
getchar() feof()
putw() getw()
fseek()

alloc.h

realloc() farralloc()
farcoreleft() coreleft()
farmalloc() brk()
sbrk() malloc()
calloc()

conio.h

ungetch() wherex()
gettextinfo() gettext()
getche() getpass()
cputs() delline()
clrscr() getch()
clreol() cgets()

dos.h

bdos() delay()
disable() enable()
freemem() getdta()
freemem() absread()
keep() getdate()
setdate() sound()
getverify() unixtodos()