Sei sulla pagina 1di 9

Q1 (ii) Java Operator Precedence

Operator Type Category Precedence

Unary postfix expr++ expr--

prefix ++expr --expr +expr -expr ~ !

Arithmetic multiplicative */%

additive +-

Shift shift << >> >>>

Relational comparison < > <= >= instanceof

equality == !=

Bitwise bitwise AND &

bitwise exclusive OR ^

bitwise inclusive OR |

Logical logical AND &&

logical OR ||

Ternary ternary ?:

Assignment assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=

(iii)
BASIS FOR
WHILE DO-WHILE
COMPARISON

General Form while ( condition) { do{


statements; //body of loop .
} statements; // body of loop.
.
} while( Condition );

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.

3 constants defiend in Thread class:


1. public static int MIN_PRIORITY
2. public static int NORM_PRIORITY
3. public static int MAX_PRIORITY
Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and the value of MAX_PRIORITY is 10.
Example of priority of a Thread:
class TestMultiPriority1 extends Thread{
public void run(){
System.out.println("running thread name is:"+Thread.currentThread().getName());
System.out.println("running thread priority is:"+Thread.currentThread().getPriority());
}
public static void main(String args[]){
TestMultiPriority1 m1=new TestMultiPriority1();
TestMultiPriority1 m2=new TestMultiPriority1();
m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);
m1.start();
m2.start();
}
}
Output:running thread name is:Thread-0
running thread priority is:10
running thread name is:Thread-1
running thread priority is:1

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);

String colorParam = getParameter ("color");


Color fg = parseColor (colorParam);

setBackground (Color.black);
setForeground (fg);
}

private void parseSquareSize (String param) {


if (param == null) return;
try {
squareSize = Integer.parseInt (param);
}catch (Exception e) {
// Let default value remain
}
}
The applet calls parseSquareSize() to parse the squareSize parameter. parseSquareSize() calls the library method Integer.parseInt(), which parses a
string and returns an integer. Integer.parseInt() throws an exception whenever its argument is invalid.
Therefore, parseSquareSize() catches exceptions, rather than allowing the applet to fail on bad input.
The applet calls parseColor() to parse the color parameter into a Color value. parseColor() does a series of string comparisons to match the parameter
value to the name of a predefined color. You need to implement these methods to make this applet work.

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;
}

The above statement create a package called mypack.


Java uses file system directory to store package. For example the .class for any classes you define to be part of mypack package must be stored in a
directory called mypack.
Additional points on package:
 A package is always defined in a separate folder having the same name as a package name.
 Define all classes in that package folder.
 All classes of the package which we wish to access outside the package must be declared public.
 All classes within the package must have the package statement as its first line.
 All classes of the package must be compiled before use (So that its error free)

Example of java package


//save as FirstProgram.java
package LearnJava;
public class FirstProgram{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
import keyword
import keyword is used to import built-in and user-defined packages into your java source file so that your class can refer to a class that is in another
package by directly using its name.
There are 3 different ways to refer to class that is present in different package
1. Using fully qualified name(But this is not a good practice.)
If you use fully qualified name then only declared class of this package will be accessible. Now there is no need to import. But you need to use fully
qualified name every time when you are accessing the class or interface.
It is generally used when two packages have same class name e.g. java.util and java.sql packages contain Date class.
Example :
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
}
Output:
Hello
2. import the only class you want to use(Using packagename.classname)
If you import package.classname then only declared class of this package will be accessible.
Example :
//save by A.java
package pack;
public class A{
public void msg(){
System.out.println("Hello");
}
}
//save by B.java
package mypack;
import pack.A;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:
Hello
3. import all the classes from the particular package(Using packagename.*)
If you use package.* then all the classes and interfaces of this package will be accessible but not subpackages.
The import keyword is used to make the classes and interface of another package accessible to the current package.
Example :
//save by First.java
package LearnJava;
public class First{
public void msg(){System.out.println("Hello");}
}
//save by Second.java
package Java;
import Learnjava.*;
class Second{
public static void main(String args[]){
First obj = new First();
obj.msg();
}
}
Output:
Hello
Q5
Overriding vs. Overloading in Java
Overriding and Overloading are two very important concepts in Java. They are confusing for Java novice programmers. This post illustrates their
differences by using two simple examples.
1. Definitions
Overloading occurs when two or more methods in one
class have the same method name but different
parameters.
Overriding means having two methods with the same
method name and parameters (i.e., method signature).
One of the methods is in the parent class and the other
is in the child class. Overriding allows a child class to
provide a specific implementation of a method that is
already provided its parent class.
2. Overriding vs. Overloading
Here are some important facts about Overriding and
Overloading:
1). The real object type in the run-time, not the reference variable's type, determines which overridden method is used at runtime. In contrast,
reference type determines which overloaded method will be used at compile time.
2). Polymorphism applies to overriding, not to overloading.
3). Overriding is a run-time concept while overloading is a compile-time concept.
3. An Example of Overriding
Here is an example of overriding. After reading the code, guess the output.
class Dog{
public void bark(){
System.out.println("woof ");
}
}
class Hound extends Dog{
public void sniff(){
System.out.println("sniff ");
}
public void bark(){
System.out.println("bowl");
}
}
public class OverridingTest{
public static void main(String [] args){
Dog dog = new Hound();
dog.bark();
}
}
Output:
bowl
In the example above, the dog variable is declared to be a Dog. During compile time, the compiler checks if the Dog class has the bark() method. As long
as the Dog class has the bark() method, the code compilers. At run-time, a Hound is created and assigned to dog. The JVM knows that dog is referring
to the object of Hound, so it calls the bark() method of Hound. This is called Dynamic Polymorphism.
4. An Example of Overloading
class Dog{
public void bark(){
System.out.println("woof ");
}
//overloading method
public void bark(int num){
for(int i=0; i<num; i++)
System.out.println("woof ");
}
}
In this overloading example, the two bark method can be invoked by using different parameters. Compiler know they are different because they have
different method signature (method name and method parameter list).
Q7
Decision Making in Java (if, if-else, switch, break, continue, jump)
Decision Making in programming is similar to decision making in real life. In programming also we face some situations where we want a certain block
of code to be executed when some condition is fulfilled.
A programming language uses control statements to control the flow of execution of program based on certain conditions. These are used to cause the
flow of execution to advance and branch based on changes to the state of a program.
Java’s Selection statements:
 if
 if-else
 nested-if
 if-else-if
 switch-case
 jump – break, continue, return
These statements allow you to control the flow of your program’s execution based upon conditions known only during run time.
 if: if statement is the most simple decision making statement. It is used to decide whether a certain statement or block of statements will be
executed or not i.e if a certain condition is true then a block of statement is executed otherwise not.
Syntax:

 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.");
}
}}

Potrebbero piacerti anche