Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts
Monday, June 3, 2013

What is Java, Introduction of Java, What is Core Java, Features of Java


What is Core Java?

Core Java means core components of Java Programming Language like the basics of java, how to write programs in java, how to compile the java code, how to run the java code, concepts of classes and objects, operators, operands in java, Conditional statements in java, iterative statements in java, inheritance in java, polymorphism in java, Exception handling in java, File Handling in java etc.
The above mentioned topics are comes under the core part of java and these concepts should be clear for each java programmer for learning advance topics of java.

Java is an object-oriented programming language developed by Sun Microsystems, It is an Advancement of C++, initially Java was developed for programmed the Embedded Systems like Microwave Oven etc, the Java language was designed to be small, simple, and portable across platforms and operating systems, both at the source and at the binary level.

Java has become popular, because of Internet Programming.Java programs works on the write once and run anywhere terminology. Java is simple, object oriented, distributed, interpreted, robust, secure, architecture neutral, portable, high performance, multi-threaded, and dynamic.


Java programs can be run through the web browser by its Applet Programming, user can deploy any application on the internet through the Java Applets.


The java applications can be run from a Web server to generate dynamic Web pages, by Servlet.


Java is a multipurpose language you can develop the program for standalone computers, web servers and small handheld devices too in java.


Features of Java:-

Object Oriented :Supports OOP's Features.
Platform independent : Can be run any platform like any OS.
Simple :Easy to learn.
Secure : Do not support pointers so it is secure
Architectural - neutral : Can be run any of the system architecture.
Portable : Can be transfer to any other system without changes.
Robust :Trusted to develop softwares.
Multi-threaded : Support multi thread with one time execution.
Compiled and Interpreted : Java is Compiled and Interpreted language.
High Performance 
Distributed :
Dynamic :

The Core components of java are described below.


Wednesday, May 15, 2013

How to Change Font Color of a Label in Java, Changing Font of a Label in Java


How to Change Font Color of a Label in Java, Changing Font of a Label in Java



There are several ways to change the Font of a Label in Java.We can change the font color, font size, font type, font weight etc. I am showing an example for doing these task in one example.

Example:-

import java.awt.*;
public class ChangeFont extends Frame
{
Label lbl;
public ChangeFont()
{
Font font=new Font("Curlz MT",Font.BOLD,20);
this.setSize(400,200);
this.setTitle("Change Font of a Label");
this.setLayout(null);
this.setVisible(true);
lbl=new Label("This is Sample Text");
lbl.setBounds(100,80,200,40);
lbl.setFont(font);
lbl.setForeground(Color.RED);
this.add(lbl);
}
public static void main(String st[])
{
new ChangeFont();
}

}

I am sure the above example definitely helps you.

Thanks for visiting
Tuesday, May 14, 2013

How to Sort ArrayList of Objects in Java, Sorting ArrayList by Objects in Java


How to Sort ArrayList of Objects in Java, Sorting ArrayList by Objects in Java



In java ArrayList is a collection of Objets means when we want to store the collection of objects into a single variable the ArrayList is used.

Sorting of Integer, Float, Double, Long and String is very simple, Java provide the Collections interface to sort the list.

For Example

import java.util.ArrayList;
import java.util.Collections;

class SortArrayList
{
public static void main(String st[])
{
ArrayList<String> strlist=new ArrayList<String>();
strlist.add("Java");
strlist.add("XML");
strlist.add("AJAX");
strlist.add("SQL");
strlist.add("ASP.Net");
strlist.add("JavaScript");

System.out.println("UnSorted List");
for(String str:strlist)
  System.out.println(str);

Collections.sort(strlist);

System.out.println("Sorted List");

for(String str:strlist)
  System.out.println(str);
}
}

Output

UnSorted List
Java
XML
AJAX
SQL
ASP.Net
JavaScript

Sorted List
AJAX
ASP.Net
Java
JavaScript
SQL

XML

But if you want to Sort the ArrayList for those objects which does not has the countable values like TextFiled, Button etc.
Then there is no method in java to sort such ArrayList but you can Sort it by apply some logic which i am provided to you.

Example to Sort the ArrayList for TextField

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

import java.util.*;

