Saturday, May 30, 2009

How to create MenuBar Steps

How to create Menu and MenuBars Step wise procedure

1.Create an object of MenuBar class:MenuBar can be attached a Frame and it will be displayed just below the title bar.
MenuBar mb=new MenuBar();

2.Call the method setMenuBar(MenuBar):-This method is used to attach the MenuBar to a Frame.
setMenuBar(mb);

3.Create objects of the Menu class for each menu you want to add on menu bar.

Menu file=new Menu("File");
Menu edit=new Menu("Edit");
Menu help=new Menu("Help");

4.Call add() method of MenuBar class to add each menu object to the menu.

mb.add(file);
mb.add(edit);
mb.add(help);

5.Create object of MenuItem or CheckboxMenuItem class for each sub menu item.

MenuItem save =new MenuItem("Save");
MenuItem newf =new MenuItem("New");
MenuItem open =new MenuItem("Open");
CheckboxMenuItem cbm=new CheckboxMenuItem("check");

6.Call add() method of Menu class to add each menu item to its appropriate menu.

file.add(newf);
file.add(open);
file.add(save);

Complete Example :-

Source Code:-
//MyMenubar.java


import java.awt.*;
public class MyMenubar
{
public static void main(String a[])
{
Frame frame=new Frame("MenuBar Demo");
MenuBar mb=new MenuBar();
frame.setMenuBar(mb);
Menu file=new Menu("File");
Menu edit=new Menu("Edit");
Menu help=new Menu("Help");
Menu options=new Menu("Options");
mb.add(file);
mb.add(edit);
mb.add(help);
MenuItem save =new MenuItem("Save");
MenuItem newf =new MenuItem("New");
MenuItem open =new MenuItem("Open");
CheckboxMenuItem cbm=new CheckboxMenuItem("check");
file.add(newf);
file.add(open);
file.add(save);
file.add(options);
options.add(new MenuItem("Font"));
options.add(new MenuItem("Size"));
options.add(new MenuItem("Color"));
edit.add(cbm);
cbm.setState(true);
cbm.setEnabled(false);
open.setEnabled(false);
frame.setVisible(true);
frame.setSize(300,300);
}
}

Read more...

Menus In Java Swings

Every window can have a menu associated with it.Menu Bars basic function is to provide a list of choices.Each choice has its own drop-down menu(is provided otherwise none).This is implemented in Java by using following classes:-

MenuBar
Menu
MenuItem
CheckboxMenuItem

A menu bar can contains many menu objects.Each menu object may contain many MenuItem objects.In this implementation it is also possible to include checkable menu items.These can be implemented by CheckboxMenuItem class and will place a check mark next to them when they get selected.

First look at the constructors involved in creation of a menubar application.

1. MenuBar:-MenuBar is the highest class in this application and it will contain all the menu's inside it.It has only default constructor.

//MenuBar () only default constructor

2.Menu:-The constructors for Menu is as following.Menu's object will hold menu item's in them.

//Menu()
//Menu(String optionName)
//Menu(String optionName,boolean Removable)

In this case optionName provides the name of menu selection.If removable are set to true then menu can be removed and allowed to roam free.Otherwise it will remain with the menu bar.

3.MenuItem:-The Individual menuitems are of type MenuItem .These controls are to be placed on Menu object.

//MenuItem()
//MenuItem(String itemName)
//MenuItem(String itemName,MenuShortcut key)

here itemName is the name of item shown on menu and key is the menu shortcut for this item.

4.CheckboxMenuItem:-CheckboxMenuItem creates the checkboxes which can be placed as a menu and show their state by checked or unchecked.

//CheckboxMenuItem()
//CheckboxMenuItem(String itemName)
//CheckboxMenuItem(String itemName,boolean on)

itemName refers to the name of checkbox displayed on menu and on refers its state checked or unchecked.

Important Methods:-There are methods with various functionality lets see

1.void setEnabled(boolean flagvalue):-This method sets any menuitem to enabled or disabled state.Which specifies whether the menuitem is active or not(Click works or not).

2.boolean isEnabled():-This method returns the value whether the menuitem is active or inactive.That is either true or false.

3.void setLabel(String newName):-This method changes the name of a menuitem.

4.String getLabel():-It returns the name of the menuitem.

5.boolean getState():-This method returns the value (checked or unchecked) of
CheckboxMenuItem object.

6.void setState(boolean checked):-You can set the value of CheckboxMenuItem to true or false using this method.

For learning an example click below:-

How Menu is created step wise step procedure

Read more...

Saturday, May 16, 2009

Java Class Loader Architecture

Class loader is one of the main components of the JVM implementation.Since a JVM can have many class loaders and are thus used to provide security and network mobility to Java programs.
The JVM has two types of Class loaders:-


1.Primordial Class Loader:-A Primordial Class loader is the part of JVM implementation.It loads only the Java API classes(not other classes) when we execute our Java programs.


2.Class Loader Objects:-An application can create many class loaders at runtime for loading each and every class which is used in the program.


Following diagram depicts how the Class loader is implemented in JVM.




The classes in the primordial class loader are trusted since they are a part of JVM and Java API.The class loaded in the class loader object are not trusted .


Important:-Trusted classes are more authorized to use the resources of a local machine than untrusted classes.


A class loader is just another object in Java.There is no difference in simple Java objects and class loader object.Since it is a part of Java program you can extend the Java program dynamically at runtime.


How it works??
When a class A refers to a class B,the class B is loaded into the same class loader as class A.Therefore,each class can only see the classes that are in the same name space.A name space has a list of classes loaded in the class loader.This is what we call default access(within same package).The classes loaded by different class loaders cannot access each other unless the application explicitly allows the access.In your program,You can load classes from different sources into class loaders and restrict the interaction between the code loaded from different sources.

