Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts
Java Control Statement
Java Control statements control the order of execution in a java program, based on data values and conditional logic. There are three main categories of control flow statements;
- Selection statements: if, if-else and switch.
- Iteration statements: while, do-while and for.
- Transfer statements: break, continue, return, try-catch-finally and assert.
Selection Statements
The If Statement
The if statement executes a block of code only if the specified expression is true. If the value is false, then the if block is skipped and execution continues with the rest of the program. You can either have a single statement or a block of code within an if statement. Note that the conditional expression must be a Boolean expression.
The simple if statement has the following syntax:
if (<conditional expression>)
{
<statement action>;
}
Below is an example that demonstrates conditional execution based on if statement condition.
public class IfStatementDemo { public static void main(String[] args) { int a = 10, b = 20; if (a > b) System.out.println("a > b"); if (a < b) System.out.println("b > a"); } }
Output: b > a
The If-else Statement
The if-else statement is an extension of the if statement. If the statements in the if statement fails, the statements in the else block are executed. You can either have a single statement or a block of code within if-else blocks. Note that the conditional expression must be a Boolean expression.
The if-else statement has the following syntax:
if (<conditional expression>)
{
<statement action>;
}
else
{
<statement action>;
}
Below is an example that demonstrates conditional execution based on if else statement condition.
public class IfElseStatementDemo { public static void main(String[] args) { int a = 10, b = 20; if (a > b) { System.out.println("a > b"); } else { System.out.println("b > a"); } } }
Output: b > a
Nesting of if-else Statements
When a series of decisions are involved, we may have to use more than one if-else statement in nested form. The general syntax for nested if else is as follows:
if(<Conditional Statements>)
{
if(<Conditional Statement>)
{
<Statement>;
}
else
{
<Statement>;
}
}
else
{
<Statement>;
}
Below is an example that demonstrates conditional execution based on if else statement condition.
public class IfElseStatementDemo { public static void main(String[] args) { int a = 10, b = 20, c = 30; if (a > b) { if (a > c) { System.out.println("a is greater"); } } else { if(b > c) { System.out.println("b is greater"); } else { System.out.println("c is greater"); } } } }
Output: c is greater
The Ladder if-else Statements
There is another way of putting if-else together when multi-path decisions are involved. A multipath decision is a chain of its in which the statement associated with each else is an if. It takes the following general form:
if(Condition)
{
<Statement>;
}
else if(Condition)
{
<statement>;
}
else if(Condition)
{
<Statement>;
}
else
{
<Statement>;
}
<Statement x>;
The Conditions are evaluated from top to bottom, as soon as the True condition is found, the Statement associated with it is executed and the control is transferred to the <Statement x>; (Skipping the rest of the Ladder) When all the condition becomes false, then the final else containing the default-statement will be executed.
Example:
class LadderIfElse { public static void main(String arg[]) { int marks = 85; char grade; if (marks >=90) { grade = 'A' ; } else if (marks >= 70) { grade = 'B' ; } else if (marks >= 50) { grade = 'C'; } else { grade = 'F' } System.out.print("Your Grade: " +grade); } }
The Ladder If-else gave birth to Switch Case Statement, Which is based on the working of Ladder if-else.
Switch Case Statement
The switch case statement, also called a case statement is a multi-way branch with several choices. A switch is easier to implement than a series of if/else statements. The switch statement begins with a keyword, followed by an expression that equates to a no long integral value. Following the controlling expression is a code block that contains zero or more labeled cases. Each label must equate to an integer constant and each must be unique. When the switch statement executes, it compares the value of the controlling expression to the values of each case label. The program will select the value of the case label that equals the value of the controlling expression and branch down that path to the end of the code block. If none of the case label values match, then none of the codes within the switch statement code block will be executed. Java includes a default label to use in cases where there are no matches. We can have a nested switch within a case block of an outer switch.
Its general form is as follows:
switch(<non-long integral expression>)
{
case label1: <statement1>
case label2: <statement2>
…
case labeln: <statementn>
default: <statement>
} // end switch
When executing a switch statement, the program falls through to the next case. Therefore, if you want to exit in the middle of the switch statement code block, you must insert a break statement, which causes the program to continue executing after the current code block.
Below is a java example that demonstrates conditional execution based on nested if else statement condition to find the greatest of 3 numbers.
public class SwitchCaseStatementDemo { public static void main(String[] args) { int a = 10, b = 20, c = 30; int status = -1; if(a > b && a > c) { status = 1; } else if (b > c) { status = 2; } else { status = 3; } switch(status) { case 1: System.out.println("a is the greatest"); break; case 2: System.out.println("b is the greatest"); break; case 3: System.out.println("c is the greatest"); break; default: System.out.println("Cannot be determined"); } } }
Output: c is the greatest
Iteration Statements
While Statement
The while statement is a looping construct control statement that executes a block of code while a condition is true. You can either have a single statement or a block of code within the while loop. The loop will never be executed if the testing expression evaluates to false. The loop condition must be a boolean expression.
The syntax of the while loop is
while (<loop condition>)
{
<statements>;
}
Below is an example that demonstrates the looping construct namely while loop used to print numbers from 1 to 10.
public class WhileLoopDemo { public static void main(String[] args) { int count = 1; System.out.println("Printing Numbers from 1 to 10"); while (count <= 10) { System.out.print(count++); System.out.print(","); if(count==10) { System.out.println("\b"); //backspace } } } }
Output:
Printing Numbers from 1 to 10
1,2,3,4,5,6,7,8,9,10
Do-while Loop Statement
The do-while loop is similar to the while loop, except that the test is performed at the end of the loop instead of at the beginning. This ensures that the loop will be executed at least once. A do-while loop begins with the keyword do, followed by the statements that make up the body of the loop. Finally, the keyword while and the test expression completes the do-while loop. When the loop condition becomes false, the loop is terminated and execution continues with the statement immediately following the loop. You can either have a single statement or a block of code within the do-while loop.
The syntax of the do-while loop is:
do
{
<loop body>
}
while (<loop condition>);
Below is an example that demonstrates the looping construct namely do-while loop used to print numbers from 1 to 10.
public class DoWhileLoopDemo { public static void main(String[] args) { int count = 1; System.out.println("Printing Numbers from 1 to 10"); do { System.out.print(count++); System.out.print(","); if(count==10) { System.out.print("\b"); } } while (count <= 10); } }
Output:
Printing Numbers from 1 to 10
1,2,3,4,5,6,7,8,9,10
For Loops
The for loop is a looping construct which can execute a set of instructions a specified number of times. It’s a counter controlled loop.
The syntax of the loop is as follows:
for (<initialization>; <loop condition>; <increment expression>)
{
<loop body>;
}
The first part of a for statement is a starting initialization, which executes once before the loop begins. The <initialization> section can also be a comma-separated list of expression statements. The second part of a for statement is a test expression. As long as the expression is true, the loop will continue. If this expression is evaluated as false the first time, the loop will never be executed. The third part of the for statement is the body of the loop. These are the instructions that are repeated each time the program executes the loop. The final part of the for statement is an increment expression that automatically executes after each repetition of the loop body. Typically, this statement changes the value of the counter, which is then tested to see if the loop should continue.
All the sections in the for-header are optional. Any one of them can be left empty, but the two semicolons are mandatory. In particular, leaving out the <loop condition> signifies that the loop condition is true. The (;;) form of for loop is commonly used to construct an infinite loop.
Below is an example that demonstrates the looping construct namely for loop used to print numbers from 1 to 10.
public class ForLoopDemo { public static void main(String[] args) { System.out.println("Printing Numbers from 1 to 10"); for (int count = 1; count <= 10; count++) { System.out.print(count+","); if(count==10) { System.out.println("\b"); } } } }
Output:
Printing Numbers from 1 to 10
1,2,3,4,5,6,7,8,9,10
Transfer Statements
Continue Statement
A continue statement stops the iteration of a loop (while, do or for) and causes execution to resume at the top of the nearest enclosing loop. You use a continue statement when you do not want to execute the remaining statements in the loop, but you do not want to exit the loop itself.
The syntax of the continue statement is
continue; // the unlabeled form
continue <label>; // the labeled form
You can also provide a loop with a label and then use the label in your continue statement. The label name is optional, and is usually only used when you wish to return to the outermost loop in a series of nested loops.
Below is a program to demonstrate the use of continue statement to print Odd Numbers between 1 to 10.
public class ContinueExample { public static void main(String[] args) { System.out.println("Odd Numbers"); for (int i = 1; i <= 10; ++i) { if (i % 2 == 0) continue; // Rest of loop body skipped when i is even System.out.println(i + " "); } } }
Output:
Odd Numbers
1 3 5 7 9
Break Statement
The break statement transfers control out of the enclosing loop ( for, while, do or switch statement). You use a break statement when you want to jump immediately to the statement following the enclosing control structure. You can also provide a loop with a label, and then use the label in your break statement. The label name is optional, and is usually only used when you wish to terminate the outermost loop in a series of nested loops.
The Syntax for break statement is as shown below;
break; // the unlabeled form
break <label>; // the labeled form
Below is a program to demonstrate the use of break statement to print numbers Numbers 1 to 10.
public class BreakExample { public static void main(String[] args) { System.out.println("Numbers 1 - 10"); for (int i = 1;; ++i) { if (i == 11) break; // Rest of loop body skipped when i is 11 System.out.println(i + " "); } } }
Output:
Numbers 1 - 10
1 2 3 4 5 6 7 8 9 10
Java Operators
They are used to manipulate primitive data types. Java operators can be classified as unary, binary, or ternary—meaning taking one, two, or three arguments, respectively. A unary operator may appear
before (prefix) its argument or after (postfix) its argument. A binary or ternary operator appears between its arguments.
Operators in java fall into 8 different categories:
Java operators fall into eight different categories: assignment, arithmetic, relational, logical, bitwise,
compound assignment, conditional, and type.
Assignment Operators: (=)
Arithmetic Operators: (- , + , * , / , % , ++ , --)
Relational Operators: (> , < , >= , <= , == , !=)
Logical Operators: (&& , || , & , | , ! , ^)
Bit wise Operator: (& , | , ^ , >> , >>>)
Compound Assignment Operators: (+= , -= , *= , /= , %= , <<= , >>= , >>>=)
Conditional Operator: (?:)
Java has eight different operator types: assignment, arithmetic, relational, logical, bitwise, compound assignment, conditional, and type.
Assignment operators
The java assignment operator statement has the following syntax:
<variable> = <expression>
If the value already exists in the variable it is overwritten by the assignment operator (=).
public class AssignmentOperatorsDemo { public AssignmentOperatorsDemo() { int j, k; // Assigning Primitive Values j = 10; // j gets the value 10. j = 5; // j gets the value 5. Previous value is overwritten. k = j; // k gets the value 5. System.out.println("j is : " + j); System.out.println("k is : " + k); // Assigning References Integer i1 = new Integer("1"); Integer i2 = new Integer("2"); System.out.println("i1 is : " + i1); System.out.println("i2 is : " + i2); i1 = i2; System.out.println("i1 is : " + i1); System.out.println("i2 is : " + i2); // Multiple Assignments k = j = 10; // (k = (j = 10)) System.out.println("j is : " + j); System.out.println("k is : " + k); } public static void main(String args[]) { new AssignmentOperatorsDemo(); } }
Arithmetic operators
Java provides eight Arithmetic operators. They are for addition, subtraction, multiplication, division, modulo (or remainder), increment (or add 1), decrement (or subtract 1), and negation. An example program is shown below that demonstrates the different arithmetic operators in java.
The binary operator + is overloaded in the sense that the operation performed is determined by the type of the operands. When one of the operands is a String object, the other operand is implicitly converted to its string representation and string concatenation is performed.
String message = 100 + “Messages”; //”100 Messages”
public class ArithmeticOperatorsDemo { public ArithmeticOperatorsDemo() { int x, y = 10, z = 5; x = y + z; System.out.println("+ operator resulted in " + x); x = y - z; System.out.println("- operator resulted in " + x); x = y * z; System.out.println("* operator resulted in " + x); x = y / z; System.out.println("/ operator resulted in " + x); x = y % z; System.out.println("% operator resulted in " + x); x = y++; System.out.println("Postfix ++ operator resulted in " + x); x = ++z; System.out.println("Prefix ++ operator resulted in " + x); x = -y; System.out.println("Unary operator resulted in " + x); // Some examples of special Cases int tooBig = Integer.MAX_VALUE + 1; // -2147483648 which is Integer.MIN_VALUE. int tooSmall = Integer.MIN_VALUE - 1; // 2147483647 which is Integer.MAX_VALUE. System.out.println("tooBig becomes " + tooBig); System.out.println("tooSmall becomes " + tooSmall); System.out.println(4.0 / 0.0); // Prints: Infinity System.out.println(-4.0 / 0.0); // Prints: -Infinity System.out.println(0.0 / 0.0); // Prints: NaN double d1 = 12 / 8; // result: 1 by integer division. d1 gets the value 1.0. double d2 = 12.0F / 8; // result: 1.5 System.out.println("d1 is " + d1); System.out.println("d2 iss " + d2); } public static void main(String args[]) { new ArithmeticOperatorsDemo(); } }
Relational operators
Relational operators in Java are used to compare 2 or more objects. Java provides six relational operators:
greater than (>), less than (<), greater than or equal (>=), less than or equal (<=), equal (==), and not equal (!=).
All relational operators are binary operators, and their operands are numeric expressions.
Binary numeric promotion is applied to the operands of these operators. The evaluation results in a boolean value. Relational operators have precedence lower than arithmetic operators, but higher than that of the assignment operators. An example program is shown below that demonstrates the different relational operators in java.
public class RelationalOperatorsDemo { public RelationalOperatorsDemo( ) { int x = 10, y = 5; System.out.println("x > y : "+(x > y)); System.out.println("x < y : "+(x < y)); System.out.println("x >= y : "+(x >= y)); System.out.println("x <= y : "+(x <= y)); System.out.println("x == y : "+(x == y)); System.out.println("x != y : "+(x != y)); } public static void main(String args[]) { new RelationalOperatorsDemo(); } }
Logical operators
Logical operators return a true or false value based on the state of the Variables. There are six logical, or boolean, operators. They are AND, conditional AND, OR, conditional OR, exclusive OR, and NOT. Each argument to a logical operator must be a boolean data type, and the result is always a boolean data type. An example program is shown below that demonstrates the different Logical operators in java.
public class LogicalOperatorsDemo { public LogicalOperatorsDemo() { boolean x = true; boolean y = false; System.out.println("x & y : " + (x & y)); System.out.println("x && y : " + (x && y)); System.out.println("x | y : " + (x | y)); System.out.println("x || y: " + (x || y)); System.out.println("x ^ y : " + (x ^ y)); System.out.println("!x : " + (!x)); } public static void main(String args[]) { new LogicalOperatorsDemo(); } }
Given that x and y represent boolean expressions, the boolean logical operators are defined in the Table below.
x
|
y
|
!x
|
x & y
x && y
|
x | y
x || y
|
x ^ y
|
true
|
true
|
false
|
true
|
true
|
false
|
true
|
false
|
false
|
false
|
true
|
true
|
false
|
true
|
true
|
false
|
true
|
true
|
false
|
false
|
true
|
false
|
false
|
false
|
Java provides Bit wise operators to manipulate the contents of variables at the bit level.
These variables must be of numeric data type ( char, short, int, or long). Java provides seven bitwise
operators. They are AND, OR, Exclusive-OR, Complement, Left-shift, Signed Right-shift, and Unsigned Right-shift. An example program is shown below that demonstrates the different Bit wise operators in java.
public class BitwiseOperatorsDemo { public BitwiseOperatorsDemo() { int x = 0xFAEF; //1 1 1 1 1 0 1 0 1 1 1 0 1 1 1 1 int y = 0xF8E9; //1 1 1 1 1 0 0 0 1 1 1 0 1 0 0 1 int z; System.out.println("x & y : " + (x & y)); System.out.println("x | y : " + (x | y)); System.out.println("x ^ y : " + (x ^ y)); System.out.println("~x : " + (~x)); System.out.println("x << y : " + (x << y)); System.out.println("x >> y : " + (x >> y)); System.out.println("x >>> y : " + (x >>> y)); //There is no unsigned left shift operator } public static void main(String args[]) { new BitwiseOperatorsDemo(); } }
The result of applying bitwise operators between two corresponding bits in the operands is shown in the Table below.
A
|
B
|
~A
|
A & B
|
A | B
|
A ^ B
|
1
|
1
|
0
|
1
|
1
|
0
|
1
|
0
|
0
|
0
|
1
|
1
|
0
|
1
|
1
|
0
|
1
|
1
|
0
|
0
|
1
|
0
|
0
|
0
|
Output: 3,0,3
/* * The below program demonstrates bitwise operators keeping in mind operator precedence * Operator Precedence starting with the highest is -> |, ^, & */ public class BitwisePrecedenceEx { public static void main(String[] args) { int a = 1 | 2 ^ 3 & 5; int b = ((1 | 2) ^ 3) & 5; int c = 1 | (2 ^ (3 & 5)); System.out.print(a + "," + b + "," + c); } }
Conditional operators
The Conditional operator is the only ternary (operator takes three arguments) operator in Java. The operator evaluates the first argument and, if true, evaluates the second argument. If the first argument evaluates to false, then the third argument is evaluated. The conditional operator is the expression equivalent of the if-else statement. The conditional expression can be nested and the conditional operator associates from right to left:
(a?b?c?d:e:f:g) evaluates as (a?(b?(c?d:e):f):g)
An example program is shown below that demonstrates the Ternary operator in java.
public class TernaryOperatorsDemo { public TernaryOperatorsDemo() { int x = 10, y = 12, z = 0; z = x > y ? x : y; System.out.println("z : " + z); } public static void main(String args[]) { new TernaryOperatorsDemo(); } }
/* * The following programs shows that when no explicit parenthesis is used then the conditional operator * evaluation is from right to left */ public class BooleanEx1 { static String m1(boolean b) { return b ? "T" : "F"; } public static void main(String[] args) { boolean t1 = false ? false : true ? false : true ? false : true; boolean t2 = false ? false : (true ? false : (true ? false : true)); boolean t3 = ((false ? false : true) ? false : true) ? false : true; System.out.println(m1(t1) + m1(t2) + m1(t3)); } }
Output: FFT
Type conversion allows a value to be changed from one primitive data type to another. Conversion can occur explicitly, as specified in
the program, or implicitly, by Java itself. Java allows both type widening and type narrowing conversions.
In java Conversions can occur by the following ways:
Using a cast operator (explicit promotion)
Using an arithmetic operator is used with arguments of different data types (arithmetic promotion)
A value of one type is assigned to a variable of a different type (assignment promotion)
Operator Precedence
The order in which operators are applied is known as precedence. Operators with a higher precedence are applied before operators with a lower precedence. The operator precedence order of Java is shown below. Operators at the top of the table are applied before operators lower down in the table. If two operators have the same precedence, they are applied in the order they appear in a statement.
That is, from left to right. You can use parentheses to override the default precedence.
postfix | [] . () expr++ expr– |
unary | ++expr –expr +expr -expr ! ~ |
creation/caste | new (type)expr |
multiplicative | * / % |
additive | + - |
shift | >> >>> |
relational | < <= > >= instanceof |
equality | == != |
bitwise AND | & |
bitwise exclusive OR | ^ |
bitwise inclusive OR | | |
logical AND | && |
logical OR | || |
ternary | ?: |
assignment | = “op=” |
Example
In an operation such as,
result = 4 + 5 * 3
First (5 * 3) is evaluated and the result is added to 4 giving the Final Result value as 19. Note that ‘*’ takes higher precedence than ‘+’ according to chart shown above. This kind of precedence of one operator over another applies to all the operators.
QUIZ
1. How to generate a random number between 1 to x, x being a whole number greater than 1
Ans: double result = x * Math.random();
Basic Language Elements in Java
This part of the Java tutorial teaches you the basic language elements and syntax for the java programming language. Once you get these basic language concepts you can continue with the other object oriented programming language concepts.
To Understand the Introduction part read this post.
Keywords
There are certain words with a specific meaning in java which tell (help) the compiler what the program is supposed to do. These Keywords cannot be used as variable names, class names, or method names. Keywords in java are case sensitive, all characters being lower case.
Keywords are reserved words that are predefined in the language; see the table below (Taken from Sun Java Site). All the keywords are in lowercase.
abstract default if private this
boolean do implements protected throw
break double import public throws
byte else instanceof return transient
case extends int short try
catch final interface static void
char finally long strictfp volatile
class float native super while
const for new switch
continue goto package synchronized
Keywords are marked in yellow as shown in the sample code below:
/** This class is a Hello World Program used to introduce the Java Language*/ public class HelloWorld { public static void main(String[] args) { System.out.println(“Hello World”); //Prints output to console } }
For more information on different Keywords – Java Keywords
Some Tricky Observations: The words virtual, ifdef, typedef, friend, struct and union are all words related to
the C programming language. const and goto are Java keywords. The word finalize is the name of a method
of the Object class and hence not a keyword. enum and label are not keywords.
Comments
Comments are descriptions that are added to a program to make code easier to understand. The compiler ignores comments and hence its only for documentation of the program.
Java supports three comment styles.
Block style comments begin with /* and terminate with */ that spans multiple lines.
Line style comments begin with // and terminate at the end of the line. (Shown in the above program)
Documentation style comments begin with /** and terminate with */ that spans multiple lines. They are generally created using the automatic documentation generation tool, such as javadoc. (Shown in the above program)
name of this compiled file is comprised of the name of the class with .class as an extension.
Variable, Identifiers and Data Types
Variables are used for data that change during program execution. All variables have a name, a type, and a scope. The programmer assigns the names to variables, known as identifiers. An Identifier must be unique within a scope of the Java program. Variables have a data type, that indicates the kind of value they can store. Variables declared inside of a block or method are called local variables; They are not automatically initialized. The compiler will generate an error as a result of the attempt to access the local variables before a value has been assigned.
public class localVariableEx { public static int a; public static void main(String[] args) { int b; System.out.println("a : "+a); System.out.println("b : "+b); //Compilation error }}
Note in the above example, a compilation error results in where the variable is tried to be accessed and not at the place where its declared without any value.
The data type indicates the attributes of the variable, such as the range of values that can be stored and the operators that can be used to manipulate the variable. Java has four main primitive data types built into the language. You can also create your own composite data types.
Java has four main primitive data types built into the language. We can also create our own data types.
- Integer: byte, short, int, and long.
- Floating Point: float and double
- Character: char
- Boolean: variable with a value of true or false.
The following chart (Taken from Sun Java Site) summarizes the default values for the java built in data types. Since I thought Mentioning the size was not important as part of learning Java, I have not mentioned it in the below table. The size for each Java type can be obtained by a simple Google search.
Data Type | Default Value (for fields) | Range |
byte | 0 | -127 to +128 |
short | 0 | -32768 to +32767 |
int | 0 | |
long | 0L | |
float | 0.0f | |
double | 0.0d | |
char | ‘\u0000′ | 0 to 65535 |
String (object) | null | |
boolean | false |
When we declare a variable we assign it an identifier and a data type.
For Example
String message = “hello world”
In the above statement, String is the data type for the identifier message. If you don’t specify a value when the variable is declared, it will be assigned the default value for its data type.
Identifier Naming Rules
Can consist of upper and lower case letters, digits, dollar sign ($) and the underscore ( _ ) character.
Must begin with a letter, dollar sign, or an underscore
Are case sensitive
Keywords cannot be used as identifiers
Within a given section of your program or scope, each user defined item must have a unique identifier
Can be of any length.
Classes
A class is nothing but a blueprint for creating different objects which defines its properties and behaviors. An object exhibits the properties and behaviors defined by its class. A class can contain fields and methods to describe the behavior of an object. Methods are nothing but members of a class that provide a service for an object or perform some business logic.
Objects
An object is an instance of a class created using a new operator. The new operator returns a reference to a new instance of a class. This reference can be assigned to a reference variable of the class. The process of creating objects from a class is called instantiation. An object reference provides a handle to an object that is created and stored in memory. In Java, objects can only be manipulated via references, which can be stored in variables.
Interface
An Interface is a contract in the form of collection of method and constant declarations. When a class implements an interface, it promises to implement all of the methods declared in that interface.
Instance Members
Each object created will have its own copies of the fields defined in its class called instance variables which represent an object’s state. The methods of an object define its behaviour called instance methods. Instance variables and instance methods, which belong to objects, are collectively called instance members. The dot ‘.’ notation with a object reference is used to access Instance Members.
Static Members
Static members are those that belong to a class as a whole and not to a particular instance (object). A static variable is initialized when the class is loaded. Similarly, a class can have static methods. Static variables and static methods are collectively known as static members, and are declared with a keyword static. Static members in the class can be accessed either by using the class name or by using the object reference, but instance members can only be accessed via object references.
Below is a program showing the various parts of the basic language syntax that were discussed above.
/** Comment * Displays "Hello World!" to the standard output. */ public class HelloWorld { String output = ""; static HelloWorld helloObj; //Line 1 public HelloWorld(){ output = "Hello World"; } public String printMessage(){ return output; } public static void main (String args[]) { helloObj = new HelloWorld(); //Line 2 System.out.println(helloObj.printMessage()); } }
Class Name: HelloWorld
Object Reference: helloObj (in Line 1)
Object Created: helloObj (In Line 2)
Member Function: printMessage
Field: output (String)
Static Member: helloObj
Instance Member : output (String)
Popular Posts
-
It's been about three years since Microsoft unveiled a new version of Office, and particularly with Windows 8 just months away from ...
-
There's general agreement that Sony stumbled out of the gate with the PlayStation 3. Months of intense hype were followed by a la...
-
Latest Windows Phone 8 rumor suggests that current Windows Phone devices will receive the update Microsoft has yet to come forward wi...
-
Microsoft is holding an invitation-only press event in San Francisco today at which it is expected to debut the next version of its...
-
Gaming & Gadgets Microsoft kick-started the "next-generation" of gaming on November 22, 2005, when the company release...