Creating Simple Window in Java: using swings

This Java video tutorial demonstrates the creation of a simple window by importing Swings package and extending JFrame class.

import javax.swing.*;

javax.swing provides a set of lightweight components that, to the maximum degree possible, works the same on all platforms.

myWindow Class

class myWindow extends JFrame
{
 
}

myWindow is user the name given to the defined class. extends is the keyword. JFrame is a built-in class of swing package.

Constructor

 myWindow()
 { 
		setTitle("My window program, using Swings");
		setSize(400, 200);
		setVisible( true );
		setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
 }

myWindow() is the constructor, and thus it’s name matches with that of its class name.
setTitle() : To set the string present on the title bar of the window we are creating.
setSize() : To set the size of the window. It takes two parameters, width and height of the window.
setVisible() : It’s very important for all the programs which involves visual components. passing a value of true makes the window visible.

Main method

	public static void main(String args[])
	{
		 // new myWindow();
		myWindow m1 = new myWindow();
	}

main method just calls the constructor. We can simply write new myWindow() since we are not at all taking the help of any object here.

Video Tutorial: Creating Simple Window in Java: using swings


You need to a flashplayer enabled browser to view this YouTube video

YouTube Link: http://www.youtube.com/watch?v=7ThtNST8gKE [Watch the Video In Full Screen.]



Full Source code to create a simple window in Java: using swings

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import javax.swing.*;
 
class myWindow extends JFrame
{
	myWindow()
	{
		setTitle("My window program, using Swings");
		setSize(400, 200);
		setVisible( true );
		setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
	}
 
	public static void main(String args[])
	{
		 // new myWindow();
		myWindow m1 = new myWindow();
	}
}

Output:
window-swing-java

Read Keyboard Input: Java

This video tutorial shows how to read user input from Keyboard in Java.

In this tutorial we illustrate using a relatively simple program, where user is asked to input some string and it is read by the program and then out put to the console window. Simple java program.

Import
We have to import io package, so that we can make use of DataInputStream Class present in io package.

    import java.io.*;

Creating Object
Next, we create an object of the inbuilt class DataInputStream. And not that it takes a parameter System.in for reading keyboard inputs.

DataInputStream d = new DataInputStream(System.in);

try catch
To know more about try catch and finally read: Try, Catch and Finally in Java.

Since user can give any kind of unwanted input, we should write those code (which may rise exception) inside the try block.
and write the corresponding catch statement.

		try
		{
			System.out.println("Entered String is: "+d.readLine());	
		}
		catch(Exception e)
		{
			System.out.println(e);	
		}

Video Tutorial: Read Keyboard Input: Java


You need to a flashplayer enabled browser to view this YouTube video

YouTube Link: http://www.youtube.com/watch?v=FzUOZo3AX2Y [Watch the Video In Full Screen.]




Full Source Code:(keyboardInput.java)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import java.io.*;
 
class keyboardInput
{
	public static void main(String args[])
	{
		DataInputStream d = new DataInputStream(System.in);
 
		System.out.println("Enter a string");
		try
		{
			System.out.println("Entered String is: "+d.readLine());	
		}
		catch(Exception e)
		{
			System.out.println(e);	
		}
 
	}
}

Output:
Enter a string
Microsoft Windows 8
Entered String is: Microsoft Windows 8

Try, Catch and Finally in Java

This Java Video Tutorial illustrates the use of try, catch and finally along with the Exceptions like: ArrayIndexOutOfBoundsException, ArithmeticException.

Exceptions:
Checked Exceptions: Environmental error that cannot necessarily be detected by testing; e.g. disk full, broken socket, database unavailable, etc.
Errors: Virtual machine error: class not found, out of memory, no such method, illegal access to private field, etc.
Runtime Exceptions: Programming errors that should be detected in testing: index out of bounds, null pointer, illegal argument, etc.

Checked exceptions must be handled at compile time. Runtime exceptions do not need to be. Errors often cannot be.

Why to use Exceptions:
To handle the situations where the code acts the way you did not intend it to act.
For example, if the user tries to divide a number by zero: user keyboard input.