Suggested Reading Links:-
Java Architecture
Java Architecture Features and tradeoff's


Other Links:-
Home
Open Your online shop Today for free!!!

Read more...

Java Basic questions:Control Statements

Following are some good basic questions of Control statements read them and make your fundamentals strong

1) What are the programming constructs?
Ans: a) Sequential
b) Selection -- if and switch statements
c) Iteration -- for loop, while loop and do-while loop

2) class conditional {
public static void main(String args[]) {
int i = 20;
int j = 55;
int z = 0;
z = i < j ? i : j; // ternary operator
System.out.println("The value assigned is " + z);
}
}
What is output of the above program?
Ans: The value assigned is 20

3) The switch statement does not require a break.
a)True
b)False
Ans: b.

4) The conditional operator is otherwise known as the ternary operator.
a)True
b)False
Ans: a.

5) The while loop repeats a set of code while the condition is false.
a)True
b)False
Ans: b.

6) The do-while loop repeats a set of code atleast once before the condition is tested.
a)True
b)False
Ans: a.

7) What are difference between break and continue?
Ans: The break keyword halts the execution of the current loop and forces control out of the loop.
The continue is similar to break, except that instead of halting the execution of the loop, it starts the next iteration.

8) The for loop repeats a set of statements a certain number of times until a condition is matched.
a)True
b)False
Ans: a.

9) Can a for statement loop indefintely?
Ans : Yes.

10) What is the difference between while statement and a do statement/
Ans : A while statement checks at the beginning of a loop to see whether the next loop iteration should occur.
A do statement checks at the end of a loop to see whether the next iteration of a loop should occur. The do statement will always execute the body of a loop at least once.

Links:-
Home
India Online
Other Java Questions
Open Your Online Store for free!!!

Read more...

Wednesday, May 13, 2009

Java Architecture Features and TradeOff's

Java has become a very popular programming language due to its capability of executing the program on any machine irrespective of where its compilation is being done.There are three main features offered by Java Architecture.

  • Platform Independence.
  • Security.
  • Network Mobility.
Platform Independence:-

The support for platform Independence is spread across all four components of the Java architecture.All these components were told in previous tutorial.

The Java platform:- The Java platform insulates the Java program from the hardware and operating system on the target machine.Java program are compiled to execute on the JVM.The Java API enables programs to use system resources.All Java program can only interact with the JVM,that is why it can be executed on any machine that hosts JVM.

The Java Language:- The Java Language defines the range and behaviour of primitive data types.For example in C and C++ ,the target machine platform determines the size of the data types.For Example int in C and C++ may occupy 2 bytes in one platform and 4 bytes in the other.This results in unpredictable results across the various platforms.But in Java ,the primitive data type are the same across all platforms.This is all due to the JVM.Since JVM uses the data types defined by the language and therefore,the data type behaviour remains same on all platforms .

The Java class file:-The Java class file is a binary standard for files that can be executed by the JVM.The bytecode(class file) which is produced after compilation is platform independent.

NOTE:-There are specifications that you can use native libraries in Java but using Native methods affects the platform independence of Java.If a Java program invokes a native method,the program becomes platform specific.Native methods are used when the certain conditions are there:-

  • The resources of the machine cannot be accessed through Java API.
  • A set of methods exists in non-Java API.
  • The speed of the program needs to be increased.

Security:-Java is perfect language for networks.Any network-oriented software must deal with security.Java's security model makes it appropriate for network-oriented programming.Java code is loaded, for example an applet loaded by a browser may contain a virus or malicious code.Java protects its end users from such threats by using a sandbox model.

There are some restrictions imposed on untrusted code(applet)

  • It cannot neither read nor write the local files.
  • It can make a connection only to the machine from where it was downloaded.
  • It cannot load new dynamic linked libraries.
  • It cannot call a native method.

The Java Sandbox:- The sandbox allows code to be downloaded from any source but imposing some restrictions on it.A Java sandbox is an area in memory outside which the Java programs cannot make calls .This prevents Java programs from being able to call low level system functions that may cause data corruption or other damages.The Java
Sandbox has three components:-

1.The ByteCode Verifier:-The first level of Java security is Bytecode verifier.The bytecode is verified before it is allowed to run on the users machine.It is checked to authenticate its creation by a Java compiler.ByteCode verifier make sure that the format of the bytecode fragment is correct.A algorithm is applied to chck that the bytecode does not violate access restrictions or try to access object using incorrect or bad information.The bytecode verification is done in two phases .In first phase the verifier checks for the validity of the bytecode when it is loaded,this is done by checking the structure of the .class file.In second phase verifier checks for the validity of the classes,the variables,and the methods used in the program.This is done because Java programs are dynamically linked.

2.The Applet Class Loader :-The second level of security is in the applet call loader.All java objects belong to classes and the applet class loader determines how and when an applet is allowed to add classes to a running Java environment.It also makes sure that important parts of JRE are not replaced by any applet code.

3.The Security Manager:-The third and most important level of Java sandbox,is security manager.The security manager defines the boundary of a sandbox.The Java API refers to the security manager before it allows any access to resource.While loading classes ,the class loaded always follow the security managers decisions.Built-in classes are given preferences over classes loaded over the Network.This sandbox can be used to run untrusted code on the user's machine.

NOTE:-
Java Protected Domain:- It is an extension of Java sandbox in a file system.Java protected domains enable use of permissions for providing access to function calls outside the sandbox.


Network mobility:-Java offers platform independence and security two essential parameters that make a program network-oriented.One program can serve the entire network that comprises of machines using different operating systems.
Another issue in network mobility is amount of time it take to download a program for the network.As Java is dynamically linked,you need not wait for all the .class files to be loaded before you execute a program.The .class file is compact and travels quickly across the network.Only classes that are used in the course of the program execution are downloaded.Class loaders also help in extending the program dynamically.