class SortArrayList extends JFrame
{
public static void main(String st[])
{
ArrayList<TextField> newBox=new ArrayList<TextField>();
int yVal=80;
public SortArrayList()
{
this.setSize(600,500);
this.setVisible(true);

this.setLayout(null);
this.setTitle("Sorting ArrayList for TextFields");
for(int i=0;i<5;i++)
{
TextField t=new TextField();
yVal+=60;
t.setBounds(xVal, yVal,75,50);
add(t);

newBox.add(t);

sortArrayList();
}
public void sortArrayList()
{
TextField[] temp=newBox.toArray(new TextField[newBox.size()]);
for(int i=0;i<temp.length;i++)
{
for(int j=0;j<temp.length;j++)
{
if(Integer.parseInt(temp[i].getText())<Integer.parseInt(temp[j].getText()))
{
TextField tmp=temp[i];
temp[i]=temp[j];
temp[j]=tmp;
}
}

}
for(int i=0;i<5;i++)
  newBox.remove(i);
for(int i=0;i<5;i++)
  newBox.add(temp[i]);
for(int i=0;i<5;i++)
System.out.println(newBox.get(i).getText());
}

}
}

The Above Example is a sample example for Sorting the TextField by value and you can sort any object with this logic.


Please Give your valueable Comments
Thanks & Regards
Talib Hassan

Monday, May 13, 2013

How to set Image on JButton in Java Swing, Java Swing Setting Image Icon on JButton


How to set Image on JButton in Java Swing, Java Swing Setting Image Icon on JButton



The Java Swing Provide the JButton for adding an image on the Button this is a call which has diffrent Constructor to do it, and some merhods to do it.

Setting Image By Constructor

JButton btnBack=new JButton(new ImageIcon("back.jpg"));
or
JButton btnBack=new JButton(new ImageIcon("Back","back.jpg"));

Setting Image By Method
JButton btnBack=new JButton();
Image img = getToolkit().createImage("back.jpg");
ImageIcon btnIcon = new ImageIcon(img);

btnBack.setIcon(myIcon);


Friday, April 19, 2013

Use of Break And Continue keywords in Java, Break and Continue Keywords in Java


Use of Break And Continue keywords in Java, Break and Continue Keywords in Java


Two keywords, break and continue, can be used in loop statements to provide additional controls. Using break and continue can simplify programming in some cases like sometimes if you don't want to execute the statement after a specific statement.

You can use the keyword break in a switch statement. You can also use break in a loop with the help of a conditional (if) statement to immediately terminate the loop.

The following program demonstrate the effect
of using break in a loop.


public class Test {
public static void main(String st[]) {
int sum = 0;
int num = 0;
while (num < 20) {
num++;
sum += num;
if (sum >= 100)
break;
}

System.out.println("The number is " + num);
System.out.println("The sum is " + sum);
}
}

Output:-

The number is 14
The sum is 105


The above program adds integers from 1 to 20 in this order to sum until sum is greater than or equal to 100. Without the if statement, the program calculates the sum of the numbers from 1 to 20. But with the if statement when the sum becomes less then or equal to 100 the loop has terminate and the output is as follows--

The number is 20
The sum is 210


You can also use the continue keyword in a loop. When it is encountered, it ends the current iteration. Program control goes to the end of the loop body. In other words, continue breaks out of an iteration while the break keyword breaks out of a loop.The following program demonstrate the effect of using continue in a loop.


public class Test {
public static void main(String st[]) {
int sum = 0;
int num = 0;
while (num < 20) {
num++;
if (num == 10 || num == 11)
continue;
sum += num;
}
System.out.println("The sum is " + sum);
}
}

Output:-

The sum is 189


The above program adds integers from 1 to 20 except 10 and 11 to sum. With the if statement in the program, the continue statement is executed when number becomes 10 or 11 and the 10 and 11 numbers are not added to the sum and the output is as follows

The sum is 210

In this case, all of the numbers are added to sum, even when number is 10 or 11. Therefore, the result is 210, which is 21 more than it was with the if statement.



Core Java Tutorials - Iterative Statements (Loops) in Java, For Each Loop in Java, For Loop, While Loop, Do-while Loop in Java


Iterative Statements (Loops) in Java, For Each Loop in Java, For Loop, While Loop, Do-while Loop in Java


Suppose that you want to print a string like "Java is an Object Oriented Programming" a 100 times. It would be lengthy process to write the following statement a 100 times:

System.out.println("Java is an Object Oriented Programming!");
System.out.println("Java is an Object Oriented Programming!");
...
...
...
System.out.println("Java is an Object Oriented Programming!");

So, how do you solve this problem?

Java gives a powerful feature called a loop that controls how many times an operation or a sequence of operations is performed in succession. Using a loop statement, you simply tell the computer to print a string a 100 times without printing the hard coded code to print the statement a 100 times, as follows: 

int c = 0;
while (c < 100) {

System.out.println("Java is an Object Oriented Programming!");

c++;
}


The variable c is initially 0. The loop checks whether (c < 100) is true. If so, it executes the loop body to print the message "Java is an Object Oriented Programming!" and increments c by 1. It repeatedly executes the loop body until (c < 100) becomes false. When (c < 100) is false (i.e., when c reaches 100), the loop terminates and the next statement. after the loop statement is executed.


Loops are constructs that control repeated executions of a block of statements. The concept of looping is fundamental to programming. Java provides three types of loop statements: while loops, do-while loopsfor loops and for-each loop.


The while Loop

The syntax for the while loop is as follows:

while (condition) 
{
// Loop body
Statement 1;
Statement 2;
........
........
Statement n;
}




Example

class whileDemo
{
public static void main(String st[])
{
char ch;
ch='a';
while(ch<='z'){
System.out.println(ch);
ch++;
}
}
}



The do-while Loop
The do-while loop is an another way of the while loop. But, The do-while loop executes the loop body first, then checks the loop condition to determine whether to continue or terminate the loop. The do-while loop must be execute at least one time whether the condition will true or false.The syntax is given below:

do {
// Loop body;
Statement(1);
Statement(2);
...........
...........
Statement(n);
} while (loop-condition);



Example:-
public class Test
{
public static void main(String st[])
{
int a=5;
int b=1;
do{
int c=1;
do{
if((c==b)||(c==a+1-b))
System.out.print("#");
else
System.out.print("#");
b++;
}while(c<=a);
System.out.println();
b++;
}while(b<=a);
}
}




The for Loop:-

A for loop can be used to simplify the proceeding loop:

for (i = initial Value; i < end Value; increments or decrements) {
// Loop body
Statement(1);
Statement(1);
........
........
Statement(n);
}

In general, the syntax of a for loop is as shown below:

for (initial-action; loop-condition;
action-after-each-iteration) {
// Loop body;

Statement(1);
Statement(1);
........
........

Statement(n);
}
Example:-

public class ForLoopsDemo
{
public static void main(String st[])
{
int loopVal;
int endVal=11;
for(loopVal=0;loopVal<endVal;loopVal++)
{
System.out.println("Loop Value "+loopVal);
}
}
}




For-Each Loop:-

The for-each loop is used to iterate a collection for example if we want to print the all elements of an array then we need to find the length of the array and iterate it from 0 to less then length but if we use the for-each loop we don't need to find the length of the array.

Example:-

int numbers[]=new numbers[]{12,23,43,25,65,67};
for(int num:numbers)
{
System.out.println(num);
}

it will print
12
23
43
25
65
67





Core Java Tutorials - Type Casting in Java, How to cast a type to another type in Java, Difference between implicit and explicit type casting in java


Type Casting in Java, How to cast a type to another type in Java, Difference between implicit and explicit type casting in java


In Java Casting is an operation that converts a value of one data type into a value of another data type. There are two type of Type Casting in Java (1)Implicit Type Casting, (2)Explicit Type Casting.
Casting a variable of a type with a small range to a variable of a type with a larger range is known as widening a type. Casting a variable of a type with a large range to a variable of a type with a smaller range is known as narrowing a type. Widening a type can be performed automatically without explicit casting. Narrowing a type must be performed explicitly. 
The syntax is the target type in parentheses, followed by the variable’s name or the value to be cast. For example, the following statement


System.out.println((int)1.9);

Display Output 1 because, if a double value is cast into an int value, then the  fractional part is truncated.

The following statement

System.out.println((double)2 / 4);


Displays Output 0.5, because 2 is cast to 2.0 first, then 2.0 is divided by 4. 

See This Example again

System.out.println(2 / 4);

Displays Output 0, because 2 and 4 are both integers and the resulting value should be an integer.

Note:- Casting is necessary if you are assigning a value to a variable of a smaller type range, such as assigning a double value to an int variable. A compile error will occur if casting is not used in situations of this kind. Be careful when using casting. Loss of information might lead to inaccurate results.


Casting does not change the variable being cast. For example, d is not changed after casting in the following code:

double d = 7.5;
int i = (int)d; // i becomes 7, but d is not changed, still 7.5


To assign a variable of the int type to a variable of the short or byte type, explicit casting must be used. For example, the following statements have a compile error:

int i = 1;
byte b = i; // Error because explicit casting is required







Thursday, April 18, 2013

Core Java Tutorials - Creating Constants in Java, How to Create Constants in Java


Creating Constants in Java, How to Create Constants in Java


A simple variable's value can be change during the program execution but a constant value can't be change after it's creation time.

A constant must be declared and initialized in the same statement. In other programming languages like C and C++, we use a keyword const to declare a constant same as the word final is a Java keyword for declaring a constant. For example, you can declare PI as Constant like this-

final double PI=3.14159;

Benefits for declaring constants


There are three benefits of using constants:

(1) you don’t have to repeatedly type the same value.

(2) if you have to change the constant value (e.g., from 3.14 to 3.14159 for PI), you need to change it only in a single location in the source code.

(3) A descriptive name for a constant makes the program easy to read.


Core Java Tutorials - Identifiers in Java, Variables declaration in Java, How to Declare Variables in Java


Identifiers in Java, Variables declaration in Java, How to Declare Variables in Java

The Identifiers(Variables) are used to store the data in any programming language and the use of Identifiers are same in java like other languages. Identifiers are the combination of letters, digits, underscores(_) and dollar signs($).

Rules for constructing Identifiers in Java 


