Operators Controllers Loops

Incrementing (++) and Decrementing (--):

The ++ operator increments its operand by one and the -- operator decrements its operand by one.

Ex.

public class app
{
public static void main(String[] args)
{
int a=0, b=1;
a++; // Increment operation. As a = a +1
b--; // Decrement operation. As b = b -1
System.out.println("A = "+ a +"\nB = "+ b);
}
}

Output:

A = 1
B = 0

Topñ

Unary Not: ~ and !

The ~ operator is the bitwise unary Not operator and ! is the logical unary Not operator. So , the ~ operator flips all the bits of numeric arguments and the ! operator flips true values to false and false value to true.

public class app
{
public static void main(String[] args)
{
short short1 = 32767;
boolean boolean1 = true;
System.out.println("Most negative short = "+ ~short1); // ~ operator is used in integer value
System.out.println("!true = "+ !boolean1); // ! operator is used in boolean value
}
}

Output:

Most negative short = -32768
!true = false

Topñ

Addition Subtraction Multiplication Division: + - * /

public class app
{
public static void main(String[] args)
{
int a = 2, b = 6, add, subt, mult, div;
add = a + b; // add = 2 + 6 = 8
subt = b - a; // subt= 6 - 2 = 4
mult = a * b; // mult = 6 * 2 = 12
div = b / a; // div = 6 / 2 = 3
System.out.println("a = "+ a +"\tb = "+b);
System.out.println("Addition of a and b = "+ add);
System.out.println("Subtraction of a and b = "+ subt);
System.out.println("Multiplication of a and b = "+ mult);
System.out.println("Division of a and b = "+ div);
}
}

Output:

a = 2 b = 6
Addition of a and b = 8
Subtraction of a and b = 4
Multiplication of a and b = 12
Division of a and b = 3

Topñ

Shift Operators: >>, >>>, and <<

Syntax:

new_value = value << number_places;
new_value = value >> number_places;
new_value = value >>> number_places;

Ex.

public class app
{
public static void main(String[] args)
{
int value = 16, negvalue = -1;
System.out.println(value + " << 2 = "+ (value << 2));
System.out.println(value + " >> 2 = "+ (value >> 2));
System.out.println(negvalue + " >> 2 = "+ (negvalue >> 2));
System.out.println(negvalue + " >>> 22 = "+ (negvalue >>> 22));
}
}

Output:

16 << 2 = 64
16 >> 2 = 4
-1 >> 2 = -1
-1 >>> 22 = 1023

Topñ

Relational Operators: > , >= , < , <= , == , !=

You can use relational operators to create logical conditions that you can test with conditional statement such as the if statement.

Ex.

public class app
{
public static void main(String[] args)
{
int budget = 1;
if ( budget < 0 ) // Relational operators (<) is used in if statement
{
System.out.println("Uh oh.");
}
else {
System.out.println("Still solvent.");
}
}
}

Output:

Still solvent

Relational Operators Description
> Greater than
>= Greater than or equal to
< Less then
<= Less than or equal to
== Equal to
!= Not equal to

Topñ

Bitwise and Bitwise Logical And, Xor, Or: &, ^, |

Ex.

public class app
{
public static void main(String[] args)
{
int value = 12;
int bit3setting = value & 1 <<3;
if ( bit3setting != 0){
System.out.println("Bit 3 is set.");
}
else {
System.out.println("Bit 3 is not set.");
}
}
}

Output:

Bit 3 is set.

X Y X|Y (Or) X&Y (And) X^Y (Xor)
0 0 0 0 0
1 0 1 0 1
0 1 1 0 1
1 1 1 1 0

public class App
{
public static void main(String[] args)
{
int buget=1;
boolean fired=false;

if(buget<0 | fired==true){
System.out.println("Uh oh.");
}
else {
System.out.println("Still Solvent");
}
}
}

Output

2419430 kbps Topñ

Logical && and ||:

Topñ

The if-then-else operator: ?:

There's java operator that acts much like an if-else statement - the ternary operator (?:). This operator is called a ternal operator because it takes three operands - a condition and two values.

Syntax: value = condition ? value1 : value2;

If condition is true then value = value1 and when condition is false, value=value2.

Ex.

public class app
{
public static void main(String[] args)
{
int value = 15;
String digit, chars[]={"a","b","c","d","e","f"};
digit = value < 10 ? String.valueOf(value) : chars[value - 10];
System.out.println(value +" = 0x"+digit);
}
}

