eramarswami.com

amar swami


Leave a comment

String and operation on String in java

Strings, which are widely used in Java programming, are a sequence of characters. In the Java programming language, strings are objects.

The Java platform provides the String class to create and manipulate strings.

Creating Strings:

The most direct way to create a string is to write:

String greeting = “Hello world!”;
Whenever it encounters a string literal in your code, the compiler creates a String object with its value in this case, “Hello world!’.

As with any other object, you can create String objects by using the new keyword and a constructor. The String class has eleven constructors that allow you to provide the initial value of the string using different sources, such as an array of characters.

public class StringDemo{

public static void main(String args[]){
char[] helloArray = { ‘h’, ‘e’, ‘l’, ‘l’, ‘o’, ‘.’};
String helloString = new String(helloArray);
System.out.println( helloString );
}
}
This would produce the following result:

hello.

Note: The String class is immutable, so that once it is created a String object cannot be changed. If there is a necessity to make a lot of modifications to Strings of characters, then you should use String Buffer & String Builder Classes.

String Length:

Methods used to obtain information about an object are known as accessor methods. One accessor method that you can use with strings is the length() method, which returns the number of characters contained in the string object.

After the following two lines of code have been executed, len equals 17:

public class StringDemo {

public static void main(String args[]) {
String palindrome = “Dot saw I was Tod”;
int len = palindrome.length();
System.out.println( “String Length is : ” + len );
}
}
This would produce the following result:

String Length is : 17

Concatenating Strings:
The String class includes a method for concatenating two strings:

string1.concat(string2);
This returns a new string that is string1 with string2 added to it at the end. You can also use the concat() method with string literals, as in:

“My name is “.concat(“Zara”);
Strings are more commonly concatenated with the + operator, as in:

“Hello,” + ” world” + “!”
which results in:

“Hello, world!”
Let us look at the following example:

public class StringDemo {

public static void main(String args[]) {
String string1 = “saw I was “;
System.out.println(“Dot ” + string1 + “Tod”);
}
}
This would produce the following result:

Dot saw I was Tod


Creating Format Strings:

You have printf() and format() methods to print output with formatted numbers. The String class has an equivalent class method, format(), that returns a String object rather than a PrintStream object.

Using String’s static format() method allows you to create a formatted string that you can reuse, as opposed to a one-time print statement. For example, instead of:

System.out.printf(“The value of the float variable is ” +
“%f, while the value of the integer ” +
“variable is %d, and the string ” +
“is %s”, floatVar, intVar, stringVar);

you can write:

String fs;
fs = String.format(“The value of the float variable is ” +
“%f, while the value of the integer ” +
“variable is %d, and the string ” +
“is %s”, floatVar, intVar, stringVar);
System.out.println(fs);

ARRAY

Java provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.

Instead of declaring individual variables, such as number0, number1, …, and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and …, numbers[99] to represent individual variables.

This tutorial introduces how to declare array variables, create arrays, and process arrays using indexed variables.

Declaring Array Variables:

To use an array in a program, you must declare a variable to reference the array, and you must specify the type of array the variable can reference. Here is the syntax for declaring an array variable:

dataType[] arrayRefVar; // preferred way.

or

dataType arrayRefVar[]; // works but not preferred way.
Note: The style dataType[] arrayRefVar is preferred. The style dataType arrayRefVar[] comes from the C/C++ language and was adopted in Java to accommodate C/C++ programmers.

Example:

The following code snippets are examples of this syntax:

double[] myList; // preferred way.

or

double myList[]; // works but not preferred way.

Creating Arrays:

You can create an array by using the new operator with the following syntax:

arrayRefVar = new dataType[arraySize];
The above statement does two things:

It creates an array using new dataType[arraySize];

It assigns the reference of the newly created array to the variable arrayRefVar.

Declaring an array variable, creating an array, and assigning the reference of the array to the variable can be combined in one statement, as shown below:

dataType[] arrayRefVar = new dataType[arraySize];
Alternatively you can create arrays as follows:

dataType[] arrayRefVar = {value0, value1, …, valuek};
The array elements are accessed through the index. Array indices are 0-based; that is, they start from 0 to arrayRefVar.length-1.

Example:

Following statement declares an array variable, myList, creates an array of 10 elements of double type and assigns its reference to myList:

double[] myList = new double[10];
Following picture represents array myList. Here, myList holds ten double values and the indices are from 0 to 9

array
Processing Arrays:

When processing array elements, we often use either for loop or foreach loop because all of the elements in an array are of the same type and the size of the array is known.

Example:

Here is a complete example of showing how to create, initialize and process arrays:

public class TestArray {

public static void main(String[] args) {
double[] myList = {1.9, 2.9, 3.4, 3.5};

// Print all the array elements
for (int i = 0; i < myList.length; i++) {
System.out.println(myList[i] + ” “);
}
// Summing all elements
double total = 0;
for (int i = 0; i < myList.length; i++) {
total += myList[i];
}
System.out.println(“Total is ” + total);
// Finding the largest element
double max = myList[0];
for (int i = 1; i < myList.length; i++) { if (myList[i] > max) max = myList[i];
}
System.out.println(“Max is ” + max);
}
}
This would produce the following result:

1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5

The foreach Loops:

JDK 1.5 introduced a new for loop known as foreach loop or enhanced for loop, which enables you to traverse the complete array sequentially without using an index variable.

Example:

The following code displays all the elements in the array myList:

public class TestArray {

public static void main(String[] args) {
double[] myList = {1.9, 2.9, 3.4, 3.5};

// Print all the array elements
for (double element: myList) {
System.out.println(element);
}
}
}
This would produce the following result:

1.9
2.9
3.4
3.5

Passing Arrays to Methods:

Just as you can pass primitive type values to methods, you can also pass arrays to methods. For example, the following method displays the elements in an int array:

public static void printArray(int[] array) {
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + ” “);
}
}
You can invoke it by passing an array. For example, the following statement invokes the printArray method to display 3, 1, 2, 6, 4, and 2:

printArray(new int[]{3, 1, 2, 6, 4, 2});

Returning an Array from a Method:

A method may also return an array. For example, the method shown below returns an array that is the reversal of another array:

public static int[] reverse(int[] list) {
int[] result = new int[list.length];

for (int i = 0, j = result.length – 1; i < list.length; i++, j–) {
result[j] = list[i];
}
return result;
}

Date Function and use
Getting Current Date & Time:

This is very easy to get current date and time in Java. You can use a simple Date object with toString() method to print current date and time as follows:

import java.util.Date;

public class DateDemo {
public static void main(String args[]) {
// Instantiate a Date object
Date date = new Date();

// display time and date using toString()
System.out.println(date.toString());
}
}
This would produce the following result:

Mon May 04 09:51:52 CDT 2009

Date Comparison:

There are following three ways to compare two dates:

You can use getTime( ) to obtain the number of milliseconds that have elapsed since midnight, January 1, 1970, for both objects and then compare these two values.

You can use the methods before( ), after( ), and equals( ). Because the 12th of the month comes before the 18th, for example, new Date(99, 2, 12).before(new Date (99, 2, 18)) returns true.

You can use the compareTo( ) method, which is defined by the Comparable interface and implemented by Date.

Date Formatting using SimpleDateFormat:

SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner. SimpleDateFormat allows you to start by choosing any user-defined patterns for date-time formatting. For example:

import java.util.*;
import java.text.*;

public class DateDemo {
public static void main(String args[]) {

Date dNow = new Date( );
SimpleDateFormat ft =
new SimpleDateFormat (“E yyyy.MM.dd ‘at’ hh:mm:ss a zzz”);

System.out.println(“Current Date: ” + ft.format(dNow));
}
}
This would produce the following result:
Current Date: Sun 2004.07.18 at 04:14:09 PM PDT


Leave a comment >

There are two types of decision making statements in Java. They are:

if statements