  • An identifier is a sequence of characters that consists of letters, digits, underscores (_), and dollar signs ($).
  • An identifier must start with a letter, an underscore (_), or a dollar sign ($). It cannot start with a digit.
  • An identifier cannot be a reserved word. (See Appendix A, “Java Keywords,” for a list of reserved words.)
  • An identifier cannot be true, false, or null.
  • An identifier cannot be a keyword.
  • An identifier can be of any length.
  • An Identifier should have its data type.

Examples of valid variables declaration 

double radious=1.0;
double area=radious*radious*3.14159;
String data="Hello Identifier";
int value=30;
int roll_no=1001;
String permanent_add;

Examples of invalid variables declaration 


double 1radious=1.0;
double @area=radious*radious*3.14159;
String da.ta="Hello Identifier";
int val&ue=30;
int roll#no=1001;
String permanent*add;



 

Core Java Tutorials - Reading Input from the keyboard in Java, How to read input from keyword in Java, Scanner Class in Java


Reading Input from the keyboard in Java, How to read input from keyword in Java, Scanner Class in Java

Java uses System.out to refer to the standard output device and System.in to the standard input device. These are the InputStream and OutputStream class's methods. By default the output device is the display monitor, and the input device is the keyboard. To perform console output, you simply use the println() method to display a primitive value or a string to the console. Console input is not directly supported in Java but,
There are several method to reading input from the console in java some of them are as follwos:-


