Simple 'Try and Catch' Example


import java.io.*;

public class TryCatchExample
{
public static void main (String args[]) throws IOException
{
BufferedReader HelloWorld = new BufferedReader(new InputStreamReader(System.in));


System.out.println("Enter A Number: ");


try
{
int GalaxyNumber = Integer.parseInt(HelloWorld.readLine());
}


catch (NumberFormatException ShowError)
{
System.out.println("Enter A Number: ");
}
}

you can also have...


catch (NumberFormatException ShowError)
{
System.out.println(ShowError);
}



instead of...


catch (NumberFormatException ShowError)
{
System.out.println("Enter A Number: ");
}


... to know the error.

Try and Catch

Try - Make an attempt or effort to do something
Catch - Intercept and Hold

Syntax:

try
{
statement(s);
}

catch (Exception Handler Tag)
{
statement(s);
}


The try and catch  allows you to test a block of errors. Once it encounters a block of errors in the try, it passes it to the tag. A tag is a variable that hold the exception. The statements under the catch are to be executed once the try receives an error (it catches the errors from the try).

Exception Handler is an exception. An exception an error. Famous exceptions are IOException and NumberFormatException.

For an example of a try and catch, refer to the next post.

Creating a GUI of a Simple Calculator



The image above is a simple calculator found in Windows; while the image below is a simplier version of calculator compared to the one above.


And yes, it is created in Java. Try to create your own version of a Java Calculator using the simple operations. The code will be posted in a few days.

PS
Just the GUI. Never mind the functions yet.

Ways to Use Inheritance

There are two ways to use Inheritance in Java.

1. Using the Extend keyword
     As you have learned from the previous lesson, the extend keyword is used in Method Overriding, which is a part of Polymorphism. We use it to refer the different methods and variables in a parent or super class that can be used in the parent of child class. Given the example from the previous post...


class first
{
int number;

void Add()
{
number=number+1;
}

void Subtract()
{
number=number-1;
}
}
class second extends first
{
void Add()
{
number=number*1;
}
void Divide()
{
number=number/1;
}
}
public class MClass
{
public static void main (String args[])
{
first one = new first();
one.Add();
one.Subtract();

second two = new second();
two.Add();
two.Divide()
}
}



2. Constructor Method
     A constructor method is commonly used (beginners) in creating methods in a simple program. The constructor method uses parameters to connect values from the object class to the main class. For example, given a Sample Class and a Main Class...


class Sample
{
void test()
{
System.out.println("Test");
}
}

public class MainClass
{
public static void main (String args[])
{
Sample x = new Sample();
}
}


The output will only display Test.

Inheritance

In Java, the following terms are often used:

  • Super Class - the topmost part of the class
  • Parent Class - the class before the child class
  • Child Class - the last class in the program
To understand fully, here's a sample of a family tree.







Obviously, the child (classes) are the following:

  • Me
  • Brother
  • Sister
  • Cousin; and
  • OTHER Cousin
The Parent Classes are:
  • Mommy and Daddy Smith
  • Uncle and Aunt Trotter
  • Aunt and OTHER A.N
The Super Class are:
  • Grandad and Granny Jones
  • Great Grandad and Great Granny Bloggs
However, Java does not support multiple inheritance. Java can only hold one Super Class, one Parent Class, and one Child Class.

GUI Basics

A GUI is an acronym of Graphical User Interface, and is sometimes pronounced as Gooey. Visual Basic has a very good example of GUI wherein you can draw your objects freely with the use of the mouse. However, in Java, you have to plot it point by point.

The first thing in creating a GUI in Java is to use everything in the swing package and to override swing's JFrame by using the extend keyword.

Our main goal in this lesson is to create a simple GUI of an ATM Machine with two labels and textboxes (Card Number and Pin), two buttons (OK and Cancel) and name it ATM.





Below is the code with explanations...


import javax.swing.*;  //use everything within the swing package
public class CodeGalaxy extends JFrame  //overrides JFrame
{

JTextField txt1 = new JTextField();  //JTextField is equivalent to a textbox
JLabel CardN = new JLabel("Card Number: ");  //JLabel is equivalent to a label

JTextField txt2 = new JTextField();
JLabel PIN = new JLabel("Pin: ");

JButton OKbtn = new JButton("OK");  //JButton is equivalent to a command button
JButton Can = new JButton("Cancel");


public CodeGalaxy()   //constructor method with the same name of your class
{

//shows the output of the Card Number


getContentPane().setLayout(null);   //set to nothing / null 
CardN.setBounds(70,10,90,10); //setBounds defines the boundary of your object
getContentPane().add(CardN);

txt1.setBounds(150,10,150,18);
getContentPane().add(txt1);

//same flow of idea as to the Card Number//

//shows the output of the PIN
PIN.setBounds(70,30,80,10);
getContentPane().add(PIN);

txt2.setBounds(150,30,150,18);
getContentPane().add(txt2);


//shows Ok button
OKbtn.setBounds(230,60,70,30);
getContentPane().add(OKbtn);


//shows Cancel button
Can.setBounds(70,60,90,30);
getContentPane().add(Can);


setTitle("ATM");   //sets the title as ATM
setSize(400,130);  //sets the size
setVisible(true);  //makes our ATM visible

}

public static void main (String args[])
{
CodeGalaxy x = new CodeGalaxy();
}
}



Further explanation:

setBounds syntax:
variable.setBounds(x-axis,y-axis,width,height);

setSize syntax:
setSize(width, height);


public static void main (String args[])
{
Lab3 x = new Lab3();
}
without the public static void main, our program will run invisibly.

JTextField txt1 = new JTextField();
JTextField is a textbox with the variable name txt1


JLabel PIN = new JLabel("Pin: ");
JLabel is a label with the variable name PIN with the caption as Pin:


JButton Can = new JButton("Cancel");
JButton is a command button with the variable name Can with the caption as Cancel

The 'extend' keyword


class first

{
int number;


void Add()
{
number=number+1;
}


void Subtract()
{
number=number-1;
}
}
class second extends first
{
void Add()
{
number=number*1;
}
void Divide()
{
number=number/1;
}
}
public class MClass
{
public static void main (String args[])
{
first one = new first();
one.Add();
one.Subtract();


second two = new second();
two.Add();
two.Divide()
}
}

Given the code above, second extends first where second inherits first's methods and variable. As you can see the variable in class first  and class second is the same, which is number, though number is only declared in class first. Class Second overrides the Add method and added a Divide method.

When class second extends to first, we call second as a subclass of first and first is the superclass of second. In java, two or more classes can inherit from the same parent class but a class can only have one parent.

Method Overriding

Let's start with an example. If Aphrodite Keys is a famous celebrity, her mother, Hera Keys is also a famous celebrity. Whatever the parent is doing is inherited by the child.

In programming, method overriding means that whatever the parent class is doing, it is inherited by the child class. Given the code below:


class CodeGalaxy

{
public void planet()
{
System.out.print("Pluto is not considered a planet");
}
}


class MilyWay extends CodeGalaxy
{
public void planet()
{
System.out.print("How many planets do we have now?");
}
}


public class RunningCode
{
public static void main(String args[])
{
CodeGalaxy output1 = new CodeGalaxy();
CodeGalaxy output2 = new Milkyway();


output1.planet();
output2.planet()
}
}


Class MilkyWay extends CodeGalaxy is better understood as MilkyWay overrides CodeGalaxy.  The output will be:

Pluto is not considered a planet.How many planets do we have now?

For more on Overriding, refer to next post about the extend keyword.

Method Overloading


Whenever a two or more methods have the same name but different behaviors or parameters, it is called method overloading.

A good example of method overloading is a set (or a pair) of people with the same name. A very good example to understand this are social networking sites. Let's say that there are two people with the name Aphrodite Keys on Facebook. The first Aphrodite Keys is a famous celebrity, while the second is just a poser.

Between the two Aphrodite Keys, it is obvious that both have the same name. It is also obvious that both have different personalities and behaviors.  The original Aphrodite Keys posts updates regarding her work and insights of life honestly, while the poser Aphrodite Keys posts different things that may help gain her social network fame.

Given the codes below....

class CodeGalaxy
{
public int sum;

public CodeGalaxy()
{
sum = 0;
}

public void Add(int num1, int num2)
{
sum = num1 + num2;
}

public void Add(int num1, int num2, int num3)
{
sum=int1+num2+num3;
}

public void Add(int num1)
{
sum = num1;
}
}

The code of the main class is the following:

public class UseGalaxy
{
public static void mai (String args[])
{
CodeGalaxy planet = new CodeGalaxy();
planet.Add(2,3);
planet.Add(1,2,3);
planet.Add(100);
}
}

Using the first planet.Add with parameters 2 and 3, the values are passed on the first (public void) Add in your object. The values of the second planet.Add with parameters 1,2 and 3, are passed on the second (public void) Add in your object. The last planet.Add with 1 as its parameter is passed on the last method in your object.

The main idea is: You cannot pass planet.Add(2,3)  to the second method in your object with public void Add(int1, int2, int3) since planet.Add has only two values and the method requires three values. Therefore, in order to use planet.Add(2,3), the values are passed on the first method with public void Add(int1,int2)

Parameters and Polymorphism

Parameters
A parameter is a special variable that are used as a subroutine to connect to another piece of an inputted data in that subroutine. Some programming languages refer parameters as arguments. There are two kinds of parameters: formal parameter and actual parameter.


Formal Parameter
Formal parameters are actually any kinds of variables placed inside a parenthesis. In the example below, the formal parameters are num1 and num2

class CodeGalaxy
{
public int sum;

public CodeGalaxy()
{
sum = 0;
}

public void Add(int num1, int num2)
{
sum = num1 + num2;
}
}


Actual Parameters
An actual parameter is the value of the formal parameter. In the example below, the actual parameters are 2 and 3. The values of the actual parameter are passed to the formal parameter. If you refer to the codes above (formal) and the codes below (actual), 2 is passed to the formal parameter num1, while 3 is passed to the formal parameter num2.


public class UseGalaxy
{
public static void mai (String args[])
{
CodeGalaxy planet = new CodeGalaxy();
planet.Add(2,3);
}
}



Polymorphism
Polymorphism originated from the Greek word poly which means many, and morph which means form. Therefore, polymorphism means many forms. In programming, polymorphism is a variable, function, or (commonly) an object that has many forms. The main purpose of polymorphism in programming is for creating one name that can be used for a general class. Method Overriding and Method Overloading is a type of Polymorphism.

For more polymorphism, see next post (Method Overloading and Method Overriding)

Packages (Java)

What is a Package?


Java allows us to group classes in a collection, known as the Package.


A package is a helpful tool in organizing our work as well as separating our work from the libraries of codes made by others.

The standard Java library is known to have distributed over a number of packages, including the following:


  • java.util
  • java.lang
  • java.net
Reason for Using Packages


The purpose of using packages is to guarantee the uniqueness of class names. Two junior programmers, for example, come up with a good idea of supplying a price class. As long as the two programmers place their class in different packages, there is nothing wrong with it.

The sole purpose of package nesting is to manage their unique names. From the point of view of the complier, there is absolutely no relationship between nested packages. Similar to the packages java.util and java.util.jar both have nothing to do with each other since each has its own independent collection of classes.


Using Packages


A class can use all classes from its own package, including all public classes from other packages. There are indeed two ways to access public class, and those are the following:

1. Add the full package name in front of every class name

java.util.Date today = new java.util.Date();


2. The import keyword

import java.io.*;



The IMPORT keyword


The import statement gives you a shorthand to refer classes in the package. Once you use it, yo no longer have to give the classes their full names.

The * symbol is only used to import a single package. It makes you import the whole package itself.

Order of Precedence for Java Operators

Similar to Mathematics' PEMDAS or MDAS, Java also has its own Order of Precedence which is to be followed when understanding, creating or reading Java programs. It is a way for Java to determine which operator should it evaluate first before the others.

Below is the Order of Precedence displayed from the highest to the lowest precedence:


Priority  Operator  Use
1[ ]index of arrays

( )calling methods

.access members
2++increment

--decrement

+, -unary add, subtract

~NOT (bitwise)

!NOT (boolean / logical)

(type)new type cast

(new)new object
3*, /, %multiplication, division, modulo (remainder)
4+, - addition, subtraction 

+concatination
5<<signed bit shift left

>>signed bit shift right

>>>unsigned bit shift right
6<, <=less than, less than or equal to

>, >=greater than, greater than or equal to

instanceofcalling/testing references
7= =is equal to

! =is not equal to
8&AND (bitwise and logical)
9^XOR (bitwise and logical)
10|OR (bitwise and logical)
11&&Boolean AND
12||Boolean OR
13?, , , :conditional statements
14=assignment

*=, /=, +=, -=combinated assignment

%=combinated assignment

<<=, >>=combinated assignment

&=,^=, |=combinated assignment


Reminder:
  • Expressions within the parenthesis are first to be evaluated
  • Nested Parenthesis are evaluated from the inner to the outer parenthesis.
  • Higher precedence are done first before the lower precedence.

Stacks and Queues in Java

The stack and the queue is defined by two basic operations: insert a new item, and remove an item.



Representing stacks and queues with arrays is a natural idea. The rule used for a queue is to always remove the item that has been in the collection the most amount of time. This policy is known as first-in-first-out or FIFO. The rule used for a stack is to always remove the item that has been in the collection the least amount of time. This policy is known as last-in first-out or LIFO.

In stacking, we name the stack insert method push() and the stack remove operation pop(). When we queue, we name the insert method enqueue() and the remove dequeue().

Here's an exercise we just did in school today though it's quite complicated, i just wanna share the codes. It's about push(inserting) and pop(deleting) for the stack; as well as enqueue(inserting) and dequeue(deleting). Download the codes below:







It's important to download all three files.

VB6 Listbox

I'm posting an exercise of Visual Basic Properties for the List Box tool. Check this out.

Given this two listboxes where the first listbox lists the different states of the United States, and the second listbox with an empty list.

Image by VBExplorer

Let's rename the lists of the first listbox. Instead of a list of the different states, try to list down different dishes and put a little label below the listbox with the caption, Menu. Name the first listbox as lstMenu. Under the second listbox with an empty list, put another label below it with the caption of Orders. Name the second list box as lstOrders.

So what's the catch? Once you select a dish from lstMenu and press the >>>> button, that dish will be copied to lstOrders.

Solution:

Double click on the >>>> button and type the following:

Private Sub cmdLeft_Click()
listOrders.RemoveItem listOrders.ListIndex
End Sub

Next, double click on the second button (with the caption of <<<<) and type the code:

Private Sub cmdRight_Click()
listOrders.AddItem (listMenu)
End Sub

Once you get it right, you are now free to play with menu-order system by clicking on the >>>> and <<<< buttons. See how the texts appear and disappear in the empty listbox.

What is the use of Compiling in Java?


