Java Operator Precedence
Java Operator Precedence
Java Operator Precedence
additive +-
equality == !=
bitwise exclusive OR ^
bitwise inclusive OR |
logical OR ||
Ternary ternary ?:
(iii)
BASIS FOR
WHILE DO-WHILE
COMPARISON
Controlling In 'while' loop the controlling condition appears at In 'do-while' loop the controlling condition
Condition the start of the loop. appears at the end of the loop.
Iterations The iterations do not occur if, the condition at the The iteration occurs at least once even if the
first iteration, appears false. condition is false at the first iteration.
The while loop checks the condition at the starting of If the condition in a while loop is false not a single
the loop and if the condition is satisfied statement statement inside the loop is executed, and if the
inside the loop, is executed. In do-while loop, the condition in ‘do-while’ loop is false then also the
condition is checked after the execution of all body of the loop is executed at least once then the
statements in the body of the loop. condition is tested.
(v)
Declaring Arrays
Let's declare an array of 10 integer values.
This declaration declares an array named num that contains 10 integers. When the compiler
encounters this declaration, it immediately sets aside enough memory to hold all 10 elements.
The square brackets ([ ]) after the "type" indicate that num is going to be an array of type int rather
than a single instance of an int. Since the new operator creates (defines) the array, it must know the
type and size of the array. The new operator locates a block of memory large enough to contain the array and associates the array name, num, with
this memory block.
A program can access each of the array elements (the individual cells) by referring to the name of the array followed by the subscript denoting the
element (cell). For example, the third element is denoted num[2].
The subscripts of array elements begin with zero.
The first subscript is always zero and the last subscript's value is
(length - 1), where length designates the number of elements within the array (which is set when the array is declared).
Consider the following possible (?) subscripts for our array:
num [ 0 ] always OK
num [ 9 ] OK (given the above declaration)
num [ 10 ] illegal (no such cell from this declaration)
num [ -1 ] always NO! (illegal)
num [ 3.5 ] always NO! (illegal)
If the value of an index for an array element is negative, a decimal, or greater than or equal to the length of the array (remember that the last subscript
is array length - 1), an error message will be ArrayIndexOutOfBoundsException.
If you see this message, immediately check to see how your array is being utilized.
(vi)
Classes and Objects.
Object − Objects have states and behaviors. Example: A dog has states - color, name, breed as well as behaviors – wagging the tail, barking,
eating. An object is an instance of a class.
Class − A class can be defined as a template/blueprint that describes the behavior/state that the object of its type support.
Classes in Java
A class is a blueprint from which individual objects are created.
Following is a sample of a class.
Example
public class Dog {
String breed;
int age;
String color;
void barking() {
}
void hungry() {
}
void sleeping() {
}
}
A class can contain any of the following variable types.
Local variables − Variables defined inside methods, constructors or blocks are called local variables. The variable will be declared and initialized within
the method and the variable will be destroyed when the method has completed.
Instance variables − Instance variables are variables within a class but outside any method. These variables are initialized when the class is instantiated.
Instance variables can be accessed from inside any method, constructor or blocks of that particular class.
Class variables − Class variables are variables declared within a class, outside any method, with the static keyword.
A class can have any number of methods to access the value of various kinds of methods. In the above example, barking(), hungry() and sleeping() are
methods.
(vii)
CLASSPATH - For Locating Classes
CLASSPATH is an environment variable (i.e., global variables of the operating system available to all the processes) needed for the Java compiler and
runtime to locate the Java packages used in a Java program. (Why not call PACKAGEPATH?) This is similar to another environment variable PATH, which
is used by the CMD shell to find the executable programs.
CLASSPATH can be set in one of the following ways:
1. CLASSPATH can be set permanently in the environment: In Windows, choose control panel ⇒ System ⇒ Advanced ⇒ Environment Variables
⇒ choose "System Variables" (for all the users) or "User Variables" (only the currently login user) ⇒ choose "Edit" (if CLASSPATH already
exists) or "New" ⇒ Enter "CLASSPATH" as the variable name ⇒ Enter the required directories and JAR files (separated by semicolons) as the
value (e.g., ".;c:\javaproject\classes;d:\tomcat\lib\servlet-api.jar"). Take note that you need to include the current working directory
(denoted by '.') in the CLASSPATH.
To check the current setting of the CLASSPATH, issue the following command:
> SET CLASSPATH
2. CLASSPATH can be set temporarily for that particular CMD shell session by issuing the following command:
3. > SET CLASSPATH=.;c:\javaproject\classes;d:\tomcat\lib\servlet-api.jar
4. Instead of using the CLASSPATH environment variable, you can also use the command-line option -classpath or -cp of
the javac and java commands, for example,
> java –classpath c:\javaproject\classes com.abc.project1.subproject2.MyClass3
(ix)
Priority of a Thread (Thread Priority):
Each thread have a priority. Priorities are represented by a number between 1 and 10. In most cases, thread schedular schedules the threads according
to their priority (known as preemptive scheduling). But it is not guaranteed because it depends on JVM specification that which scheduling it chooses.
Q2
An applet is a Java program that runs in a Web browser. An applet can be a fully functional Java application because it has the entire Java API at its
disposal.
There are some important differences between an applet and a standalone Java application, including the following −
An applet is a Java class that extends the java.applet.Applet class.
A main() method is not invoked on an applet, and an applet class will not define main().
Applets are designed to be embedded within an HTML page.
When a user views an HTML page that contains an applet, the code for the applet is downloaded to the user's machine.
A JVM is required to view an applet. The JVM can be either a plug-in of the Web browser or a separate runtime environment.
The JVM on the user's machine creates an instance of the applet class and invokes various methods during the applet's lifetime.
Applets have strict security rules that are enforced by the Web browser. The security of an applet is often referred to as sandbox security,
comparing the applet to a child playing in a sandbox with various rules that must be followed.
Other classes that the applet needs can be downloaded in a single Java Archive (JAR) file.
Life Cycle of an Applet
Four methods in the Applet class gives you the framework on which you build any serious applet −
init − This method is intended for whatever initialization is needed for your applet. It is called after the param tags inside the applet tag have
been processed.
start − This method is automatically called after the browser calls the init method. It is also called whenever the user returns to the page
containing the applet after having gone off to other pages.
stop − This method is automatically called when the user moves off the page on which the applet sits. It can, therefore, be called repeatedly
in the same applet.
destroy − This method is only called when the browser shuts down normally. Because applets are meant to live on an HTML page, you
should not normally leave resources behind after a user leaves the page that contains the applet.
paint − Invoked immediately after the start() method, and also any time the applet needs to repaint itself in the browser. The paint() method
is actually inherited from the java.awt.
Invoking an Applet
An applet may be invoked by embedding directives in an HTML file and viewing the file through an applet viewer or Java-enabled browser.
The <applet> tag is the basis for embedding an applet in an HTML file. Following is an example that invokes the "Hello, World" applet −
<html>
<title>The Hello, World Applet</title>
<hr>
<applet code = "HelloWorldApplet.class" width = "320" height = "120">
If your browser was Java-enabled, a "Hello, World"
message would appear here.
</applet>
<hr>
</html>
Note − You can refer to HTML Applet Tag to understand more about calling applet from HTML.
The code attribute of the <applet> tag is required. It specifies the Applet class to run. Width and height are also required to specify the initial size of
the panel in which an applet runs. The applet directive must be closed with an </applet> tag.
If an applet takes parameters, values may be passed for the parameters by adding <param> tags between <applet> and </applet>. The browser
ignores text and other tags between the applet tags.
Non-Java-enabled browsers do not process <applet> and </applet>. Therefore, anything that appears between the tags, not related to the applet, is
visible in non-Java-enabled browsers.
The viewer or browser looks for the compiled Java code at the location of the document. To specify otherwise, use the codebase attribute of the
<applet> tag as shown −
<applet codebase = "https://amrood.com/applets" code = "HelloWorldApplet.class"
width = "320" height = "120">
If an applet resides in a package other than the default, the holding package must be specified in the code attribute using the period character (.) to
separate package/class components. For example −
<applet = "mypackage.subpackage.TestApplet.class"
width = "320" height = "120">
Getting Applet Parameters
The following example demonstrates how to make an applet respond to setup parameters specified in the document. This applet displays a
checkerboard pattern of black and a second color.
The second color and the size of each square may be specified as parameters to the applet within the document.
CheckerApplet gets its parameters in the init() method. It may also get its parameters in the paint() method. However, getting the values and saving
the settings once at the start of the applet, instead of at every refresh, is convenient and efficient.
The applet viewer or browser calls the init() method of each applet it runs. The viewer calls init() once, immediately after loading the applet.
(Applet.init() is implemented to do nothing.) Override the default implementation to insert custom initialization code.
The Applet.getParameter() method fetches a parameter given the parameter's name (the value of a parameter is always a string). If the value is
numeric or other non-character data, the string must be parsed.
The following is a skeleton of CheckerApplet.java −
import java.applet.*;
import java.awt.*;
public class CheckerApplet extends Applet {
int squareSize = 50; // initialized to default size
public void init() {}
private void parseSquareSize (String param) {}
private Color parseColor (String param) {}
public void paint (Graphics g) {}
}
Here are CheckerApplet's init() and private parseSquareSize() methods −
public void init () {
String squareSizeParam = getParameter ("squareSize");
parseSquareSize (squareSizeParam);
setBackground (Color.black);
setForeground (fg);
}
Q4
Creating a package
Creating a package in java is quite easy. Simply include a package command followed by name of the package as the first statement in java source file.
package mypack;
public class employee
{
...statement;
}
if(condition)
{
// Statements to execute if
// condition is true
}
Here, condition after evaluation will be either true or false. if statement accepts boolean values – if the value is
true then it will execute the block of statements under it.
If we do not provide the curly braces ‘{‘ and ‘}’ after if( condition ) then by default if statement will consider
the immediate one statement to be inside its block. For example,
if(condition)
statement1;
statement2;
// Here if the condition is true, if block will consider only statement1 to be inside its block.
Example:
// Java program to illustrate If statement
class IfDemo
{
public static void main(String args[])
{
int i = 10;
if (i > 15)
System.out.println("10 is less than 15");
// This statement will be executed
// as if considers one statement by default
System.out.println("I am Not in if");
}
}
Output:
I am Not in if
if-else: The if statement alone tells us that if a condition is true it will execute a block of statements and if the condition is false it won’t. But
what if we want to do something else if the condition is false. Here comes the else statement. We can use the else statement with if statement
to execute a block of code when the condition is false.
Syntax:
if (condition)
{
// Executes this block if
// condition is true
}
else
{
// Executes this block if
// condition is false
}
Example:
// Java program to illustrate if-else statement
class IfElseDemo
{
public static void main(String args[])
{
int i = 10;
if (i < 15)
System.out.println("i is smaller than 15");
else
System.out.println("i is greater than 15");
}
}
Output:
i is smaller than 15
nested-if: A nested if is an if statement that is the target of another if or else. Nested if statements means an if statement inside an if statement.
Yes, java allows us to nest if statements within if statements. i.e, we can place an if statement
inside another if statement.
Syntax:
if (condition1)
{
// Executes when condition1 is true
if (condition2)
{
// Executes when condition2 is true
}
}
Example:
// Java program to illustrate nested-if statement
class NestedIfDemo
{
public static void main(String args[])
{
int i = 10;
if (i == 10)
{
// First if statement
if (i < 15)
System.out.println("i is smaller than 15");
// Nested - if statement
// Will only be executed if statement above
// it is true
if (i < 12)
System.out.println("i is smaller than 12 too");
else
System.out.println("i is greater than 15");
}
}
}
Output:
i is smaller than 15
i is smaller than 12 too
if-else-if ladder: Here, a user can decide among multiple options.The if statements are executed from
the top down. As soon as one of the conditions controlling the if is true, the statement associated
with that if is executed, and the rest of the ladder is bypassed. If none of the conditions is true, then
the final else statement will be executed.
if (condition)
statement;
else if (condition)
statement;
.
.
else
statement;
Example:
// Java program to illustrate if-else-if ladder
class ifelseifDemo
{
public static void main(String args[])
{
int i = 20;
if (i == 10)
System.out.println("i is 10");
else if (i == 15)
System.out.println("i is 15");
else if (i == 20)
System.out.println("i is 20");
else
System.out.println("i is not present");
}
}
Output:
i is 20
switch-case The switch statement is a multiway branch statement. It provides an easy way to dispatch execution to different parts of code
based on the value of the expression.
Syntax:
switch (expression)
{
case value1:
statement1;
break;
case value2:
statement2;
break;
.
.
case valueN:
statementN;
break;
default:
statementDefault;
Expression can be of type byte, short, int char or an enumeration. Beginning with
JDK7, expression can also be of type String.
Dulplicate case values are not allowed.
The default statement is optional.
The break statement is used inside the switch to terminate a statement sequence.
The break statement is optional. If omitted, execution will continue on into the next
case.
Example:
// Java program to illustrate switch-case
class SwitchCaseDemo
{
public static void main(String args[])
{
int i = 9;
switch (i)
{
case 0:
System.out.println("i is zero.");
break;
case 1:
System.out.println("i is one.");
break;
case 2:
System.out.println("i is two.");
break;
default:
System.out.println("i is greater than 2.");
}
}}