Output:

15 = 0xf

Topñ

Assignment operators: =

Ex

public class app
{
public static void main(String[] args)
{
int value1, value2, value3;
value1=value2=value3=12;
System.out.println("Value1 = "+ value1);
System.out.println("Value2 = "+ value2);
System.out.println("Value3 = "+ value3);
}
}

Output:

Value1 = 12
Value2 = 12
Value3 = 12

We can combine many operators with the assignment operator (=). For example, += is the addition assignment operators, which means value+=2 is a shortcut for value = value + 2.

Ex.

public class app
{
public static void main(String[] args)
{
int value = 10;
value *= 2; // value = value * 2 => value = 10 * 2 => value = 20
System.out.println("Value * 2 = "+ value);
}
}

Output:

Value * 2 = 20

There are quite a few combination assignment operators.

Assignment Operators Description
% module assignment
&= bitwise And assignment
*= multiplication assignment
/= division assignment
^= bitwise Xor assignment
|= bitwise Or assignment
+= addition assignment
<<= shift left assignment
<= less than or equal to
- = subtraction assignment
>>= shift right assignment
>>>= shift right zero fill assignment

Topñ

Using the Math Class:

We can use the java.lang.Math class to perform a great many operations.

Ex.

public class app
{
public static void main(String[] args)
{
System.out.println("3 * 3 * 3 * 3 = "+ Math.pow(3 ,4));
}
}

Output:

3 * 3 * 3 * 3 = 81.0

Here are the constants and methods of the Math class: Click here.

Topñ

Comparing String

When you're working with the String class, there are some methods you can use much like operators.

Functions Description
string1.equals( string2 ) True if string1 equals string2
string1.equalsIgnoreCase( string2 ) True if string1 equals s2 (Ignoring case)
String1.compareTo( string2 ) Return a value less than zero is string1string2.

Ex.

public class app
{
public static void main( String[] args)
{
String s1="abc";
String s2="abc";
String s3="ABC";
String s4="bcd";
if (s1.equals(s2)){
System.out.println("s1 == s2");
}
else {
System.out.println("s1 != s2");
}

if (s1.equalsIgnoreCase(s3)){
System.out.println("s1 == s3 when ignoring case");
}
else {
System.out.println("s1 != s3 when ignoring case");
}

if (s1.compareTo(s4) < 0){
System.out.println("s1 < s2");
}
else if( s1.compareTo(s4) == 0){
System.out.println("s1 == s2");
}
else if( s1.compareTo(s4) > 0){
System.out.println("s1 > s2");
}
}
}

Output:

s1 == s2
s1 == s3 when ignoring case
s1 < s2

Variables Arrays and Strings

Variable Type Bytes of Storage Range
boolean 2 True, False
byte 1 -128 to 127
char 2 N/A
double 8 -1.7976931348623E308 to -9406545841247E-324 for negative values.
4 4.94065645841247E-324 to 1.79769313486232E308 for positive values.
float 4 -3.4028223E38 to -1.401298E-45 for negative values and 1.401298E-45 to 3.402823E38 for positive values.
int 4 -2147483648 to 2147483647
long 8 -9223372036854775808 to 9223372036854775807
short 2 -32768 to 32767




Integer variable

Example of Integer variable,

public class app
{
public static void main(String[] args)
{
int days;
days=365;
System.out.println("Number of days = "+days);
}
}

Ex. Long can have more digits than int values, so java provides an explicit way of creating long.

public class app
{
public static void main(String[] args)
{
long value;
value=1234567890123456789L;
System.out.println("The value = "+value);
}
}

Ex. You can also create literals in octal format by starting them with a leading zero and in hexadecimal format by starting them with 0x or 0X.

public class app
{
public static void main(String[] args)
{
int value;
value=16;
System.out.println("16 decimal = "+value );
value=020;
System.out.println("20 octal = "+value+" in decimal" );
value=0x10;
System.out.println("10 hexadecimal = "+value+" in decimal");
}
}

Output:

C:\> java app
16 decimal =16
20 octal =16 in decimal
10 hexadecimal =16 in decimal

Java uses four types of integers, each with its own number of bytes put aside for it in memory: byte (one byte), short (two bytes), int (four bytes) and long (eight bytes).

Ex.