Java Architecture Trade off

Java offers many features for a networked programmer.The price paid for these feature is a trade off on the execution speed of Java programs.It is well known that C++ programs are faster than Java programs due to following reasons:-

  • Interpreting bytecode is slower than executing the machine code for C++.
  • Checks on array bounds are made for each and every array.
  • The garbage collector needs to be more efficient and faster than it is at present.
  • Java programs are dynamically linked and therefore,the programs has to wait for bytecode to get downloaded.
  • All the variables are checked for types at runtime.
Links:-
<
Java Architecture
Earn money Quick
Open your Online Store now!!!!

Read more...

Tuesday, May 12, 2009

I have Opened My Own Shop

Wow!!! Today I have created my first online store.It sounds great to have your own.My store has everything a person would like.It is not as big but I will work on it and add as many products I can .You can visit my store here.It currently contains the gaming products like gaming consoles including Nintendo Wii,XBOX,Sony playstation etc.The games according to each console is also provided.

My Store!!!!!

I have one more thing to tell that you can also create your own shop in few clicks and you can also earn upto 10% commission on each sale you have made.They have a very interesting referral program too in which you will get 10% commission on your first level referrals and 5% commission on your second level referrals.

But what you have to do that you have to frequently update your shop according to need otherwise your shop will be closed.You can check this program by clicking here.You can get your thematic shops that belongs to only one theme like if you are interested in computers you can open your computer shop.You are just a few clicks away from earning a good sound income.The best part is they pay through PAYPAL and you don't have to bother about the shipping of product bought.Its great check it out:-

Open your shop here


Read more...

Java Architecture

According to Sun Microsystems the Java architecture comprises of four components.Each of them is defined by Sun Microsystems.


The Components are:-

  • 1.Java Programming Language
  • 2.Java class file format
  • 3.Java Virtual Machine
  • 4.Java (API) Application Programming Interface.
Every Java program uses features of all the four components.They are used in following sequence:-

  1. We write code in Java programming Language.
  2. When we compile the .java file it creates a new file which is called as the class file(also called bytecode).
  3. The .class file(or class file) is executed by the JVM.
  4. When we execute the program the method calls are made through the Java API.The above

Sequence may be represented as following block diagram:-



The JVM and the Java API forms the basic Java runtime system and is must to execute any java program.The specification provided by the Sun Microsystems only lists the components features but this specification lacks the way how these features to be implemented.The implementation is always left to the designers.The JVM is provided by many vendors, mostly it comes along with the Operating System.All the JVM's must have some unique features that is why it is said that "Threads are JVM behaviour dependent".So its important to figure out how your JVM performs internal task of scheduling,memory related issues and other performance matrices.Although the JVM vendors and JVM functioning is a bit different but still all of them follow the Sun Microsystems Specification for Java Architecture.

Links:-
Home
Earn Money Quick

Read more...

Monday, May 11, 2009

Simple Java Twisters

Hi guys I am back after giving away the so called tough exam "The advanced computer architecture".That was fine but I am not enjoyed it at all.But here are some twisters you guys must enjoy, at first sight they seem simple but mind you they are very simple to twist you.Check them out.These twisters surely gonna test your program understanding capabilities, so be prepared.If you think you got the answers right then check on your own ,just copy this code and try to run it on your system.If you got answers matched with yours then you are not twisted by them else no worries just try to make your basics strong.Some guys will find these questions really easy but I must say these are just for guys who want some fun from programming.

Here they come:-

1.What would be the output of following code segment

public class test
{
public static void main(String a[])
{
boolean x;
if(x=true)
System.out.println("This is true");
else
System.out.println("This is false");
}
}

2.What would be the output of following code:-

public class maintest
{
public static int main(String a[])
{
int x=10;
if(x++)
System.out.println(x++);
else
System.out.println(++x);
}
}

3.What would be the output of following code:-

public class inttest
{
public static void main(String a[])
{
int x=20;
if(x==x++)
System.out.println("This is true");
else
System.out.println("This is false");
}
}

4.What would be the output of following code:-

public class inttest4
{
public static void main(String a[])
{
int x=20;
if(x+1 ==((x++ + ++x)/2))
System.out.println("This is true");
else
System.out.println("This is false");
}
}

5.What would be the output of following code:-

public class inttest3
{
public static void main(String a[])
{
int x=20;
if(x+1 ==((++x + x++)/2))
System.out.println("This is true");
else
System.out.println("This is false");
}
}

6.what would be the output of following code:-

public class inttest2
{
public static void main(String a[])
{
int x=20;
if(x==++x)
System.out.println("This is true");
else
System.out.println("This is false");
}
}

Links:-

Home
Earn money Quick

Read more...

Saturday, May 9, 2009

Java Practice and Interview Questions:Operators

Here are Some Important questions of Operators which are frequently asked in practical viva's and Job Interviews.They are a bit theoretical but they are very basic questions.

Operators

1) What are operators and what are the various types of operators available in Java?
Ans: Operators are special symbols used in expressions.
The following are the types of operators:
Arithmetic operators,
Assignment operators,
Increment & Decrement operators,
Logical operators,
Bitwise operators,
Comparison/Relational operators
and
Conditional operators

2) The ++ operator is used for incrementing and the -- operator is used for
decrementing.
a)True
b)False
Ans: a.

3) Comparison/Logical operators are used for testing and magnitude.
a)True
b)False
Ans: a.

4) Character literals are stored as unicode characters.
a)True
b)False
Ans: a.

5) What are the Logical operators?
Ans: OR(|), AND(&), XOR(^) AND NOT(~).