switch statements

The if Statement:

An if statement consists of a Boolean expression followed by one or more statements.

Syntax:
The syntax of an if statement is:

if(Boolean_expression)
{
//Statements will execute if the Boolean expression is true
}
If the Boolean expression evaluates to true then the block of code inside the if statement will be executed. If not the first set of code after the end of the if statement (after the closing curly brace) will be executed.

Example:

public class Test {

public static void main(String args[]){
int x = 10;

if( x < 20 ){
System.out.print(“This is if statement”);
}
}
}
This would produce the following result:

This is if statement
The if…else Statement:

An if statement can be followed by an optional else statement, which executes when the Boolean expression is false.

Syntax:
The syntax of an if…else is:

if(Boolean_expression){
//Executes when the Boolean expression is true
}else{
//Executes when the Boolean expression is false
}
Example:
public class Test {

public static void main(String args[]){
int x = 30;

if( x < 20 ){
System.out.print(“This is if statement”);
}else{
System.out.print(“This is else statement”);
}
}
}
This would produce the following result:

This is else statement
The if…else if…else Statement:
An if statement can be followed by an optional else if…else statement, which is very useful to test various conditions using single if…else if statement.

When using if , else if , else statements there are few points to keep in mind.

An if can have zero or one else’s and it must come after any else if’s.

An if can have zero to many else if’s and they must come before the else.

Once an else if succeeds, none of the remaining else if’s or else’s will be tested.

Syntax:
The syntax of an if…else is:

if(Boolean_expression 1){
//Executes when the Boolean expression 1 is true
}else if(Boolean_expression 2){
//Executes when the Boolean expression 2 is true
}else if(Boolean_expression 3){
//Executes when the Boolean expression 3 is true
}else {
//Executes when the none of the above condition is true.
}

Example:

public class Test {

public static void main(String args[]){
int x = 30;

if( x == 10 ){
System.out.print(“Value of X is 10”);
}else if( x == 20 ){
System.out.print(“Value of X is 20”);
}else if( x == 30 ){
System.out.print(“Value of X is 30”);
}else{
System.out.print(“This is else statement”);
}
}
}
This would produce the following result:

Value of X is 30
Nested if…else Statement:

It is always legal to nest if-else statements which means you can use one if or else if statement inside another if or else if statement.

Syntax:
The syntax for a nested if…else is as follows:

if(Boolean_expression 1){
//Executes when the Boolean expression 1 is true
if(Boolean_expression 2){
//Executes when the Boolean expression 2 is true
}
}
You can nest else if…else in the similar way as we have nested if statement.

Example:

public class Test {

public static void main(String args[]){
int x = 30;
int y = 10;

if( x == 30 ){
if( y == 10 ){
System.out.print(“X = 30 and Y = 10”);
}
}
}
}
This would produce the following result:

X = 30 and Y = 10
The switch Statement:
A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each case.

Syntax:
The syntax of enhanced for loop is:

switch(expression){
case value :
//Statements
break; //optional
case value :
//Statements
break; //optional
//You can have any number of case statements.
default : //Optional
//Statements
}
The following rules apply to a switch statement:

The variable used in a switch statement can only be a byte, short, int, or char.

You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon.

The value for a case must be the same data type as the variable in the switch and it must be a constant or a literal.

When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached.

When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement.

Not every case needs to contain a break. If no break appears, the flow of control will fall through to subsequent cases until a break is reached.

A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case.

Example:

public class Test {

public static void main(String args[]){
//char grade = args[0].charAt(0);
char grade = ‘C’;

switch(grade)
{
case ‘A’ :
System.out.println(“Excellent!”);
break;
case ‘B’ :
case ‘C’ :
System.out.println(“Well done”);
break;
case ‘D’ :
System.out.println(“You passed”);
case ‘F’ :
System.out.println(“Better try again”);
break;
default :
System.out.println(“Invalid grade”);
}
System.out.println(“Your grade is ” + grade);
}
}
Compile and run above program using various command line arguments. This would produce the following result:

$ java Test
Well done
Your grade is a C
$

loops in java

Leave a comment

There may be a situation when we need to execute a block of code several number of times, and is often referred to as a loop.

Java has very flexible three looping mechanisms. You can use one of the following three loops:

1.while Loop

2.do…while Loop

3.for Loop

As of Java 5, the enhanced for loop was introduced. This is mainly used for Arrays.

The while Loop:

A while loop is a control structure that allows you to repeat a task a certain number of times.

Syntax:
The syntax of a while loop is:

while(Boolean_expression)
{
//Statements
}
When executing, if the boolean_expression result is true, then the actions inside the loop will be executed. This will continue as long as the expression result is true.

Here, key point of the while loop is that the loop might not ever run. When the expression is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed.

Example:

public class Test {

public static void main(String args[]) {
int x = 10;

while( x < 20 ) {
System.out.print(“value of x : ” + x );
x++;
System.out.print(“\n”);
}
}
}
This would produce the following result:

value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19

The do…while Loop:

A do…while loop is similar to a while loop, except that a do…while loop is guaranteed to execute at least one time.

Syntax:

The syntax of a do…while loop is:

do
{
//Statements
}while(Boolean_expression);
Notice that the Boolean expression appears at the end of the loop, so the statements in the loop execute once before the Boolean is tested.

If the Boolean expression is true, the flow of control jumps back up to do, and the statements in the loop execute again. This process repeats until the Boolean expression is false.

Example:

public class Test {

public static void main(String args[]){
int x = 10;

do{
System.out.print(“value of x : ” + x );
x++;
System.out.print(“\n”);
}while( x < 20 );
}
}
This would produce the following result:

value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19

The for Loop:

A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.

A for loop is useful when you know how many times a task is to be repeated.

Syntax:

The syntax of a for loop is:

for(initialization; Boolean_expression; update)
{
//Statements
}
Here is the flow of control in a for loop:

The initialization step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears.

Next, the Boolean expression is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement past the for loop.

After the body of the for loop executes, the flow of control jumps back up to the update statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the Boolean expression.

The Boolean expression is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then update step, then Boolean expression). After the Boolean expression is false, the for loop terminates.

Example:

public class Test {

public static void main(String args[]) {

for(int x = 10; x < 20; x = x+1) {
System.out.print(“value of x : ” + x );
System.out.print(“\n”);
}
}
}
This would produce the following result:

value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19

Enhanced for loop in Java:

As of Java 5, the enhanced for loop was introduced. This is mainly used for Arrays.

Syntax:
The syntax of enhanced for loop is:

for(declaration : expression)
{
//Statements
}
Declaration: The newly declared block variable, which is of a type compatible with the elements of the array you are accessing. The variable will be available within the for block and its value would be the same as the current array element.

Expression: This evaluates to the array you need to loop through. The expression can be an array variable or method call that returns an array.

Example:

public class Test {

public static void main(String args[]){
int [] numbers = {10, 20, 30, 40, 50};

for(int x : numbers ){
System.out.print( x );
System.out.print(“,”);
}
System.out.print(“\n”);
String [] names ={“James”, “Larry”, “Tom”, “Lacy”};
for( String name : names ) {
System.out.print( name );
System.out.print(“,”);
}
}
}
This would produce the following result:

10,20,30,40,50,
James,Larry,Tom,Lacy,

The break Keyword:

The break keyword is used to stop the entire loop. The break keyword must be used inside any loop or a switch statement.

The break keyword will stop the execution of the innermost loop and start executing the next line of code after the block.

Syntax:
The syntax of a break is a single statement inside any loop:

break;

Example:

public class Test {

public static void main(String args[]) {
int [] numbers = {10, 20, 30, 40, 50};

for(int x : numbers ) {
if( x == 30 ) {
break;
}
System.out.print( x );
System.out.print(“\n”);
}
}
}
This would produce the following result:

10
20

The continue Keyword:

The continue keyword can be used in any of the loop control structures. It causes the loop to immediately jump to the next iteration of the loop.

In a for loop, the continue keyword causes flow of control to immediately jump to the update statement.

In a while loop or do/while loop, flow of control immediately jumps to the Boolean expression.

Syntax:
The syntax of a continue is a single statement inside any loop:

continue;
Example:
public class Test {

public static void main(String args[]) {
int [] numbers = {10, 20, 30, 40, 50};

for(int x : numbers ) {
if( x == 30 ) {
continue;
}
System.out.print( x );
System.out.print(“\n”);
}
}
}
This would produce the following result:

10
20
40
50


Leave a comment >

Useful Programs:

1) Program of factorial number.

class Operation{

static int fact(int number){
int f=1;
for(int i=1;i<=number;i++){
f=f*i;
}
return f;
}

public static void main(String args[]){
int result=fact(5);
System.out.println(“Factorial of 5=”+result);
}
}

2) Program of fibonacci series.

class Fabnoci{

public static void main(String[] args)
{
int n=10,i,f0=1,f1=1,f2=0;
for(i=1;i<=n;i++)
{
f2=f0+f1;
f0=f1;
f1=f2;
f2=f0;
System.out.println(f2);
}

}
}

3) Program of armstrong number.

class ArmStrong{
public static void main(String…args)
{
int n=153,c=0,a,d;
d=n;
while(n>0)
{
a=n%10;
n=n/10;
c=c+(a*a*a);
}
if(d==c)
System.out.println(“armstrong number”);
else
System.out.println(“it is not an armstrong number”);

}
}

Bitwise operator

public class Test {

public static void main(String args[]) {
int a = 60; /* 60 = 0011 1100 */
int b = 13; /* 13 = 0000 1101 */
int c = 0;

c = a & b; /* 12 = 0000 1100 */
System.out.println(“a & b = ” + c );

c = a | b; /* 61 = 0011 1101 */
System.out.println(“a | b = ” + c );

c = a ^ b; /* 49 = 0011 0001 */
System.out.println(“a ^ b = ” + c );

c = ~a; /*-61 = 1100 0011 */
System.out.println(“~a = ” + c );

c = a << 2; /* 240 = 1111 0000 */
System.out.println(“a << 2 = ” + c ); c = a >> 2; /* 215 = 1111 */
System.out.println(“a >> 2 = ” + c );

c = a >>> 2; /* 215 = 0000 1111 */
System.out.println(“a >>> 2 = ” + c );
}
}

program on logical operator

public class Test {

public static void main(String args[]) {
boolean a = true;
boolean b = false;

System.out.println(“a && b = ” + (a&&b));

System.out.println(“a || b = ” + (a||b) );

System.out.println(“!(a && b) = ” + !(a && b));
}
}


Leave a comment

how to compile and run a java program

Understanding first java program

Let’s see what is the meaning of class, public, static, void, main, String[], System.out.println().

  • class keyword is used to declare a class in java.
  • public keyword is an access modifier which represents visibility, it means it is visible to all.
  • static is a keyword, if we declare any method as static, it is known as static method. The core advantage of static method is that there is no need to create object to invoke the static method. The main method is executed by the JVM, so it doesn’t require to create object to invoke the main method. So it saves memory.
  • void is the return type of the method, it means it doesn’t return any value.
  • main represents startup of the program.
  • String[] args is used for command line argument. We will learn it later.
  • System.out.println() is used print statement. We will learn about the internal working of System.out.println statement later.

To write the simple program, open notepad by start menu -> All Programs -> Accessories -> notepad and write simple program as displayed below:

javaprogramcompile

As displayed in the above diagram, write the simple program of java in notepad and saved it as Simple.java. To compile and run this program, you need to open command prompt by start menu -> All Programs -> Accessories -> command prompt.

javacompile

To compile and run the above program, go to your current directory first; my current directory is c:\new . Write here:
To compile: javac Simple.java
To execute: java Simple

Internal Details of Hello Java Program