In such a situation, we need to handle the code to make the program work with stability.

Note:
There can be only one try block and any number of catch blocks can be written.

Array declaration:

int[] array = new int[3];

array is the variable name.

Try block which generates ArrayIndexOutOfBoundsException Exception:

	try
		{
			for(int i=0; i<4; i++)
			{
			array[i] = i;
			System.out.println(array[i]);
			}
		}

Notice that we have array[0], array[1], array[2] but we are trying to print even array[3] which isn’t present.
Notice the for loop, it executes 4 times, instead of 3 times, so raising exception.

Try block which generates ArithmeticException Exception:

		try
		{
			for(int i=0; i<3; i++)
			{
			array[i] = i;
			System.out.println(array[i]);
			}
 
			array[0] = 2/0;
		}

Notice the division by zero.
We purposefully assign 2/0 to array[0] to raise ArithematicException.

Super Class: Exception

catch(Exception e)
{
	System.out.println("You did some mistake, correct yourself!");
}

those exceptions which are not caught by those specific Exception handlers, those and any other unknown or unexpected exception are handled by Exception class.

Finally:

finally
{
	System.out.println("I get executed each time irrespective of the situation!");
}

the code inside finally block gets executed irrespective of the exception being raised or not.
That is, the code inside finally block will always be executed, if the program doesn’t crash!

Video Tutorial: Try, Catch and Finally in Java


You need to a flashplayer enabled browser to view this YouTube video

YouTube Link: http://www.youtube.com/watch?v=_j99G6u206o [Watch the Video In Full Screen.]




Full Source Code:(execute.java)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import java.lang.*;
 
class exception
{
 public static void main(String args[])
 {
	int[] array = new int[3];
 
	try
	{
		for(int i=0; i<3; i++)
		{
		array[i] = i;
		System.out.println(array[i]);
		}
 
	//	array[0] = 2/0;
	}
	catch(ArrayIndexOutOfBoundsException e)
	{
		System.out.println("Do not try to print more than it can store!");
	}
	catch(ArithmeticException e)
	{
		System.out.println("Do not divide by zero..learn math!");
	}
	catch(Exception e)
	{
		System.out.println("You did some mistake, correct yourself!");
	}
 
	finally
	{
	System.out.println("I get executed each time irrespective of the situation!");
	}
 
 }
}

Output:
0
1
2
I get executed each time irrespective of the situation!

Display System Date and Time: Java

This Java Video Tutorial shows how to extract and display system date(with time stamp).

Inorder to make this program work, you MUST include or import Date class of util package.

  import java.util.Date;

Video Tutorial: Extract and display System Date and Time: Java


You need to a flashplayer enabled browser to view this YouTube video

YouTube Link: http://www.youtube.com/watch?v=XwQfh8i81r4 [Watch the Video In Full Screen.]




We create an object of class Date, and just display its content.

Full Source Code:(SysDate.java)

1
2
3
4
5
6
7
8
9
10
11
12
import java.lang.*;
import java.util.Date;
 
class SysDate
{
	public static void main(String args[])
	{
		Date d1 = new Date();
 
		System.out.println(d1);
	}
}

Output:
Sun Sep 11 17:33:50 IST 2011

Addition/Subtraction of Complex Number: Java

Video Tutorial and Free source code: Addition and Subtraction of Complex numbers in Java.
It also explains about Do Nothing Constructor.

Complex numbers are of the form x+iy. Where x is the real part and iy is the imaginary part.

In this program we are using parameterized constructor to copy the real and imaginary values of the objects created, into the local variables of the class calc.(float real, img;)

	calc(float r, float i)
	{
			real = r;
			img = i;
	}

Passing values to parameterized constructor:

		calc c1 = new calc(12.5F, 2.5F);
		calc c2 = new calc(09.5F, 0.5F);

But since we are also creating a third object c3, which doesn’t pass any parameter values, we need to write a default constructor even though it doesn’t contain any definition in it. Such a constructor is called Do Nothing Constructor.

calc c3 = new calc(); //Not Passing any value, 
                      //hence it starts searching for default constructor.