public class app
{
public static void main(String[] args)
{
byte byte1;
short short1;
int int1;
long long1;

byte1=1;
short1=100;
int1=10000;
long1=100000000;

System.out.println("Byte1 = "+byte1 );
System.out.println("Short1 = "+short1 );
System.out.println("int1 = "+int1 );
System.out.println("Long1 = "+Long1 );
}
}

Output:

Byte1 = 1
Short1 = 100
Int1 = 10000
Long1= 100000000

Ex. Initial variable.

public class app
{
public static void main(String[] args)
{
int int1, int2=200;
int1=100;
System.out.println("The Int1 = "+ int1 +"\nThe Int2 = "+ int2);
}
}

Output:

The Int1 = 100
The Int2 = 200

Ex. Dynamic initialize:

public class app
{
public static void main(String[] args)
{
int int1=2, int2=3;
System.out.println("The Int1 = "+ int1 +"\tThe Int2 = "+ int2);
int int3=int1*int2;
int1=int3;
System.out.println("\nThe Int1 = "+ int1 +"\tThe Int3 = "+ int3);
}
}

Output:

The Int1 = 2 The Int2 = 3
The Int1 = 6 The Int3 = 6

Converting between data type:

Automatic conversation:

When you're assigning one type of data to a variable of another type, java will convert the data to the new variable type automatically if both the following conditions are true:

1. The data type and the variable types are compatible.
2. The target type has a larger range than the source type.

Ex.

public class app
{
public static void main(String[] args)
{
byte byte1=1;
int int1;
int1=byte1;
System.out.println("The Int1 = "+ int1);
}
}

Output:

The Int1 = 1

Casting to new data type:

If you want to perform a narrowing conversion, you must use an explicit cast which looks like this,

(target-data-type) value

Ex.

public class app
{
public static void main(String[] args)
{
byte byte1;
int int1=1;
byte1=(byte) int1;
System.out.println("The Byte1 = "+ byte1);
}
}

=> Without the explicit type cast, the compiler would object, but with the type cast, there's no problem, because java decides that you know about the possibility of losing some data when you cram a possible larger value into a smaller type. For example, when you put a floating-point number into a long, the fractional part of the number will be truncated, and you may lose more data if the floating-point value is outside the range that a long can hold.

Ex.

public class vari {
public static void main(String[] args) {
char char1='A';
int int1;
int1=(int) char1;
System.out.println(" Character converted to Integer = "+ int1);
}
}

However, because java knows that multiplying bytes can result in integer-sized values, it automatically promotes the result of the byte1*byte2 operation into an integer, which means we actually have to use an explicit cast here to get back to the byte type.

Ex.

public class app_dynamic1
{
public static void main(String[] args)
{
byte byte1=100,byte2=100;
byte byte3;
byte3= byte1*byte2/100;
System.out.println("\nThe Byte3 = "+ byte3);
}
}

Output:

C:\>javac app_dynamic1.java
app_dynamic1.java:7: possible loss of precision found : int required: byte
byte3= byte1*byte2/100;
^
1 error

=> For this reason, we have to add an explicit cast to get back to the byte type. Example is given in below.

public class app_dynamic1
{
public static void main(String[] args)
{
byte byte1=100,byte2=100;
byte byte3;
byte3=(byte) (byte1*byte2/100);
System.out.println("\nThe Byte3 = "+ byte3);
}
}

Outout:

C:\>javac app_dynamic1.java

The Byte3 = 100


Float Variable

Floating-point literals are of type double by default in java code, example include 3.1415926535, 1.5 and 0.1111111. We can also indicate a power of 10 with e or E, such as 1.345E10. This is the same as 1.345*1010 or -9.999E-23, which is the same as -9.999*10-23.

Ex.

public class app
{
public static void main(String[] args)
{
float value;
value=1.5;
System.out.println("The value = "+value);
}
}

Output:

C:\> javac app.java

appt.java:6: possible loss of precision found : double required: float
value=1.5;
^
1 erro

=> Unfortunately, the default type for floating-point literals is double, so java gives me the following error. we can fix this by explicitly making my literal into a float,

public class app
{
public static void main(String[] args)
{
float value;
value=1.5f;
System.out.println("The value = "+value);
}
}

Output:

C:\> javac app.java

The value = 1.5

Java has two built-in types of floating-point variables, each with its own number of bytes set aside for it in memory: float (four bytes) and double (eight bytes).