6) What is the % operator?
Ans : % operator is the modulo operator or reminder operator. It returns the reminder of dividing the first operand by second operand.

7) What is the value of 111 % 13?
a)3
b)5
c)7
d)9
Ans : c.

8) Is &&= a valid operator?
Ans : No.

9) Can a double value be cast to a byte?
Ans : Yes

10) Can a byte object be cast to a double value ?
Ans : No. An object cannot be cast to a primitive value.

11) What are order of precedence and associativity?
Ans : Order of precedence the order in which operators are evaluated in expressions.
Associativity determines whether an expression is evaluated left-right or right-left.

12) Which Java operator is right associativity?
Ans : = operator.

13) What is the difference between prefix and postfix of -- and ++ operators?
Ans : The prefix form returns the increment or decrement operation and returns the value of the increment or decrement operation.
The postfix form returns the current value of all of the expression and then
performs the increment or decrement operation on that value.

14) What is the result of expression 5.45 + "3,2"?
a)The double value 8.6
b)The string ""8.6"
c)The long value 8.
d)The String "5.453.2"
Ans : d

15) What are the values of x and y ?
x = 5; y = ++x;
Ans : x = 6; y = 6

16) What are the values of x and z?
x = 5; z = x++;
Ans : x = 6; z = 5


Control Statements
1) What are the programming constructs?
Ans: a) Sequential
b) Selection -- if and switch statements
c) Iteration -- for loop, while loop and do-while loop

2) class conditional {
public static void main(String args[]) {
int i = 20;
int j = 55;
int z = 0;
z = i < j ? i : j; // ternary operator
System.out.println("The value assigned is " + z);
}
}
What is output of the above program?
Ans: The value assigned is 20
3) The switch statement does not require a break.
a)True
b)False
Ans: b.

4) The conditional operator is otherwise known as the ternary operator.
a)True
b)False
Ans: a.

5) The while loop repeats a set of code while the condition is false.
a)True
b)False
Ans: b.

6) The do-while loop repeats a set of code atleast once before the condition is tested.
a)True
b)False
Ans: a.

7) What are difference between break and continue?
Ans: The break keyword halts the execution of the current loop and forces control out of the loop.
The continue is similar to break, except that instead of halting the execution of the loop, it starts the next iteration.

8) The for loop repeats a set of statements a certain number of times until a condition is matched.
a)True
b)False
Ans: a.

9) Can a for statement loop indefinitely?
Ans : Yes.

10) What is the difference between while statement and a do statement/
Ans : A while statement checks at the beginning of a loop to see whether the next loop iteration should occur.
A do statement checks at the end of a loop to see whether the next iteration of a loop should occur. The do statement will always execute the body of a loop at least once.

Links:-
Home
Earn Quick Money

Read more...

Thursday, May 7, 2009

Java Basic Questions

List of Java Basic Questions which are frequently asked in Technical Interviews:-

1.The Java interpreter is used for the execution of the source code.
True
False
Ans: a.

2) On successful compilation a file with the class extension is created.
a) True
b) False
Ans: a.

3) The Java source code can be created in a Notepad editor.
a) True
b) False
Ans: a.

4) The Java Program is enclosed in a class definition.
a) True
b) False
Ans: a.

5) What declarations are required for every Java application?
Ans: A class and the main( ) method declarations.

6) What are the two parts in executing a Java program and their purposes?
Ans: Two parts in executing a Java program are:
Java Compiler and Java Interpreter.
The Java Compiler is used for compilation and the Java Interpreter is used for execution of the application.

7) What are the three OOPs principles and define them?
Ans : Encapsulation, Inheritance and Polymorphism are the three OOPs
Principles.
Encapsulation:
Is the Mechanism that binds together code and the data it manipulates, and keeps both safe from outside interference and misuse.
Inheritance:
Is the process by which one object acquires the properties of another object.
Polymorphism:
Is a feature that allows one interface to be used for a general class of actions.

8) What is a compilation unit?
Ans : Java source code file.

9) What output is displayed as the result of executing the following statement?
System.out.println("// Looks like a comment.");
// Looks like a comment
The statement results in a compilation error
Looks like a comment
No output is displayed
Ans : a.

10) In order for a source code file, containing the public class Test, to successfully compile, which of the following must be true?
a)It must have a package statement
b)It must be named Test.java
c)It must import java.lang
c)It must declare a public class named Test
Ans : b

11) What are identifiers and what is naming convention?
Ans : Identifiers are used for class names, method names and variable names. An identifier may be any descriptive sequence of upper case & lower case letters,numbers or underscore or dollar sign and must not begin with numbers.

12) What is the return type of program’s main( ) method?
Ans : void

13) What is the argument type of program’s main( ) method?
Ans : string array.

14) Which characters are as first characters of an identifier?
Ans : A – Z, a – z, _ ,$

15) What are different comments?
Ans : 1) // -- single line comment
2) /* --
*/ multiple line comment
3) /** --
*/ documentation

16) What is the difference between constructor method and method?
Ans : Constructor will be automatically invoked when an object is created. Whereas method has to be call explicitly.

17) What is the use of bin and lib in JDK?
Ans : Bin contains all tools such as javac, applet viewer, awt tool etc., whereas Lib
contains all packages and variables.

Data types,variables and Arrays

1) What is meant by variable?
Ans: Variables are locations in memory that can hold values. Before assigning any value to a variable, it must be declared.

2) What are the kinds of variables in Java? What are their uses?
Ans: Java has three kinds of variables namely, the instance variable, the local variable and the class variable.
Local variables are used inside blocks as counters or in methods as temporary variables and are used to store information needed by a single method.
Instance variables are used to define attributes or the state of a particular object and are used to store information needed by multiple methods in the objects.
Class variables are global to a class and to all the instances of the class and are useful for communicating between different objects of all the same class or keeping track of global states.