This is Do Nothing Constructor:

calc() { }

Now the actual addition of complex number:
The return type is calc, as it has to return value to be stored in object c3(which is of type calc).
Here, we add the real part of c1 to the real part of c2. Imaginary part of c1 to imaginary part of c2, and return the value and display the result.

	calc add(calc c2)
	{
		calc res = new calc();
 
		res.real = real + c2.real;
		res.img = img + c2.img;
 
		return(res);
	}

Since c1 object called the add method, we need not again write c1.real and c1.img Instead we can directly write real and img.

c3 = c1.add(c2);

Similarly, subtraction of complex numbers:
Here, we subtract the real part of c1 to the real part of c2. Imaginary part of c1 to imaginary part of c2, and return the value and display the result.

	calc sub(calc c2)
	{
		calc res = new calc();
 
		res.real = real - c2.real;
		res.img  = img - c2.img;
 
		return(res);
	}

Call to Subtraction method:

c3 = c1.sub(c2);

Video Tutorial: Addition and Subtraction of Complex Number: Java


You need to a flashplayer enabled browser to view this YouTube video

YouTube Link: http://www.youtube.com/watch?v=tfiTMjwDqKM [Watch the Video In Full Screen.]



Full Source Code:(Complex.java)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import java.lang.*;
 
class calc
{
	float real, img;
 
	calc() {}        // Do Nothing Constructor
 
	calc(float r, float i)
	{
			real = r;
			img = i;
	}
 
	void display()
	{
		System.out.println(real+" + i "+img);
	}
 
	calc add(calc c2)
	{
		calc res = new calc();
 
		res.real = real + c2.real;
		res.img = img + c2.img;
 
		return(res);
	}
 
	calc sub(calc c2)
	{
		calc res = new calc();
 
		res.real = real - c2.real;
		res.img = img - c2.img;
 
		return(res);
	}
 
}
 
class Complex
{
	public static void main(String args[])
	{
		calc c1 = new calc(12.5F, 2.5F);
		calc c2 = new calc(09.5F, 0.5F);
 
		System.out.println("C1 is: ");
		c1.display();
		System.out.println("C2 is: ");
		c2.display();
 
		calc c3 = new calc();
 
		System.out.println("Addition of C1 and C2 is: ");
		c3 = c1.add(c2);
		c3.display();
 
		System.out.println("Subtraction of C1 and C2 is: ");
		c3 = c1.sub(c2);
		c3.display();
	}
}

Output:
C1 is:
12.5 + i 2.5

C2 is:
9.5 + i 0.5

Addition of C1 and C2 is:
22.0 + i 3.0

Subtraction of C1 and C2 is:
3.0 + i 2.0

Method/Function Overloading in Java

In Java, function overloading is called Method Overloading.

Definition: In java method overloading means creating more than one method with same name but with different signature.
i.e., If name of the method remains common but the number and type of parameters are different, then it is called method overloading in Java.

Overloaded Methods:
Here, these methods have same return type and name, but the signature(i.e., the parameter it takes are different).

	void sum(int a, int b)
	{
		System.out.println("Int: Sum of "+a+" and "+b+" is "+(a+b));
	}
 
	void sum(float a, float b)
	{
		System.out.println("Float: Sum of "+a+" and "+b+" is "+(a+b));
	}
 
	void sum(String a, String b)
	{
		System.out.println(a+" "+b);
	}

One takes int value, other takes float value and the 3rd takes two string values as parameters.

These parameter type decides which method to call.

Video Tutorial for the working of Method/Funtion overloading in Java


You need to a flashplayer enabled browser to view this YouTube video

YouTube Link: http://www.youtube.com/watch?v=x7WMSdgMq60 [Watch the Video In Full Screen.]



Full Source Code:(overLoad.java)

import java.lang.*;
 
class work
{
	void sum(int a, int b)
	{
		System.out.println("Int: Sum of "+a+" and "+b+" is "+(a+b));
	}
 
	void sum(float a, float b)
	{
		System.out.println("Float: Sum of "+a+" and "+b+" is "+(a+b));
	}
 