Ex.

public class app
{
public static void main(String[] args)
{
float float1;
double double1;

float1=1.11111111111F;
double1=1.1111111111111E+9D;

System.out.println("Float1 = "+float1 );
System.out.println("Double1 = "+double11 );
}
}

Output:

C:\>java app

float1 = 1.1111112
double1 = 1.1111111111111E9


Boolean Variable

Boolean values can only be true or false in java.

Ex.

public class app
{
public static void main(String[] args)
{
boolean value1;
value1=true;
System.out.println("The value = "+value);
}
}

Output:

c:\> java app

the value = true

Ex. Here, we are using these two boolean variables with the java if statement. We test the value in boolean1 with the if statement, making the code display the message "boolean1 is true."

public class app
{
public static void main(String[] args)
{
boolean boolean1, boolean2;
boolean1=true;
boolean2=false;
System.out.println("The Boolean1 = "+boolean1);
System.out.println("The Boolean2 = "+boolean2);
if( boolean1 ){
System.out.println("The Boolean1 is TRUE");
} else {
System.out.println("The Boolean1 is FALSE");
}
}
}

Output:

C:\> java app

The Boolean1 = true
The Boolean2 = false
The Boolean1 is TRUE



Character Variable

Character literals are actually numbers that act as indexes into the Unicode character set, not actual characters.

Ex. The Unicode code for the letter C is 67. Therefore, the following application prints out a C:

public class app
{
public static void main(String[] args)
{
char char_value;
char_value=67;
System.out.println("The Character = "+char_value);
}
}

Output:

C:\> java app

The Character = C

Ex. You can also refer to the Unicode code for the letter C with a character literal, which you would enclose in single quotes.

public class app
{
public static void main(String[] args)
{
char char_value;
char_value='C';
System.out.println("The Character = "+ char_value);
System.out.println("The Character + 1 = "+ char_value + 1);
System.out.println("++char_value = "+ ++char_value);
}
}

Output:

C:\> java app

The Character = C
The Character + 1 = C1
++char_value = D

Note: You can also enclose special character escape sequences in single quotes to make character literals that you couldn't make by typing a single character. Here are the escape sequences.

\' - Single quote
\" - Double quote
\\ - Back slash
\b - Back Space
\ddd - Octal character
\f - Form feed
\n - New line; called a line feed in DOS and Windows.
\r - Carriage return
\uxxxx- Hexadecimal Unicode character.

Ex.

public class app
{
public static void main(String[] args)
{
System.out.println(" He said, \"Hello\" ");
}
}

Output:

C:\> java app

He said, "Hello"



Array

Declaring one-dimensional Array:

Arrays provide an easy way of handling a set of data by index. Getting an array ready for use is a two-step process. First, you must declare the array. The next step is to actually create that array by allocating memory for it.

Ex.

public class app
{
public static void main(String[] args)
{
double accounts[]; // First Step
accounts=new double[100]; // Second Step
...........
...........
}
}

Note: The lower bound of all java arrays is 0, so the first element in the array is accounts[0] and the last element is accounts[99]. That means total element is 100. If the array index is outside the range o to 99, java will create a fatal error and the program will halt.

In fact, we can combine the declaration and creation process into one step for arrays.

Ex.

public class app
{
public static void main(String[] args)
{
double accounts[]=new double[100]; // Declared in one statement
...........
...........
}
}

To initialize the data in one-dimensional array, you just place the values between curly braces, one value after the other, separated by commas, beginning with the first value in the array.

Ex.

public class app
{
public static void main(String[] args)
{
double accounts[]={238.45, 999.33, 0, 1335.67, 1111.11};
accounts[2]=99999.99;
System.out.println("Accounts[0] = "+ accounts[0] +"\nAccounts[2] = "+ accounts[2] +"\nAccounts[4] = "+ accounts[4]);
}
}

Output:

Accounts[0] = 238.45
Accounts[2] = 99999.99
Accounts[4] = 1111.11

Declaring Multidimensional Arrays:

You can declare multidimensional arrays in much the same way you declare one-dimensional arrays; just include a pair of square brackets for every dimension in the array.

Syntax: type array_name[][][]....;

Ex.

public class app
{
public static void main(String[] args)
{
double accounts[][]=new double[2][100]; // Two dimensional array
double account_id[][][][]=new double[2][3][4][5]; // Four dimensional array
...........
...........
}
}