3) How are the variables declared?
Ans: Variables can be declared anywhere in the method definition and can be initialized during their declaration.They are commonly declared before usage at the beginning of the definition.
Variables with the same data type can be declared together. Local variables must be given a value before usage.

4) What are variable types?
Ans: Variable types can be any data type that java supports, which includes the eight primitive data types, the name of a class or interface and an array.

5) How do you assign values to variables?
Ans: Values are assigned to variables using the assignment operator =.

6) What is a literal? How many types of literals are there?
Ans: A literal represents a value of a certain type where the type describes how that value behaves.
There are different types of literals namely number literals, character literals,
boolean literals, string literals,etc.

7) What is an array?
Ans: An array is an object that stores a list of items.

8) How do you declare an array?
Ans: Array variable indicates the type of object that the array holds.
Ex: int arr[];

9) Java supports multidimensional arrays.
a)True
b)False
Ans: a.

10) An array of arrays can be created.
a)True
b)False
Ans: a.

11) What is a string?
Ans: A combination of characters is called as string.

12) Strings are instances of the class String.
a)True
b)False
Ans: a.

13) When a string literal is used in the program, Java automatically creates instances of the string class.
a)True
b)False
Ans: a.

14) Which operator is to create and concatenate string?
Ans: Addition operator(+).

15) Which of the following declare an array of string objects?
a)String[ ] s;
b)String [ ]s:
c)String[ s]:
d)String s[ ]:
Ans : a, b and d

16) What is the value of a[3] as the result of the following array declaration?
a)1
b)2
c)3
d)4
Ans : d

17) Which of the following are primitive types?
a)byte
b)String
c)integer
d)Float
Ans : a.

18) What is the range of the char type?
a)0 to 216
b)0 to 215
c)0 to 216-1
d)0 to 215-1
Ans. d

19) What are primitive data types?
Ans : byte, short, int, long
float, double
boolean
char

20) What are default values of different primitive types?
Ans : int - 0
short - 0
byte - 0
long - 0 l
float - 0.0 f
double - 0.0 d
boolean - false
char - null

21) Converting of primitive types to objects can be explicitly.
a)True
b)False
Ans: b.

22) How do we change the values of the elements of the array?
Ans : The array subscript expression can be used to change the values of the elements of the array.

23) What is final variable?
Ans : If a variable is declared as final variable, then you can not change its value. It becomes constant.

24) What is static variable?
Ans : Static variables are shared by all instances of a class.

Links:-
Home
Earn Quick Money
Java Practice Questions
Best Java Interview Questions

Read more...

Compute any day in calendar using Java.Util package

Computing a day on any date is not an easy task,it can't be done so easily.By using below given source code you can compute any day which will come after your mentioned date whether it may be tomorrow or after 25 years very easily.Java.Util package has been used.This code is developed when I was doing coding for railway reservation system and the condition was to make reservation in advance say 30 days or more.This Program takes input in the specified date format which is mentioned in static method now().This method returns a String of current date.Here we have taken the two dates specifically but you can add interactivity in your program by taking date as a input.But note that the dates must be of same format.


Example(Source Code):-
// Created by vaibhav Pandey
//diffdays.java

import java.util.Calendar;
import java.io.Serializable;
import java.util.Date;
import java.text.SimpleDateFormat;

public class diffdays
{
public static String now(String dateFormat) {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
return sdf.format(cal.getTime());
}
public static void main(String a[])
{

long diffDays;
int k;
String tempTo="";
String tempFrom="";
SimpleDateFormat df = new SimpleDateFormat("yyyy/mm/dd");
Date from =new Date(diffdays.now("yyyy/MM/dd"));
Date to =new Date("2009/05/10");

long diffMillis = to.getTime() - from.getTime();
diffDays = diffMillis / (1000 * 60 * 60 * 24);

System.out.println("Format Used is yyyy/mm/dd");
System.out.println(diffdays.now("yyyy/MM/dd"));

long i=0;
String today=(diffdays.now("EEEEEE"));
String day_computed="";
System.out.println("Today is:- "+today);
if(today.compareTo("Sunday")==0)
{
i=1;
}
else if(today.compareTo("Monday")==0)
{
i=2;
}
if(today.compareTo("Tuesday")==0)
{
i=3;
}
if(today.compareTo("Wednesday")==0)
{
i=4;
}
if(today.compareTo("Thursday")==0)
{
i=5;
}
if(today.compareTo("Friday")==0)
{
i=6;
}
if(today.compareTo("Saturday")==0)
{
i=7;
}
i=(i+(diffDays-1)%7);
int j=(int)((i%7));

switch(j)
{
case 0:day_computed="Sunday";
break;
case 1:day_computed="Monday";
break;
case 2:day_computed="Tueday";
break;
case 3:day_computed="Wednesday";
break;
case 4:day_computed="Thursday";
break;
case 5:day_computed="Friday";
break;
case 6:day_computed="Saturday";
break;
}
System.out.println("Day on 2009/05/10 is "+day_computed);
System.out.println("Created by vaibhav pandey on 2009/05/06");

}
}

Output:-In the output you will get following screen showing following values:-

H:\>java diffdays
>Format used is yyyy/mm/dd
>2009/05/06
>Today is:- Thursday
>Day on 2009/05/10 is Sunday
>Created by Vaibhav Pandey on 2009/05/06





Illustration:-As in previous post where I told you how can you get date your specified format,we will use it here also coz it is needed to get date in desired format to save complexity and time.The logic of this is implemented in now() method.Coming to main() method you can see we have taken two variables of date type and passed same type of date format to them.Then we have computed the difference in milliseconds between both dates.According to which we have calculated difference in days by dividing the value by (1000*60*60*24).