 Here's a diagram of Computer Languages.

Machine language is all it starts since our computer can only read numbers 1 and 0. Then there goes Low-level languages, where a very good example is Assembly language and the C programming (language. Then there is High-level language, where you can find Visual Basic and Java.


So what's the use of Compiling in Java? Why can't you not run the program right away without compiling?

Because Java is one of the High-level languages, it translates it to a low level language and finally, machine language since as said earlier that our computer can only read binary digits.



So that means that the codes we type and the variables we create are translated to a language which the computer can only understand.

We cannot understand Machine Language immediately. It takes time to understand each line of Machine Language since each 1 and 0 has its own designated meaning depending on how we code it.

For Next Loops in Visual Basic 6.0

A For Next Loop lets you execute a specific group of program statements a  set of number times in an event procedure. This is useful if you are performing several related calculations, working with elements on screen ot processing several pieces for user inputs.

A For Next Loop is just a shortcut of writing a long list of statements. Because each group of statements in such a list would do essentially the same thing, VB lets you define just one group of statements and request that it would be executed as many times as you want.

In a For Next Loop, start and end determine how long the loop runs

Check the syntax below:


for your_variable = start To end
     code block
     or
     statements to be repeated
Next your_variable

Example:
The following For Next Loop sounds four beeps in rapid succession from the computer's speakers:

For x =  1 To 4
     Beep
Next x

so the output of that would be:

Beep
Beep
Beep
Beep



Based from the book Step by Step Microsoft Visual Basic

Until Keyword in Do [While] Loops

Visual Basic lets you try the Until keyword in Do [While] Loops until a certain condition is true. The Until keyword can be used at the top or the bottom of a Do [While] Loop to test a condition (similar to the While Loop).

Check this example below
Do
     InputName = InputBox("Enter item or type Finish to quit.")
     If InputName <> "Finish" Then Print InputName
Loop Until InputName = "Finish"


Based from the book Step by Step Microsoft Visual Basic

Do Loops on Visual Basic

A Do Loop executes a line, or lines of code until a specific condition is met. It is sometimes referred as Do While Loops to some.

For example, you want to let the user enter names in a database until the user types the word Finish in an input box, or maybe until the user clicks the Done button. In that case, you can use a Do [While] Loop cycle until the next string Finish is entered or until the user clicks the Done button.

A Do [While] Loop has several formats, depending on where and how the loop condition is evaluated. The most common syntax used is:

Do While (condition)
       code block
       or
       block of statements
       to be executed
Loop




More examples will be posted soon.




Based on the book, Step by Step Microsoft Visual Basic 6.0

Extended Search

Custom Search
Hello World