Ex. Creating multidimensional Arrays.

public class app
{
public static void main(String[] args)
{
double accounts[][];
accounts = new double[2][100];
accounts[0][3] = 345.98
accounts[1][3] = 23456.65
System.out.println("Saving Account 3 has $ "+ accounts[0][3]);
System.out.println("Checking Account 3 has $ "+ accounts[1][3]);
}
}

Output:

Saving Account 3 has $ 345.98
Checking Account 3 has $ 23456.65

Ex. Initializing Multidimensional arrays.

public class app
{

public static void main(String[] args)
{
double accounts[][] = {{10.11,19.56,
12.56,48.78} , {11.20,34.74,25.58,45.67}};
System.out.println("Saving Account 3 has $ "+ accounts[0][2]);
System.out.println("Checking Account 3 has $ "+ accounts[1][2]);
}
}

Output:

Saving Account 3 has $ 12.56
Checking Account 3 has $ 25.58

Ex. We can construct arrays as we like as in this example, in which each row of a two-dimensional array has a different number of elements. which is called Creating Irregular Multidimensional Array.

public class app
{
public static void main(String[] args)
{
double accounts[][] = new double[5][];
accounts[0] = new double[500];
accounts[1] = new double[400];
accounts[2] = new double[300];
accounts[3] = new double[200];
accounts[4] = new double[100];

array[3][3] = 2666.76
System.out.println("Account[3][3] has $ "+ accounts[3][3]);
}
}

Output:

Account[3][3] has $ 2666.76

Ex. Getting an array's length. Such as how many elements are in that array.