Coming to the implementation logic ,here we computed current day and matched it to get the value of ' i ' in switch() construct.After getting this value we applied the formula (i+(diffdays-1)%7) to get the resulting value of ' i ' which will take us the resultant day.This formula computes the value of ' i ' by adding remiander of (diffdays-1)%7.Actually only (diffdays%7) would have worked but since I have taken it so I have to work accordingly.Lets make it simple assume that today is monday the from first switch we will get i=2,and we wish to compute day after 4 days, thus diffdays would be equal to 4.Now applying the formula we get

i=(2+(4-1)%7)

=> i = (2+3) //since 3%7=3
=> i = 5.

going to next switch() and getting day according to value of j we get day=" Friday" which is desired result.We used ' j ' here to use in switch() because ' i ' being long cannot be used in it.If you liked it please comment.I need your feedback desperately.


Links:-
Home
Date Time in your Specified Format
Earn Money Quick




Read more...

Wednesday, May 6, 2009

Loading Image on JFrame using JFileChooser

JFileChooser is a very handy utility in java Swings to choose any particular file of an extension.
Sometimes in our applications we need to load images onto our main container .In java we can use either JFrame or JPanel to load images.Statically we can provide the path of image into our program,but most of times it is not feasible for us to give image path statically.For specifying image path dynamically we use JFileChooser which returns path of a selected image.You can also select the desierd file extensions for whom you are looking.In following Example it is elaborated how to use JFileChooser and using it how we can load an image on a container.

Example (Source code ):-

//imageloading.java

//Program developed by Vaibhav Pandey

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;

public class imageloading extends JFrame
{
BufferedImage mImage;
String name,name1;
public imageloading()
{
JFrame frm=new JFrame("image loading test");
String source=filechoose();
File inputFile = new File(source);
try {
mImage = ImageIO.read(inputFile);
} catch (IOException ex) {
//Logger.getLogger(index.class.getName()).log(Level.SEVERE, null, ex);
}
JLabel lb=new JLabel(new ImageIcon(mImage));
frm.getContentPane().add(lb);
frm.show();
frm.pack();
}

String filechoose()
{
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new File("."));

chooser.setFileFilter(new javax.swing.filechooser.FileFilter() {
public boolean accept(File f) {
name = f.getName().toLowerCase();
return name.endsWith(".gif") || name.endsWith(".jpg")
|| name.endsWith(".jpeg") || f.isDirectory();
}

public String getDescription() {
return "Image files";
}
});

int r = chooser.showOpenDialog(this);

if (r == JFileChooser.APPROVE_OPTION) {
name1 = chooser.getSelectedFile().getAbsolutePath();
StringBuffer sb=new StringBuffer();
sb.append(name1);

int l=sb.length();
for(int i=0;i
{
if(sb.charAt(i)=='\\')
{
sb.insert(i, "\\");i++;
}
}
}
return name1;
}
public static void main(String a[])
{
new imageloading();
}
}

Output Windows:-

Following first widow shows the JFileChooser() instance opened and asking to
select a file of given extension,and in second window you can see the loaded image.


















Elaboration:-In the given code we have used the ImageIO class to read the image file whose file is being specified and consequently is buffered.Later this buffered image is set on a Label as a ImageIcon to display it on the frame.

JFileChooser() is used to choose the files of desired extension here FileFilter() method is used to filter the files on the basis of extensions .Here we have considered only .jpeg and .gif images.Since the '/' is treated as a escape sequence in Java thus in when we are fetching path name in variable 'name1' using method 'JFileChoose.getSelectedFile().getAbsolutePath()' ,in order to omit the escape sequence we embed '//' in the path when we have some path selected.

We have used 'JFileChooser.APPROVE_OPTION' because to verify that we have selected a legitimate file or not.Any queries and comments are most welcome.In Java JFileChooser is a nice utility ,use it and tell me about the tutorial.

Read more...

Tuesday, May 5, 2009

Using SQL(insert command) in Java through JDBC

Using SQL DML statements in Java is very easy and is done through JDBC.Apart from writing this first I tell you what happened to me today.I have just given my first exam of this semester under some real harsh conditions.I was badly suffering and have vomiting and lose motions going around,But still somehow I managed to write away all the answers.
So its enough lets start:-

Peoples aware with SQL must know that there are 3 types of languages:-

1.Data Definition Language(DDL)
2.Data Manipulation Language(DML)
3.Transaction control Language(TCL)

Right here I will present ways by which you can use DML to update,insert and delete your database through front end application.I have presented here simple methods which can be used directly into your programmes.

Here we will see how data can be added to database through JDBC.

Adding Records to DataBase

You can use executeUpdate() method of Statement object to execute simple insert command.Through this insert Command the values are inserted in the database.

Syntax:-

// stat.excecuteUpdate("insert table values (26,50)")

There is no return type of this method but it results in the affected rows in the database.

Method:-

public void addRecord()
{
try
{
stat.executeUpdate("insert employee values('vaibhav',21,javaapp)");
}
catch(Exception e){}
}

This was the example of static data manipulation that is value are provides in advance,what if we will do if our application is a bit interactive.You have to provide values during execution.For this purpose we will use PreparedStatement object and few methods of this Class named executeUpdate() and setString()(or setInt()).

In that case the method will look like following:-

public void addRecord()
{
try
{
stat=con.prepareStatement("insert employee values(?,?,?)");
stat.setString(1,text1.getText());
stat.setString(2,text2.getText());
stat.setString(3,text3.getText());
stat.executeUpdate();
}catch(Exception e){}
}

Here in above example we have used placeholder("?") to provide values at runtime through the TextBoxes.We assume here that values are coming form the textbox on an ActionEvent.