	void sum(String a, String b)
	{
		System.out.println(a+" "+b);
	}
 
}
 
class overLoad
{
	public static void main(String args[])
	{
		work w1 = new work();
 
		w1.sum(10,20);
		w1.sum(10.5F,1.5F);
		w1.sum("I Love","You!");
	}
}

output:
Int: Sum of 10 and 20 is 30
Float: Sum of 10.5 and 1.5 is 12.0
I Love You!

Using Constructors & Member Function to add two numbers: Java

In this Java video tutorial we have covered both ways of adding numbers: using constructors as well as using methods.

Constructors:

Constructor name and the class name must be same.
No return type.
There are 3 types of constructors:
1. Default constructors.
2. Parameterized constructors.
3. Copy Constructors.

In this video tutorials we have shown the use of Parameterized constructors.

	calc(int a, int b)
	{
		no1 = a;  
		no2 = b;  
	}

Adding and displaying the result:

	public void sum()
	{
		System.out.println("Sum of "+no1+" and "+no2+" is "+(no1+no2));
	}

Strings are written inside double quotes and the variables written outside the double quotes will display the value stored in them.
+ (plus) is concatenation operation.
(no1+no2) adds the value present in no1 and no2 and displays the result of addition.

Video Tutorial


You need to a flashplayer enabled browser to view this YouTube video

YouTube Link: http://www.youtube.com/watch?v=gUXq1psurdk [Watch the Video In Full Screen.]



Object Creation:

/* calc c; 		// object declaration. It will have null in it.
   c = new calc(20,10); // Construction call
*/
 
   calc c = new calc(30, 10);

Full Java code: Using Constructors & Member Function to add two numbers(add.java)

import java.lang.*;
 
class calc
{
	int no1, no2;
 
	calc(int a, int b)
	{
		no1 = a;  // 30
		no2 = b;  // 10
	}
 
/*
	public void assign(int a, int b)
	{
				no1 = a;  // 30
		                no2 = b;  // 10
	}	
*/
 
	public void sum()
	{
		System.out.println("Sum of "+no1+" and "+no2+" is "+(no1+no2));
	}
}
 
class add
{
	public static void main(String args[])
	{
		/* calc c; 		// object declaration. It will have null in it.
		c = new calc(20,10); 	// Construction call
		*/
 
		calc c = new calc(30, 10);
		//c.assign(30,10);
		c.sum();
	}
}

Member functions are called with the help of object.
Syntax:
object.memberfuntion();

First Java Program: Basic

This Java tutorial will illustrate the basics of all java programs.

class Welcome

Class is a keyword. Welcome is an identifier or name of the class.
Class Welcome is declaration of class.

class Welcome
{
 
}

Every class definition in Java begins with an opening brace and ends with a matching closing brace. Note that there is no ending semicolon in Java unlike in C++.

public static void main(String args[])
	{
		System.out.println("Welcome To Java!");
	}

main() is the starting point for the interpreter to begin execution of the program. A java application can have any number of classes but only one of them must include a main method.
void: since main does not return any value;
static: Java is a pure object oriented programming language and hence even main is written inside of a class. main() belongs to the entire class and not a part of any objects of the class, so main is declared as static.
public: methods with public access specification can be accessed even outside the class.

String: is a built-in class, present inside java.lang package.
args[] : is a array variable, used to get the arguments from the user.

System.out.print() or System.out.println() is similar to printf() in C or cout>> in C++.
print() or println() method is a member of the out object, which is a static data member of System class.

Full Java code to print “Welcome to Java!” (Welcome.java)

1
2
3
4
5
6
7
class Welcome
{
	public static void main(String args[])
	{
		System.out.println("Welcome To Java!");
	}
}

Video Tutorial



YouTube Link: http://www.youtube.com/watch?v=lXaFnboq3sk [Watch the Video In Full Screen.]






YouTube Link: http://www.youtube.com/watch?v=ePG4GE3hmbY [Watch the Video In Full Screen.]



Please watch the above video tutorial in full screen.