public class app
{

public static void main(String[] args)
{
double grades[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
System.out.println("The length of Array = "+ grades.length);
}
}

Output:

The length of Array = 10



String

String objects hold text strings that you can't change; if you want to change the actual text in the string, you should use the StringBuffer class instead.

Creating Strings:

Ex..

public class app
{
public static void main( String[] args)
{
String s1="Hello from JAVA!";

String s2;
s2="Hello from JAVA!"

String s3= new String();
s3="Hello from JAVA!";

String s3= new String("Hello from JAVA!");

char c1[]={'H','i',' ','f','r','o','m',' ','J','A','V','A','!'};
String s5=new String(c1);

String s6=new String(c1,0,2);

double d1=1.23456789;
String s7=String.valueOf(d1);

System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
System.out.println(s4);
System.out.println(s5);
System.out.println(s6);
System.out.println(s7);
}
}

Output:

Hello from JAVA!
Hello from JAVA!
Hello from JAVA!
Hello from JAVA!
Hi
1.23456789

Topñ

Getting length of String:

Ex.

public class app
{
public static void main(String[] args)
{
String s1="Hello from JAVA!";
System.out.println("\""+ s1 +"\" is "+ s1.length() +" Characters long.");
System.out.println("\"Hello\" is "+ "Hello".length() +" Characters long.");
}
}

Output:

"Hello from JAVA!" is 16 Characters long.
"Hello" is 5 Characters long.

Topñ

Concatenating String:

Ex. Concatenating String is used to join two strings and create a new one.

public class app
{
public static void main(String[] args)
{
String s1="Hello ";

String s2=s1 + "from ";
String s3=s2 + "Java!";

String s4=s1.concat("from ");
String s5=s4.concat("Java!");

System.out.println(s3);
System.out.println(s5);
}
}

Output:

Hello from JAVA!
Hello from JAVA!

Topñ

Getting Characters and Substrings:

Ex. Getting characters is used to get the character at a specific position. You can also use the substring method to create a new string that's substring of the old one, like this:

public class app
{
public static void main(String[] args)
{
String s1="Hello from JAVA!";

char c1=s1.charAt(0);
System.out.println("The first character of \" "+ s1 + " \" is "+ c1);

char chars1[]=s1.toCharArray(); // Getting a Character from given String
System.out.println("The second character of \" "+ s1 + " \" is "+ chars1[1]);

char chars2[]=new char[5]; // Getting characters from given String
s1.getChars(0,5,chars2,0);
System.out.println("The first five characters of \" "+ s1 + " \" are "+ new String(chars2));

String s2=s1.substring(0,5); // Getting Substrings from given String
System.out.println("The first five characters of \"" + s1 +" \" are "+ s2);
}
}

Output:

C:\jdk1.3\myproject>java app
The first character of "Hello from JAVA!" is H
The second character of "Hello from JAVA!" is e
The first five characters of " Hello from JAVA!" are Hello
The first five characters of "Hello from JAVA!" are Hello

Topñ

Searching for and replacing Strings:

Ex.

public class app
{
public static void main(String[] args)
{
String s1="I have drawn a nice drawing.";

System.out.println("The first occurrence of \"draw\" is "+"at location "+ s1.indexOf("draw")); // Searching from first position

System.out.println("The last occurrence of \"draw\" is "+"at location "+ s1.lastIndexOf("draw")); // Searching from last position

String s2="Edna, you\'re hired!"; // Replacing strings or character
System.out.println(s2.replace('h','f'));
}
}

Output:

C:\jdk1.3\myproject>java app
The first occurrence of "draw" is at location 7
The last occurrence of "draw" is at location 20
Edna, you're fired!

Topñ

Changing Case In Strings:

Ex.

public class app
{
public static void main(String[] args)
{
System.out.println("Hello from Java!".toLowerCase());
System.out.println("Hello from Java!".toUpperCase());
}
}

Output:

hello from java!
HELLO FROM JAVA!

Topñ

Formatting Numbers in Strings:

You can format numbers in strings using the Number-Format class of the java.text package. This class supports the format, set-Minimum-Integer-Digits, Set-Minimum-Fraction-Digits, Set-Maximum-Integer-Digits and Set-Maximum-Fraction-Digits method.

Ex. Using the set-Maximum-Fraction-Digits method, in which I round off a double value as I format it.

import java.text.*;
public class app
{
public static void main(String[] args)
{
double value=1.23456789;
NumberFormat nf=NumberFormat.getNumberInstance();
nf.setMaximumFractionDigits(6);
String s=nf.format(value);
System.out.println(s);
}
}

Output:

1.234568

Topñ

Creating StringBuffers:

Ex. here's how to create an empty StringBuffer object and then insert some text into it.

public class app
{
public static void main(String[] args)
{
StringBuffer s1=new StringBuffer();
s1.insert(0,"Hello from Java!");
System.out.println(s1);

StringBuffer s2=new StringBuffer("Hello from Java!");
System.out.println(s2);

StringBuffer s3=new StringBuffer(10);
s3.insert(0,"Hello from Java!");
System.out.println(s3);
}
}

Output:

Hello from Java!
Hello from Java!
Hello from Java!

Topñ

Getting and Setting StringBuffer Lengths and Capacities:

You can use the StringBuffer class's length method to find the lengths of the text in StringBuffer objects and you can use the capacity method to find the amount of memory space allocated for that text. You can also set the length of the text in a StringBuffer object with the setLength method, which lets you truncate strings or extend them with null characters.

Ex.

public class app
{
public static void main(String[] args)
{
StringBuffer s1=new StringBuffer("Hello from Java!");

System.out.println("The length is "+ s1.length());

System.out.println("The allocated length is "+ s1.capacity());

s1.setLength(2000);

System.out.println("The new length is "+ s1.length());
}
}

Output:

The length is 16
The allocated length is 32
The new length is 2000

Topñ

Setting Character in StringBuffers:

You can set individual characters in strings using the setCharAt.

Ex.

public class app
{
public static void main(String[] args)
{
StringBuffer s1=new StringBuffer("She had a wild look in her eyes.");
s1.setCharAt(10,'m');
System.out.println(s1);
}
}

Output:

She had a mild look in her eyes.

Topñ

Appending and Inserting using StringBuffer:

You can use the append method to append strings to the text in a StringBuffer object and you can ue insert method to insert text at a particular location.

Ex. In that example starts with the text "Hello", appends "Java!" and then inserts "from" into the middle of the text using append and insert.

public class app
{
public static void main(String[] args)
{
StringBuffer s1=new StringBuffer("Hello");
s1.append(" Java!");
System.out.println(s1);
s1.insert(6,"from ");
System.out.println(s1);
}
}

Output:

Hello Java!
Hello from Java!

Topñ

Deleting Text in StringBuffer:

You can delete text in a StringBuffer object using the delete and deleteCharAt methods.

Ex.

public class app
{
public static void main(String[] args)
{
StringBuffer s1=new StringBuffer("I'm not having a good time.");
s1.delete(4,8);
System.out.println(s1);
}
}

Output:

I'm having a good time.

Topñ

Replacing Text in StringBuffers:

Ex. we're using the StringBuffer class's replace method to change the contents of a StringBuffer object from "Hello from Java!" to "Hello to Java!".

public class app
{
public static void main(String[] args)
{
StringBuffer s1=new StringBuffer("Hello from Java!");
s1.replace(6,10,"to");
System.out.println(s1);
}
}

Output:

Hello from Java!

Topñ

String class constructor summary:

Constructor Means
String() Initialize a new String object so that holds an empty character sequence.
String( byte[] bytes)
String( byte[] ascii, int hibyte)
String()
String()
String()
String()
String()
String()

How do you run Java application

1. First take the copy of Java in c: directory. Let the directory name is "Jdk1.3". The main files stored in bin is sub directory of Jdk1.3.

2. Click on Start > Run. Type cmd and click Ok bottom. It will open the Command Prompt of windows.

3. Type edit AUTOEXEC.BAT on Command Prompt.

4. Add a new line in the autoexec.bat file, such as, PATH=%PATH%;C:\jdk1.3\bin;I:\jdk1.3\myproject; myproject is a directory where all java programs stored. Save and close the file. Restart the computer to set the PATH.

5. Type Cd c:\jdk1.3\myproject.

6. Type javac to get help information.

7. Type javac app.java command to compile you program.

8. Type Java app command to run you program.

Note: The file name of Java program must be had .java extension.

app.java file:

public class app
{
public static void main(String[] args)
{
System.out.println("Hello from JAVA!");
}
}

Basic Skill: Finding Java classes with CLASSPATH:

You can set the CLASSPATH environment variable to include that directory. By default, there are no paths or directories in CLASSPATH , but you can add a semicolon - separated list to CLASSPATH like this one for windows.

C:\> SET CLASSPATH=c:\classes;c:\newclasses;%CLASSPATH %

Now the java compiler (and other java tools) will know enough to search c:\classes and c:\newclasses automatically. That means that this code will now work if printer.class (own class) is in c:\classes, because that directory is in CLASSPATH.

Note: CLASSPATH is very important while we compile java program. Remember after compiling a written program in java it creates a .class file which must be stored in that directory which set at CLASSPATH.

Essential Java

Primary discussion about Creating An Java Application:

Here's a sample Java application that I'll develop over the next few sections, all the way through the compiling and running stages.

public class app
{
public static void main(String[] args)
{
System.out.println("Hello from JAVA!");
}
}

Output: Here's how it looks in a DOS window under windows:

C:\java app

Hello from JAVA!

Topñ

public class app:

Here's the first line in app.java,

public class app
{
....
....
}

=> This line indicates that we're creating a new java class named app.

Note: The keyword public in the preceding code. This keyword is an access specifier. Which you'll learn more about in later. The public access specified indicates that this class is available anywhere in a progress that makes use of it.

Note: If you make a class public, Java insists that you name the file after it. That is, you can only have one public class in a Java file. The reason for this is that the Java compiler will translate the .java file into a byte code file with the extension ".class", which means that app.java will be translated into app.class and if the JVM needs the app class, it'll know to look in the app.class file.

Note: Java always encloses block of code within curly braces - that is "{" and "}".

Topñ

public static void main(String[] args):

public class app
{
public static void main(String[] args)
{
....
....
}
}

=> main is a class method not an object method. It must not return a value when it's finished executing which is why we use the keyword void in this code (in other words, a return value of type void means that there actually is no return value). We are including that main is passed an array of string values called args. There stings values hold the values passed from the command line when you start the application for example java app Hello there, then "Hello" and "there" would be the two strings in the args array.

Topñ

System.out.println("Hello from JAVA!"):

public class app
{
public static void main(String[] args)
{
System.out.println("Hello from JAVA!");
}
}

=> The java.lang package's System class includes a field called out and this field, in turn, has a method named printin, which does the actual displaying of text.

Topñ

Basic Knowledge about Commenting in Java:

Java supports three types of comments.

1st type: You can surround a comment of any length with the characters /* and */.

/* This application prints out "Hello from JAVA!" */
public class app
{
public static void main(String[] args)
{
System.out.println("Hello from JAVA!");
}
}

=> The java compiler will ignore all the text between the /* and */ markers. You can split comments between this markers across multiple lines, such as,

/* This application prints out "Hello from JAVA!"
Created by: G. Whiz, 1/1/00 */
public class app
{
public static void main(String[] args)
{
System.out.println("Hello from JAVA!");
}
}

2nd type: Java also supports a one-line comment, using a double slash, //.

public class app // Create the app class
{
public static void main(String[] args)
{
// Print out the message
System.out.println("Hello from JAVA!");
}
}

3rd type: Finally, java also supports a documentation comment, which starts with /** and ends with */. This comment is designed to be used with the javadoc tool, which can automatically.

/** This application prints out "Hello from JAVA!" */
public class app
{
public static void main(String[] args)
{
System.out.println("Hello from JAVA!");
}
}

Topñ

Importing Java Packages And Classes:

The classes that Sun has created for you to use are stored in class libraries called packages. To make a class in a package available to your code. You have to import the package, which means the compiler will search that package for classes. You can also import individual classes that are not part of a package. By default, only the basic java statement are available to you in an application - that is, the ones in the core java.lang java package. The compiler automatically imports the java.lang package for you, but to use the rest of the classes that come with java, you'll have to do your own importing with the import statement. Here's how you use that statement.

Syntax:

Import[Package1 [.package2. . . .]](.class|*)

The stander java packages, themselves are stored in a large package called java. If you're going to use import statement to import classes into a program, the import statements should be at the top of the code.

import java.util.date;
public class app
{
public static void main(String[] args)
{
System.out.println("Today = "+ new Date());
}
}

There's also a shorthand technique that loads in all the classes in a package - you can use an asterisk (*) as a wildcard to stand for all classes in a particular package.

import java.util.*;
public class app
{
........
........
}

To import your own classes you should follow the process which given as example in below.

Suppose you have a classes named printer in a file named printer.java and that class has one method named print.

public class printer
{
public void print()
{
System.out.println(" Hello from Java! ");
}
}

Now, you might want to make use of the print method in other classes as in this case where we're creating a new object of the printer class using new operator and using that object's print method in a application named app.

import printer;
public class app
{
public static void main(String[] args)
{
(new printer()).print();
}
}

=> You can import the printer class (Own class) this way.

Topñ

Creating Applets:

Standard applets are built on the Applet class which is in the java.applet package. The java.applet.Applet class is the class that forms the base for standard applets and you can derive your own applet classes from this class using the extend keyword.

import java.applet.Applet;
public class applet extends Applet
{
.......
.......
}

Applets don't have a main method like applications do - in fact, that's the primary code difference between applets and applications.

import java.applet.Applet;
import java.awt.*;
public class applet extends Applet
{
public void paint(Graphics g)
{
g.drawString("Hello from Java!",60,100)
}
}

=> The paint method is passed a java object of the Graphics class (this object is named g in the code). You can use this object's drawString method to actually draw the text. In this case, we'll draw the text "Hello from Java!" at location (60, 100) in the applet. Now you can compile applet.java to applet.class.

Topñ

Running Applets:

To display an applet, we can use a web page with an HTML tag in it. For now, here's a Web Page, applet.html, that will display the applet.



Applet











=> You can open this applet Web Page in a Web browser or you can also use the sun appletviewer, which comes with java to open applet.html.

C:\> appletviewer applet.html

Topñ

Creating Windowed Applications:

Creating a windowed application is much like creating an applet, except that you have to have a main method and you're responsible for creating tha window yourself. To create the window for the application, we'll derive a new class form AWT Frame class.

Now we'll create the application class itself, which we'll name app. This is the class that will have a main method and we'll use the new operator to create a new object of the AppFrame class.

import java.awt.*;
import java.awt.event.*;
class AppFrame extends Frame
{
public void paint(Graphics g)
{
g.drawString("Hello from Java=",60,100);
}
}

public class app1
{
public static void main(String[] args)
{
AppFrame f=(new AppFrame());
f.setSize(200,200);
f.addwindowListener(new WindowAdapter(){public void windowClosing(WindowEvent e){System.exit(0);}});
f.show();
}
}

Topñ

Running Windowed Applications:

To run a windowed application, you can use the java and javaw tools after compiling the program.

C:\> java app

C:\> javaw app

=> The java tool launches the application and makes the console window wait until the application is dismissed, whereas the javaw launches the application and doesn't wait until the application is dismissed.