Monday, December 28, 2009

The " ? " Operator

Java includes a special Three-way(Ternary) operator that can replace certain types of if-then-else statements.These statements include assignment when certain conditions are fulfilled.This operator is " ? ".The working of " ? " operator is similar as in C,C++ and C#.The " ? " operator at first look might seem confusing but it is extremely useful in particular conditions when mastered.

General Syntax :-

expression 1 ? expression 2 : expression 3

Here expression 1 can be any expression that evaluates to a Boolean value.If expression 1 is true then expression 2 is evaluated else expression 3 is evaluated.Both the expressions expression 1 and expression 2 must have a return type,they can never be void.Make it more clear by understanding below example.

Example:-

public class optest
{
public static void main(String a[])
{
int ratio=0,num=20,denom=10;

/* The " ? " operator assignes 0 if condition denom==0 is true else it assigns num/denom to ratio if condituion is false*/

ratio=denom==0?0:num/denom;

System.out.println("The ratio is "+ratio);
}
}

Output:-
The ratio is 2

Explanation:-When Java evaluates this assignment expression ,it first looks at the expression to the left of the question mark.If denom equals to zero then expression 2 between ? and : is evaluated else last expression is evaluated.The resultant is then assigned to the ratio variable used in expression 1.

Suggested Reading:-

Arithmetic Operators
Conditional Operators
Logical Operators
Assignment Operators
Relational Operators
Bitwise Logical Operators
Operators Practice Questions

Read more...

Wednesday, December 23, 2009

Dynamic Initialization

There are two types of variable mainly:-

1.Instance Variable or Class Variable
2.Local Variable or method variable

Instance variable are initialized by JVM to their default values if not defined explicitly.Whereas the local variables needs to be defined each time time they are declared.But the local variables can be used to a greater effect by using the concept of dynamic initialization.

Dynamic Initialization can be defined as the dynamic operation that allows variables to be initialized dynamically using any expression valid at the time of the variable declaration.

Above definition implies that if you need a variable to store value of an expression you can use dynamic initialization.In which value of an expression is assigned to a variable.

Dynamic Initialization can be clear by understanding following example:-

class DynamicInit{
public static void main(String a[]){
int a=2;
int b=5;
int c=a*a+b*b;
System.out.println("value of c is "+c);
}
}

Output :-The output of above program is
value of c is 29

In the above program we have three variables a,b and c.Each has been declared as ' int '.Variable a and b are declared and provided values on declaration whereas the variable c has been assigned a expression to evaluate and store its value.This is done through dynamic evaluation.

NOTE:-One thing which has to be remembered is that the initialization expression may use any program construct including method calls,instance variables, literals etc.

Suggested Reading:-

Class Declaration

Interface Declaration
Local,instance variable and Shadowing
Code Reuse feature of Inheritance
Why Java classes are not final

Read more...

Tuesday, December 8, 2009

Starting and running Multiple Threads

In the previous tutorials about Threads we have learnt about the basics of Threads,How to create a Thread and also how to start a Thread.So far we have learnt how to start a single Thread but in this tutorial we will learn about how we can start and run Multiple Threads

To start Multiple Threads we use Runnable interface method which is best one.So we will implement the Runnable interface in our class and use the instance of our class to start Threads.To start a Thread we simply need a method start() to begin all the Threads.

Consider following example it will help you understand the Multiple Threads:-

class MultiTest implements Runnable
{
public void run()
{
for(int i=0;i<3;i++)
System.out.println("Run by " + Thread.currentThread().getName());
}
}

public class ManyThreads
{
public static void main(String a[])
{
MultiTest mt = new MultiTest();
Thread b = new Thread(mt);
Thread c = new Thread(mt);
c.setName("Programmer");
b.setName("Designer");
c.start();
b.start();
}
}

Output:- When we executed the program with loop running 3 times then we got the output

Run by Programmer
Run by Programmer
Run by Programmer
Run by Designer
Run by Designer
Run by Designer

but when we made loop to run for 100 times then it gave the output as

Run by Designer
Run by Programmer
Run by Designer
Run by Programmer
Run by Designer
Run by Programmer
Run by Designer
Run by Programmer
......