  • Console Class
  • DataInputStream Class 
  • Scanner Class

I am using the Scanner class to create an object to read input from System.in, as follows:

Scanner input = new Scanner(System.in);

The above statement creates a input object of Scanner type with the help of new Scanner(System.in). Here input is a variable whose type is Scanner. The whole line Scanner input = new Scanner(System.in) creates a Scanner object and assigns its reference to the variable input.This object able to invoke any method of Scanner Class.
Here is The list of some Scanner Class Methods.



Methods for Scanner Objects
MethodDescription
nextByte()reads an integer of the byte type.
nextShort()reads an integer of the short type.
nextInt()reads an integer of the int type.
nextLong()reads an integer of the long type.
nextFloat()reads a number of the float type.
nextDouble()reads a number of the double type.
next()reads a string that ends before a whitespace character.
nextLine()reads a line of text (i.e., a string ending with the Enter key pressed).


public class ExecuteCircleArea
{ 
public static void main(String st[]) {
// Create a Scanner Class object
Scanner in = new Scanner(System.in);
// Prompt a message to the user to enter a radius 

System.out.print("Enter a number for radius: ");
double r =in.nextDouble();
// Compute area 
double area = r * r * 3.14159; 
// Display result  of area
System.out.println("The area for the circle of radius " + 
r + " is " + area); 
} 
}

Core Java Tutorials - Program Execution in Java, How to Compile a Java Program and How to Run A Java Program


Core Java Tutorials - Program Execution in Java, How to Compile a Java Program and How to Run A Java Program





A Java compiler translates a Java source file into a Java bytecode file. The following command compiles Welcome.java:

javac Welcome.java

If there are no syntax errors, the compiler generates a byte code file with a .class extension. So the preceding command generates a file named 
Welcome. class


The Java language is a high-level language while Java bytecode is a low-level language. The bytecode is similar to machine instructions but is architecture neutral and can run on any platform that has a Java Virtual Machine (JVM) Rather than a physical machine, the virtual machine is a program that interprets Java bytecode. This is one of Java’s primary advantages Java bytecode can run on a variety of hardware platforms and operating systems.

To execute a Java program is to run the program’s byte code. You can execute the byte code on any platform with a JVM. Java byte code is interpreted. Interpreting translates the individual steps in the byte code into the target machine-language code one at a time rather than translating
the whole program as a single unit. Each step is executed immediately after it is translated. The following command runs the byte code:

java Welcome


Core java Tutorials - A simple program in java, How to Write Program in Java


A simple program in java, How to Write Program in Java

Let us begin with a simple Java program that displays the message “Welcome To Java!
Java is an Object Oriented Prog Language!” on the console.


Welcome.java

class Test
{
    public static void main(String st[])
    {
       System.out.println("Welcome To Java!\n Java is an Object Oriented Prog Language!"); // Display the message on console
    }
}


Output

Welcome To Java!
 Java is an Object Oriented Prog Language!


Here is an another program to display multiple messages 


Welcome1.java


public class Test
{
public static void main(String[] args) 
{
System.out.println("Java is an Object Oriented Prog Language!");
System.out.println("Java is Robust!");
System.out.println("I love Programming!");
}
}

Output

Java is an Object Oriented Prog Language!
Java is Robust!
I love Programming!
Saturday, March 9, 2013

How to set javac path - setting up jdk path, How to set java path in environment variables


How to set javac path - setting up jdk path, How to set java path in environment variables

To compile and run a java program from command prompt we need to tell the java compiler and java interpreter path to the DOS System because javac and java commands are not defined in command prompt so we explicitly tell the javac and java path to the DOS command prompt.


Setting Up Java path:-


There are few steps to set the java path for command prompt.

The first method to set up path for one time...

>> Open Command prompt

>> Go to your directory where your program is saved.
If your program saved in "javawork" folder in D drive, change your directory like this.

c:\Program Files>D:

now you are in d drive and the path is now like this..

D:\>

Now change the directory like this

D:\>cd javawork press enter

Now you are in javawork directory and the path look like this.

D:\javawork>

now write your jdk path setting string like this

D:\javawork>set path=%path%;C:\Program Files\Java\jdk1.7.0\bin press enter
 
Now your path set for one time, this path scope will remain till the command prompt is open now, write your program name like this
 
D:\javawork>javac programname.java press enter
 
If your program doesn’t have any error then your program is compiled successfully and the screen show like this  

D:\javawork>

Now you need to run your program like this

D:\javawork>java programname press enter

If your program does not have any runtime error then you can see your desired output..


 This method to set up path for all time...


Go to your java installation files like by default the jdk is installed in c:\Program Files\java\jdk 1.7.0\bin

so if your jdk installed in same directory so simply go to your installation path and copy the path from windows explorer address bar.

after copying the path right click on My Computer and the click on properties.

if you are using windows xp then you are directly see a button with name Environment Variables,
if you are using higher version of windows then you see the Advance System Settings and then you can see Environment Variables Button.

click on this button and you see the user variables click on new button, a new window appear with two text boxes write path on first textbox and paste the copied path into the second textbox then ; and then ok ok ok.


Now your path has been set and you can directly run your program by following the above steps