In the previous page, we have learned about the first program, how to compile and how to run the first java program. Here, we are going to learn, what happens while compiling and running the java program. Moreover, we will see some question based on the first program.

What happens at compile time?

At compile time, java file is compiled by Java Compiler (It does not interact with OS) and converts the java code into bytecode

javaprogramcompile
What happens at runtime?

At runtime, following steps are performed:

program of java

Classloader: is the subsystem of JVM that is used to load class files.
Bytecode Verifier: checks the code fragments for illegal code that can violate access right to objects.
Interpreter: read bytecode stream then execute the instructions.

JVM (Java Virtual Machine)

JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime environment in which java bytecode can be executed.

JVMs are available for many hardware and software platforms (i.e.JVM is plateform dependent).

What is JVM?

It is:

A specification where working of Java Virtual Machine is specified. But implementation provider is independent to choose the algorithm. Its implementation has been provided by Sun and other companies.
An implementation Its implementation is known as JRE (Java Runtime Environment).
Runtime Instance Whenever you write java command on the command prompt to run the java class, and instance of JVM is created.

What it does?

  1. A specification where working of Java Virtual Machine is specified. But implementation provider is independent to choose the algorithm. Its implementation has been provided by Sun and other companies.
  2. An implementation Its implementation is known as JRE (Java Runtime Environment).
  3. Runtime Instance Whenever you write java command on the command prompt to run the java class, and instance of JVM is created.

What it does?

The JVM performs following operation:

  • Loads code
  • Verifies code
  • Executes code
  • Provides runtime environment

JVM provides definitions for the:

  • Memory area
  • Class file format
  • Register set
  • Garbage-collected heap
  • Fatal error reporting etc.

Internal Architecture of JVM

Let’s understand the internal architecture of JVM. It contains classloader, memory area, execution engine etc.

jjj

1) Classloader:

Classloader is a subsystem of JVM that is used to load class files.

 

2) Class(Method) Area:

Class(Method) Area stores per-class structures such as the runtime constant pool, field and method data, the code for methods.

 

3) Heap:

It is the runtime data area in which objects are allocated.

 

4) Stack:

Java Stack stores frames.It holds local variables and partial results, and plays a part in method invocation and return.
Each thread has a private JVM stack, created at the same time as thread.
A new frame is created each time a method is invoked. A frame is destroyed when its method invocation completes.

 

5) Program Counter Register:

PC (program counter) register. It contains the address of the Java virtual machine instruction currently being executed.

 

6) Native Method Stack:

It contains all the native methods used in the application.

 

7) Execution Engine:

It contains:
1) A virtual processor
2) Interpreter:Read bytecode stream then execute the instructions.
3) Just-In-Time(JIT) compiler:It is used to improve the performance.JIT compiles parts of the byte code that have similar functionality at the same time, and hence reduces the amount of time needed for compilation.Here the term ?compiler? refers to a translator from the instruction set of a Java virtual machine (JVM) to the instruction set of a specific CPU.


Leave a comment

java class,variable declaration

Declaring Classes

You’ve seen classes defined in the following way:

class MyClass {
// field, constructor, and
// method declarations
}
This is a class declaration. The class body (the area between the braces) contains all the code that provides for the life cycle of the objects created from the class: constructors for initializing new objects, declarations for the fields that provide the state of the class and its objects, and methods to implement the behavior of the class and its objects.

The preceding class declaration is a minimal one. It contains only those components of a class declaration that are required. You can provide more information about the class, such as the name of its superclass, whether it implements any interfaces, and so on, at the start of the class declaration. For example,

class MyClass extends MySuperClass implements YourInterface {
// field, constructor, and
// method declarations
}
means that MyClass is a subclass of MySuperClass and that it implements the YourInterface interface.

You can also add modifiers like public or private at the very beginning—so you can see that the opening line of a class declaration can become quite complicated. The modifiers public and private, which determine what other classes can access MyClass, are discussed later in this lesson. The lesson on interfaces and inheritance will explain how and why you would use the extends and implements keywords in a class declaration. For the moment you do not need to worry about these extra complications.