con is the object of Connection class and is used to create preparedStatement.setString(index,value) or setInt(index,value) methods are used to set the value for the specified column indicated by index and value indicates the value to be stored in database.


Links
:-
Home
JDBC :Introduction
Configuring data source
connecting to database
querying database
JDBC:ResultSet Object
JDBC:Statement Object
JDBC:PreparedStatement Object

Read more...

Monday, May 4, 2009

Not usual java Post

Again this is not the usual java post,So if you believe that there is something about Java in it ,no its not its all about personal thoughts.From so many days I am creating posts on Java.In this post I want to share few my personal experiences,what I am feeling from a few days.The heat and pressure is building up as I am going to take my final semester Examinations.Most of you still don't know who I am.I am Vaibhav Pandey author of this Java blog.I am also pursuing my Engineering degree and will get it this June/July.I have already submitted my final year project and I am not up to my expectation(its a huge blow for me and my confidance).

In this semester I have 4 subjects Distributed Systems,Advanced Computer Architecture,Mobile Computing,Software Project Management.Please don't ask me write blog on them coz I have no interest in them.Distributed Systems Exam is on 5th May but I just can't remain away from this blog and stop writing,this has became a passion for me.I am a Indian Student and already got a job offer from a Multi National Company in my country where I have to join on 11th Jan 2010.There are plans queued up for me .I am planning to launch a complete educational site which will contain almost everything from tutorials to articles,reviews to polls and much much more.This will be done once Exam gets finished.I wish I could train people online on Sun Certification Once I will get Certified.I am currently preparing too and expected to write Exam somewhere around end of July.I am graduating in Computer Science and Engineering .It feels great when you let somebody learn a new technology or a new programming language tweaks and basics,because now a days what I have seen most of beginning programmers tend to start designing GUI'S and coding them despite making their programming fundamentals clears.This leads to a hugely inefficient programming I hope everybody must learn good and start from beginning rather than just run away with things.This will hamper your natural style of coding.

I also want to do some thing for charity that is why I have launched a campaign to help UNICEF please make sure you are playing your part in making world literate,because what matters is knowledge.Click following banner to contribute and buy a gift.




Peoples have talent but they don't want to brush it up.I have seen so many guys destroying their lives during this course of 4 Years so called Graduation.So be cautious always use your mind to do tasks.always try to seek knowledge from everyone and everything around you.Make most of your resources.The biggest source is the INTERNET.I am not a believer that the Social networking sites are bad and waste of time but sometimes they do . Use them but not that much so that they starting affecting your intellect.Building your network is also necessary but always think before doing something.I have so much to tell ,I am always filled up with Ideas and trying to get a way to realize them.More of my life will come soon but after I will write some good Java tutorials posts.Love you all.

For more of me mail me

Vaibhav Pandey
javatute@gmail.com

Read more...

Sunday, May 3, 2009

SCJP(310-065) Exam Objectives