Well Friends one thing you need to know that you can never be certain of the output when many Threads are in operation.The bottomline is that the behaviour cannot be predicted and are also not guaranteed when multiple Threads are in execution.

You must know that every Thread will start and come to finish but the order in which they begin execution is not always the order in the program.In the last example program you might not be able to figure it out but when you run the loop for a Thousand times then it will be clear that any order can be followed you can never be certain of the output.

Suggested Reading:-

Java Thread Basics
Java Thread life cycle
Ways of Thread creation
How to Start Java Thread
Main Thread creation and Handling

Read more...

Friday, December 4, 2009

How to Start a Thread in Java

There are two ways of Thread creation either by implementing Runnable or extending the Thread class.In both the cases you need to start the thread for getting the functionality you need.So in order to start a thread we need a method which is start() and it is invoked on Thread object.

Remember:-start() method is always invoked on Thread object to start a separate call stack of this thread,but if you call the run() method on your Runnable object then it is simply a method call and cannot initiate a separate call stack.It also clears that You start a Thread not a Runnable.

To start a new Thread in separate call stack use

t.start() // where t is Thread object which is in execution.

We have made a call to start() method but know what happens behind the scenes there are three things happen:-

  1. A new Thread in execution starts(in a new call stack).
  2. The Thread moves from the new state to the runnable state.
  3. Whenever the Thread gets a chance to execute then it goes to running state and the target run() method will run.

Consider the following example to understand how Threads are started and also you will come to know that invoking run() method do works but it never ever initiate a new Thread or a separate call stack.

class TestRunnable implements Runnable
{
public void run()
{
for(int i=0;i<5;i++)
System.out.println("In Runnable");
}

public static void main(String a[])
{
Thread tr = Thread.currentThread();
System.out.println(tr);
TestRunnable r = new TestRunnable();
Thread t = new Thread(r);
System.out.println(r);
r.run();
System.out.println(t);
t.start();
}
}


OutPut:-

Thread[main,5,main]
TestRunnable@3e25a5
In Runnable
In Runnable
Thread[First Thread,5,main]
In Runnable
In Runnable

Explanations:-

Here in above example there are two things we wanted to get you know that new Threads are started by calling start() method on Thread object and Runnable can never ever start a new call stack.invoking run() method simply works as another method invocation.
Also you can see that when we tried to print the names of Threads then r comes with only as object names whereas the Thread t and tr have original Thread names.

Suggested Reading:-

Thread Life Cycle
Java Thread Basics
Ways of creating a Thread
Main Thread creation and handling

Read more...

Wednesday, December 2, 2009

How to use Swing Scroll Panes

A Scroll Pane is a component like JFrame or JPanel which is used to add other components but Scroll Pane has a Scroll Bar Associated with it which is a unique characteristic of this component Container.Scroll Panes are implemented in swing by JScrollPane class ,which extends JComponent class.Scroll Bar is either Vertical or Horizontal and they are used in Scroll Panes as needed.Like if you want to display the Scroll Bars all the time then you may use them always and also you might choose them to show up when container overflows.

Constructors used to create the Scroll Pane in Swings are :-

JScrollPane(Component cmp)
JScrollPane(int vert, int horiz)
JScrollPane(Component cmp, int vert, int horiz)

Remember:- A window can not be added to a Scroll Pane like JFrame cannot be added to a JScrollPane,but JPanel and other similar containers can be used which are not windows.

In above constructors cmp is the component to be added on the ScrollPane.vert and horiz are the integer constants that are defined when the horizontal or vertical ScrollBars are shown in the ScrollPane.These constants are defined in ScrollPaneConstants interface.

Some example constants are :-

1.VERTICAL_SCROLLBAR_ALWAYS (Always shows up vertical scrollbar) 2.VERTICAL_SCROLLBAR_AS_NEEDED(Shows up vertical Scrollbar when needed) 3.HORIZONTAL_SCROLLBAR_ALWAYS (Always shows up horizontal scrollbar) 4.HORIZONTAL_SCROLLBAR_AS_NEEDED(Shows up horizontal Scrollbar when needed)

Lets take a look at following example which lets you learn how to create and use JScrollPanes in your applications.

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