In general, class declarations can include these components, in order:

Modifiers such as public, private, and a number of others that you will encounter later.
The class name, with the initial letter capitalized by convention.
The name of the class’s parent (superclass), if any, preceded by the keyword extends. A class can only extend (subclass) one parent.
A comma-separated list of interfaces implemented by the class, if any, preceded by the keyword implements. A class can implement more than one interface.
The class body, surrounded by braces, {}.

Declaring Member Variables

There are several kinds of variables:

Member variables in a class—these are called fields.
Variables in a method or block of code—these are called local variables.
Variables in method declarations—these are called parameters.
The Bicycle class uses the following lines of code to define its fields:

public int cadence;
public int gear;
public int speed;
Field declarations are composed of three components, in order:

Zero or more modifiers, such as public or private.
The field’s type.
The field’s name.
The fields of Bicycle are named cadence, gear, and speed and are all of data type integer (int). The public keyword identifies these fields as public members, accessible by any object that can access the class.

Access Modifiers

The fi Continue reading


Leave a comment

Basic Rules and variables of java language

Basic Syntax:

About Java programs, it is very important to keep in mind the following points.
 Case Sensitivity – Java is case sensitive, which means identifier Hello and hello would have different meaning in Java.
 Class Names – For all class names, the first letter should be in Upper Case. If several words are used to form a name of the class, each inner word’s first letter should be in Upper Case. Example class MyFirstJavaClass
 Method Names – All method names should start with a Lower Case letter. If several words are used to form the name of the method, then each inner word’s first letter should be in Upper Case. Example public void myMethodName()
 Program File Name – Name of the program file should exactly match the class name. When saving the file, you should save it using the class name (Remember Java is case sensitive) and append ‘.java’ to the end of the name (if the file name and the class name do not match your program will not compile). Example : Assume ‘MyFirstJavaProgram’ is the class name, then the file should be saved as’MyFirstJavaProgram.java’
 public static void main(String args[]) – Java program processing starts from the main() method, which is a mandatory part of every Java program.

Java Identifiers:

All Java components require names. Names used for classes, variables and methods are called identifiers.
In Java, there are several points to remember about identifiers. They are as follows:
 All identifiers should begin with a letter (A to Z or a to z), currency character ($) or an underscore (_).
 After the first character, identifiers can have any combination of characters.
 A keyword cannot be used as an identifier.  Most importantly identifiers are case sensitive.
 Examples of legal identifiers:age, $salary, _value, __1_value  Examples of illegal identifiers: 123abc, -salary

Java Modifiers:

Like other languages, it is possible to modify classes, methods, etc., by using modifiers.
There are two categories of modifiers:
 Access Modifiers: default, public, protected, private
 Non-access Modifiers: final, abstract, strictfp

Java Variables:

We would see following type of variables in Java:
 Local Variables
 Class Variables (Static Variables)
 Instance Variables (Non-static variables)

Java Arrays:

Arrays are objects that store multiple variables of the same type. However, an array itself is an object on the heap. We will look into how to declare, construct and initialize in the upcoming chapters.

Java Enums:

Enums were introduced in java 5.0. Enums restrict a variable to have one of only a few predefined values. The values in this enumerated list are called enums. With the use of enums, it is possible to reduce the number of bugs in your code. For example, if we consider an application for a fresh juice shop, it would be possible to restrict the glass size to small, medium and large. This would make sure that it would not allow anyone to order any size other than the small, medium or large.

Example:

Class FreshJuice{
enum FreshJuiceSize{ SMALL, MEDUIM, LARGE }
FreshJuiceSize size; }
public class FreshJuiceTest{
public static void main(String args[]){
FreshJuice juice =new FreshJuice();
juice.size =FreshJuice.FreshJuiceSize.MEDUIM ;
}
}

Note: enums can be declared as their own or inside a class. Methods, variables, constructors can be defined inside enums as well.