Section 1: Declarations, Initialization and Scoping

  • Develop code that declares classes (including abstract and all forms of nested classes), interfaces, and enums, and includes the appropriate use of package and import statements (including static imports).
  • Develop code that declares an interface. Develop code that implements or extends one or more interfaces. Develop code that declares an abstract class. Develop code that extends an abstract class.
  • Develop code that declares, initializes, and uses primitives, arrays, enums, and objects as static, instance, and local variables. Also, use legal identifiers for variable names.
  • Develop code that declares both static and non-static methods, and - if appropriate - use method names that adhere to the JavaBeans naming standards. Also develop code that declares and uses a variable-length argument list.
  • Given a code example, determine if a method is correctly overriding or overloading another method, and identify legal return values (including covariant returns), for the method.

    Section 2: Flow Control

  • Develop code that implements an if or switch statement; and identify legal argument types for these statements.

  • Develop code that implements all forms of loops and iterators, including the use of for, the enhanced for loop (for-each), do, while, labels, break, and continue; and explain the values taken by loop counter variables during and after loop execution.

  • Develop code that makes use of assertions, and distinguish appropriate from inappropriate uses of assertions.

  • Develop code that makes use of exceptions and exception handling clauses (try, catch, finally), and declares methods and overriding methods that throw exceptions.

  • Recognize the effect of an exception arising at a specified point in a code fragment. Note that the exception may be a runtime exception, a checked exception, or an error.

  • Recognize situations that will result in any of the following being thrown: ArrayIndexOutOfBoundsException,ClassCastException, IllegalArgumentException, IllegalStateException, NullPointerException, NumberFormatException, AssertionError, ExceptionInInitializerError, StackOverflowError or NoClassDefFoundError. Understand which of these are thrown by the virtual machine and recognize situations in which others should be thrown programatically.


    Section 3: API Contents
  • Develop code that uses the primitive wrapper classes (such as Boolean, Character, Double, Integer, etc.), and/or autoboxing & unboxing. Discuss the differences between the String, StringBuilder, and StringBuffer classes.

  • Given a scenario involving navigating file systems, reading from files, or writing to files, develop the correct solution using the following classes (sometimes in combination), from java.io: BufferedReader,BufferedWriter, File, FileReader, FileWriter and PrintWriter.

  • Develop code that serializes and/or de-serializes objects using the following APIs from java.io: DataInputStream, DataOutputStream, FileInputStream, FileOutputStream, ObjectInputStream, ObjectOutputStream and Serializable.

  • Use standard J2SE APIs in the java.text package to correctly format or parse dates, numbers, and currency values for a specific locale; and, given a scenario, determine the appropriate methods to use if you want to use the default locale or a specific locale. Describe the purpose and use of the java.util.Locale class.

  • Write code that uses standard J2SE APIs in the java.util and java.util.regex packages to format or parse strings or streams. For strings, write code that uses the Pattern and Matcher classes and the String.split method. Recognize and use regular expression patterns for matching (limited to: . (dot), * (star), + (plus), ?, \d, \s, \w, [], ()). The use of *, +, and ? will be limited to greedy quantifiers, and the parenthesis operator will only be used as a grouping mechanism, not for capturing content during matching. For streams, write code using the Formatter and Scanner classes and the PrintWriter.format/printf methods. Recognize and use formatting parameters (limited to: %b, %c, %d, %f, %s) in format strings.

    Section 4: Concurrency

  • write code to define, instantiate, and start new threads using both java.lang.Thread and java.lang.Runnable.

  • Recognize the states in which a thread can exist, and identify ways in which a thread can transition from one state to another.

  • Given a scenario, write code that makes appropriate use of object locking to protect static or instance variables from concurrent access problems.

  • Given a scenario, write code that makes appropriate use of wait, notify, or notifyAll.

    Section 5: OO Concepts

  • Develop code that implements tight encapsulation, loose coupling, and high cohesion in classes, and describe the benefits.

  • Given a scenario, develop code that demonstrates the use of polymorphism. Further, determine when casting will be necessary and recognize compiler vs. runtime errors related to object reference casting.

  • Explain the effect of modifiers on inheritance with respect to constructors, instance or static variables, and instance or static methods.

  • Given a scenario, develop code that declares and/or invokes overridden or overloaded methods and code that declares and/or invokes superclass, overridden, or overloaded constructors.

  • Develop code that implements "is-a" and/or "has-a" relationships.


    Section 6: Collections / Generics

  • Given a design scenario, determine which collection classes and/or interfaces should be used to properly implement that design, including the use of the Comparable interface.

  • Distinguish between correct and incorrect overrides of corresponding hashCode and equals methods, and explain the difference between == and the equals method.

  • Write code that uses the generic versions of the Collections API, in particular, the Set, List, and Map interfaces and implementation classes. Recognize the limitations of the non-generic Collections API and how to refactor code to use the generic versions.

  • Develop code that makes proper use of type parameters in class/interface declarations, instance variables, method arguments, and return types; and write generic methods or methods that make use of wildcard types and understand the similarities and differences between these two approaches.

  • Use capabilities in the java.util package to write code to manipulate a list by sorting, performing a binary search, or converting the list to an array. Use capabilities in the java.util package to write code to manipulate an array by sorting, performing a binary search, or converting the array to a list. Use the java.util.Comparator and java.lang.Comparable interfaces to affect the sorting of lists and arrays. Furthermore, recognize the effect of the "natural ordering" of primitive wrapper classes and java.lang.String on sorting.

    Section 7: Fundamentals

  • Given a code example and a scenario, write code that uses the appropriate access modifiers, package declarations, and import statements to interact with (through access or inheritance) the code in the example.

  • Given an example of a class and a command-line, determine the expected runtime behavior.

  • Determine the effect upon object references and primitive values when they are passed into methods that perform assignments or other modifying operations on the parameters.

  • Given a code example, recognize the point at which an object becomes eligible for garbage collection, and determine what is and is not guaranteed by the garbage collection system. Recognize the behaviors of System.gc and finalization.

  • Given the fully-qualified name of a class that is deployed inside and/or outside a JAR file, construct the appropriate directory structure for that class. Given a code example and a classpath, determine whether the classpath will allow the code to compile successfully.

  • Write code that correctly applies the appropriate operators including assignment operators (limited to: =, +=, -=), arithmetic operators (limited to: +, -, *, /, %, ++, --), relational operators (limited to: <, <=, >, >=, ==, !=), the instanceof operator, logical operators (limited to: &, |, ^, !, &&, ||), and the conditional operator ( ? : ), to produce a desired result. Write code that determines the equality of two objects or two primitives.

Read more...

Friday, May 1, 2009

Date,Time in your Specified Format

Many times in your application you need to fetch system date,time in some particular format.In following Source code I have illustrated the way you can get date,time .I have used SimpleDateFormat class with an argument which specifies the format and Calendar class for getting instance of time combined with date.

Example:-

//dateformat.java

import java.util.Calendar;
import java.io.Serializable;
import java.util.Date;
import java.text.SimpleDateFormat;

public class dateformat
{
public dateformat()
{
System.out.println(now("EEEEEE"));
System.out.println(now("yyyy/MM/dd"));
System.out.println(now("yyyy"));
System.out.println(now("MMMMM"));
System.out.println(now("MMMMM dd yyyy hh:mm aaa "));
System.out.println(now("dd MMMMM yyyy "));
System.out.println(now("dd yyyy MMMMM "));
System.out.println(now("hh:mm aaa "));
}
public String now(String dateFormat) {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
return sdf.format(cal.getTime());
}
public static void main(String a[])
{
new dateformat();
}
}

OutPut:-

Read more...

Tips to Crack SCJP

Following are Tips to Crack SCJP :-

1.Concentrate only on one book although you may refer various quiz engines for practice
Recommended: Katherine Sierra and Bert Bates and Khalid E Mughal.

2.Atleast 2 months of hard work.

3.Always try to experiment with your own.That is try run any program with complex and simple modifications.

4.Be very clear and specific about programming and syntax rule for that you may visit Javaranch.com for playing rule roundup game.

5.Give as many mock exams as you can as they will increase your chances of cracking the exam.

6.If in the Exam you are not sure of any option try omitting the options.

7.Go on to solve questions that have less to read and easy to answer as by the end of SCJP exam you will be getting exhausted and loosing patience.

8. First guess which concept is being tested and then bring out all the facts about that concept from the back of your mind.



Apart from these if you have any problems then you can send it to javatute@gmail.com

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