public class Scrollpanedemo extends JFrame
{
public Scrollpanedemo()
{
JFrame frm = new JFrame("Scroll Pane demo");
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(20,5));
for(int i=0;i<100;i++)
{
panel.add(new JButton("Button no. " + (i+1)));
}
int v=ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
int h=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
JScrollPane jsp = new JScrollPane(panel,v,h);
frm.getContentPane().add(jsp);
frm.setBounds(400,200,380,310);
frm.setVisible(true);
}

public static void main(String a[])
{
new Scrollpanedemo();
}
}

In the above example we create a frame and add a scrollpane over it.Then we create a panel which contains all the components and add it to the scrollpane.We have used the AS_NEEDED constants since we want to show that when our scrollpane overflows then the Scroll Bars shows up.


Suggested Reading :-

Using JTextField and JTextArea
How to set Icons on Swing Buttons
How to Create and use checkboxes
Using TabbedPanes in Java Swings
How to create popup menus in Java
Using DropDown menu or Choice menu

Read more...

How to Set Icons on Swing Buttons

Swing Buttons provides many exclusive features that are not found in the Button class defined in the AWT package.Swing Buttons are the subclass of AbstractButton class,which extends JComponent.You can always associate an icon of your choice with a Swing Button.The Icons are set as program runs or set when some event is fired like button pressed.AbstractButton class contains many methods that allow you to control the behaviour of buttons,check boxes and Radio Buttons.There is the way you can set the icon on the swing button and it is through the JButton constructor.

Despite of being set by constructor we can change the Icon of our Button whenever some action is fired or some condition is met.We can define different Icons when button :-

1.is disabled
2.is pressed
3.is selected(for radio buttons etc)
4.gets mouse focus

JButton class is responsible for creation of all types of push buttons whether with icons or with text or both.The constructor used to create Button with Icon is

JButton(Icon i)
But if you also want to add Text with Icon then the constructor will be

JButton(String s ,Icon i)

In case you forgot to add text and you want to add text to the button whenever you want then use following method with JButton object.

setText(String str)

The following example will help in understanding how to set Icons and how you can change them according to your need.

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

public class ButtonImage extends JFrame implements ActionListener
{
JButton button;
public ButtonImage()
{
JFrame frm = new JFrame("Icon on Button");
JPanel panel = new JPanel();
ImageIcon imageicon = new ImageIcon("d:\\Anmtd_Feed.gif");
ImageIcon im = new ImageIcon("d:\\snap.jpg");
ImageIcon img = new ImageIcon("e:\\softwares\\ICON gallery\\Icons-1\\128 x 128\\apple1 (1).ico");
button = new JButton(imageicon);
button.setText("The Feed Icon");
panel.add(button);
button.addActionListener(this);
button.setDisabledIcon(im);
button.setRolloverIcon(img);
frm.getContentPane().add(panel);
frm.setVisible(true);
frm.setBounds(100,100,250,150);
}

public void actionPerformed(ActionEvent ae)
{
if (ae.getSource()==button)
{
button.setEnabled(false);
}
}

public static void main(String a[])
{
new ButtonImage();
}
}


This is first output Frame.In example it is shown that how we can change the button image when the button is disabled or whenever mouse moves over it.


The method setDisabledIcon(Icon i) and setRolloverIcon(Icon i) changes icons when the button is disabled or Hovered by Mouse respectively.ImageIcon is just a class which implements the Icon interface thus we are passing here ImageIcon as it is more convenient to use and most of all it implements Icon interface.


You can check on your own just change the Icon or Image paths then when the button is pressed the button is disabled and the image is changed once the button is disabled then there is no way you can change the icon of the button.That is why move mouse over the button first to test and then press the button.

Suggested Reading:-

Setting Tooltip and Icon
Using Tabbed Panes in Java Swings
Adding Borders to swing Components
Setting Mnemonics and Shortcut keys

Read more...

About This Blog

This Blog is all about Java and programming.This blog is written by Vaibhav Pandey .He is a Computer Science Graduate .You can contact the author at javatute@gmail.com for any suggestion or Query.You can also contact the author for advertising on this blog.All the material presented here is the property of author and its reproduction in any form is strictly prohibited.

Disclaimer:-Download links provided here are not of author in any means.These are found over the Internet.
Page copy protected against web site content infringement by Copyscape

  © Blogger templates The Professional Template by Ourblogtemplates.com 2008

Back to TOP