BSC It - Sem IV - Core Java
BSC It - Sem IV - Core Java
BSC It - Sem IV - Core Java
Core Java
Class : S.Y.BSc(I.T)
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
Index
Chapter Name
No.
1 Introduction
2 Operators in Java
3 Statements in Java
4 Loops in Java
5 Program List
6 Arrays and Strings
7 Exception Handling
8 OOPS
9 Inheritance
10 Multithreading
11 Packages
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
1 - Introduction
What is java?
Class
A template that describes the kinds of state and behavior that objects of its
type support.
Object
At runtime, when the Java Virtual Machine (JVM) encounters the new
keyword.
it will use the appropriate class to make an object which is an instance of that
class.
That object will have its own state, and access to all of the behaviors defined
by its class.
State (instance variables)
Each object (instance of a class) will have its own unique set of instance
variables as defined in the class.
Behavior (methods)
When a programmer creates a class, He/She creates methods for that class.
They are where algorithms get executed, and data gets manipulated.
Features Of Java:-
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
Platform Independent
Simple
Object Oriented
Robust
Distributed
Portable
Dynamic
Secure
Performance
Interpreted
Platform Independent
Not even a single language is idle to this feature but java is more closer to this
feature.
The programs written on one platform can run on any platform provided the
platform must have the JVM.
Simple
There are various features that makes the java as a simple language.
Programs are easy to write and debug because java does not use the pointers
explicitly.
Java provides the bug free system due to the strong memory management. It also
has the automatic memory allocation and deallocation system.
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
Object Oriented
To be an Object Oriented language, any language must follow at least the four
characteristics as follows.
Inheritance : It is the process of creating the new classes and using the behavior of
the existing classes by extending them just to reuse the existing code and adding the
additional features as needed.
Polymorphism: As the name suggest one name multiple form, Polymorphism is the
way of providing the different functionality by the functions having the same name
based on the signatures of the methods.
Dynamic binding: Sometimes we don't have the knowledge of objects about their
specific types while writing our code. It is the way of providing the
maximum functionality to a program about the specific type at runtime.
Robust
Java has the strong memory allocation and automatic garbage collection mechanism.
It provides the powerful exception handling and type checking mechanism as
compare to other programming languages.
Compiler checks the program whether there any error and interpreter checks any
run time error and makes the system secure from crash.
All of the above features makes the java language robust.
Distributed
o The widely used protocols like HTTP and FTP are developed in java.
o Internet programmers can call functions on these protocols and can get access the
files from any remote machine on the internet rather than writing codes on their
local system.
Portable
Java also have the standard data size irrespective of operating system or the
processor. These features makes the java as a portable language.
Dynamic
While executing the java program the user can get the required files dynamically
from a local drive or from a computer thousands of miles away from the user just by
connecting with the Internet.
Secure
All the programs in java are run under an area known as the sand box.
Security manager determines the accessibility options of a class like reading and
writing a file to the local disk.
Java uses the public key encryption system to allow the java applications to transmit
over the internet in the secure encrypted form.
Performance
Java uses native code usage, and lightweight process called threads.
In the beginning interpretation of bytecode resulted the performance slow but the
advance version of JVM uses the adaptive and just in time compilation technique
that improves the performance.
Interpreted
The interpreter program reads the source code and translates it on the fly into
computations. Thus, Java as an interpreted language depends on an interpreter
program.
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
Dynamic Linking:-
Java supports a novel paradigm for code deployment: Instead of linking a complete
program before execution, the classes and interfaces making up the program are
loaded and linked on demand during execution.
Classes are verified before the creation of objects. Verification checks subtypes, and
may require loading of further classes or interfaces.
When you compile a Java program, you get a separate class file for each class or
interface in your program.
As your program runs, the Java virtual machine builds an internal web of
interconnected classes and interfaces.
The Java linking model is more complex than that usually found in programming
languages.
Advantages:
The main use of garbage collection is to identify and discard objects that are no
longer needed by a program so that their resources can be reclaimed and reused.
If successfully compiled, the resultant .class file is passed to the Java Virtual
Machine (java.exe) for execution.
The act of compiling has a two-fold effect: Firstly, the code is checked for syntax
errors and secondly, the code is converted to byte codes.
The byte codes are instructions for an imaginary machine called the Java Virtual
Machine (JVM).
This machine is emulated by all Java interpreters and therefore allows you to
execute a compiled Java program among different platforms (operating systems
with a JVM).
ByteCode
Java bytecode is the form of instructions that the Java virtual machine executes.
Each bytecode is one byte in length, although some require parameters, resulting in
some multi-byte instructions.
The byte code format is same on all platforms as it runs in the same JVM and it is
totally independent from the operating system and CPU architecture.
JVM:-
It is the principal component of Java architecture that provides the cross platform
functionality and security to Java.
This is a software process that converts the compiled Java byte code to machine
code.
Byte code is an intermediary language between Java source and the host system.
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
Most programming language like C and Pascal translate the source code into
machine code for one specific type of machine as the machine language vary from
system to system. So most complier produce code for a particular system but Java
compiler produce code for a virtual machine.
The translation is done in two steps. First the programs written in Java or the source
code translated by Java compiler into byte code and after that the JVM converts the
byte code into machine code for the computer one wants to run.
So the programs files written in Java are stored in .java files and the .java files are
compiled by the Java compiler into byte code that are stored in .class file. The JVM
later convert it into machine code.
In fact the byte code format is same on all platforms as it runs in the same JVM and it
is totally independent from the operating system and CPU architecture.
JVM is a part of Java Run Time Environment that is required by every operating
system requires a different JRE.
JRE consists of a number of classes based on Java API and JVM, and without JRE, it is
impossible to run Java.
Comments
Types of Comments
There are two types of comments.
1) double-slash (//) comment.
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
The slash-star comment mark tells the compiler to ignore everything that follows
until it finds a star-slash (*/) comment mark.
System.out.println(“String”);
Println(“String”) is the method in class System which is used to print any message
on the console.
Eg:
System.out.println(“Hello World !!!”);
The above statement print the message Hello World !!! on the console.
VARIABLES
Variables are a way of reserving memory to hold some data and assign names to
them so that we don't have to remember the numbers like 46735 and instead we
can use the memory location by simply referring to the variable.
It specifies that there are three variables v1, v2, v3 (named by programmer) and
have assigned
the memory locations 32000, 12456 and 67893.
These memory locations are not their values. The values of the variables are what
you assign to them. You can assign value 86 to v1, 32.45 to v2 and 'a' to v3.
Literal
A constant value in a program is denoted by a literal. Literals represent numerical
(integer or floating-point), character, boolean or string values.
Example of literals:
Integer literals:
33 0 -9
Floating-point literals:
.3 0.3 3.14
Character literals:
'(' 'R' 'r' '{'
String literals:
"language" "0.2" "r" ""
Integer Literals
Integer literals is a sequence of digits and a suffix as L.
To represent the type as long integer we use L as a suffix.
We can specify the integers either in decimal, hexadecimal or octal format.
To indicate a decimal format put the left most digit as nonzero. Similarly put the
characters as ox to the left of at least one hexadecimal digit to indicate hexadecimal
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
format. Also we can indicate the octal format by a zero digit followed by the digits 0
to 7. Eg.
Decimal integer literal of
659L
type long integer
Hexadecimal integer
0x4a
literal of type integer
Octal integer literal of
057L
type long integer
Character Literals
We can specify a character literal as a single printable character in a pair of single
quote characters such as 'a', '#', and '3'.
You must be knowing about the ASCII character set. The ASCII character set includes
128 characters including letters, numerals, punctuations etc.
There are few character literals which are not readily printable through a keyboard.
The table below shows the codes that can represent these special characters. The
letter d such as in the octal, hex etc represents a number.
Escape Meaning
\n New line
\t Tab
\b Backspace
Carriage
\r
return
\f Formfeed
\\ Backslash
Single
\' quotation
mark
Double
\" quotation
mark
\d Octal
\xd Hexadecimal
Unicode
\ud
character
Boolean Literals
The values true and false are also treated as literals in Java programming.
When we assign a value to a boolean variable, we can only use these two values.
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
Floating-point literals
Floating-point numbers are like real numbers in mathematics, for example, 4.13179,
-0.000001.
Java has two kinds of floating-point numbers: float and double.
The default type when you write a floating-point literal is double.
Type Size Range Precision
name bytes bits approximate in decimal digits
float 4 32 +/- 3.4 * 1038 6-7
double 8 64 +/- 1.8 * 10308 15
A floating-point literal can be denoted as a decimal point, a fraction part, an
exponent (represented by E or e) and as an integer.
We also add a suffix to the floating point literal as D, d, F or f.
The type of a floating-point literal defaults to double-precision floating-point.
The following floating-point literals represent double-precision floating-point and
floating-point values.
6.5E+32 Double-precision
(or 6.5E32) floating-point literal
Double-precision
7D
floating-point literal
Floating-point
.01f
literal
String Literals
The string of characters is represented as String literals in Java.
In Java a string is not a basic data type, rather it is an object.
These strings are not stored in arrays as in C language.
There are few methods provided in Java to combine strings, modify strings and to
know whether to strings have the same value.
Null Literals
The final literal that we can use in Java programming is a Null literal.
We specify the Null literal in the source code as 'null'.
To reduce the number of references to an object, use null literal.
The type of the null literal is always null. We typically assign null literals to object
reference variables. For instance
s = null;
Data Types
45 -932 0 12 5421
Floating-point numbers contain decimal points. They are known as real numbers to
mathematicians.
All the following expressions are floating-point numbers, and any floating-point
variable can hold them:
Type Range*
2 - Operators In Java
Operator:
Operators are symbols which take one or more operands or expressions and perform
arithmetic or logical computations.
These operators generally work on many types of variables or constants, though some are
restricted to work on certain types. Most operators are binary, meaning they take two
operands.
Assignment Operator
For example:
x = 5;
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
By following the right to left rule the value 5 is assigned to the variable x in the above
assignment statement.
Arithmetic operators
• + For addition
• - For subtraction
• * For multiplication
• / For division
• % For modulo
Example:
class Add
{
public static void main(String args[])
{
int n1 = 3;
int n2 = 6;
}
else
{
diff = n2 - n1;
System.out.println("Sum="+sum);
System.out.println("Difference="+diff);
System.out.println("Division="+div);
System.out.println("Modulas="+mod);
}
}
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
• In the case that the increment or decrement operator is used as a prefix ( ++a or –a),
then the value is respectively increased or decreased before the result of the expression is
evaluated.
• Therefore, the increased or decreased value, respectively, is considered in the outer
expression.
• In the case that the increment or decrement operator is used as a postfix (a++ or a--
), then the value stored in a is respectively increased or decreased after being evaluated.
• Therefore, the value stored before the increase or decrease operation is evaluated in
the outer expression.
For Example:
y=3;
x=++y; //Prefix : Here Value of x becomes 4
Example:
/* Program to demonstrates the increment operator*/
class IncDec
{
public static void main(String args[])
{
int a = 10;
int b = 20;
int c,d;
c = ++b;
d = a++;
System.out.println("a = "+a);
System.out.println("b = "+b);
System.out.println("c = "+c);
System.out.println("d = "+d);
}
}
• These operators are used for evaluating a comparison between two expressions.
• The value returned by the relational operation is a Boolean value (true or false
value).
The operators used for this purpose in JAVA are:
Relational and equality operators ( ==, !=, >, <, >=, <= )
In order to evaluate a comparison between two expressions we can use the relational and
equality operators. The result of a relational operation is a Boolean value that can only be
true or false, according to its Boolean result.
We may want to compare two expressions, for example, to know if they are equal or if one
is greater than the other is. Here is a list of the relational and equality operators that can be
used in JAVA:
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
Of course, instead of using only numeric constants, we can use any valid expression,
including variables. Suppose that a=2, b=3 and c=6,
(a == 5) // evaluates to false since a is not equal to 5.
(a*b >= c) // evaluates to true since (2*3 >= 6) is true.
(b+4 > a*c) // evaluates to false since (3+4 > 2*6) is false.
((b=2) == a) // evaluates to true.
Note:-
The operator = (one equal sign) is not the same as the operator == (two equal signs), the
first one is an assignment operator (assigns the value at its right to the variable at its left)
and the other one (==) is the equality operator that compares whether both expressions in
the two sides of it are equal to each other. Thus, in the last expression ((b=2) == a), we first
assigned the value 2 to b and then we compared it to a, that also stores the value 2, so the
result of the operation is true.
• The operands are implicitly converted to type bool prior to evaluation, and the
result is of type bool. Logical AND has left-to-right associativity.
• The operands to the logical AND operator need not be of the same type, but they
must be of integral or pointer type.
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
• The Operator ! is the JAVA operator to perform the Boolean operation NOT, it has
only one operand, located at its right, and the only thing that it does is to inverse the value
of it, producing false if its operand is true and true if its operand is false.
• Basically, it returns the opposite Boolean value of evaluating its operand. For
example:
!(5 == 5) // evaluates to false because the expression at its right (5 == 5) is true.
!(6 <= 4) // evaluates to true because (6 <= 4) would be false.
!true // evaluates to false
!false // evaluates to true.
• The logical operators && and || are used when evaluating two expressions to obtain
a single relational result.
• The operator && corresponds with Boolean logical operation AND.
• This operation results true if both its two operands are true, and false otherwise.
• The following panel shows the result of operator && evaluating the expression a &&
b:
&& OPERATOR
a b a && b
true true True
true false False
false true False
false false False
• The operator || corresponds with Boolean logical operation OR.
• This operation results true if either one of its two operands is true, thus being false
only when both operands are false themselves.
• Here are the possible results of a || b:
|| OPERATOR
A B a || b
True true true
True false true
false true true
false false false
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
For example:
( (5 == 5) && (3 > 6) ) // evaluates to false ( true && false ).
( (5 == 5) || (3 > 6) ) // evaluates to true ( true || false ).
Conditional operator (: ? )
• The conditional operator evaluates an expression returning a value if that
expression is true and a different one if the expression is evaluated as false. Its format is:
condition ? result1 : result2
If condition is true the expression will return result1, if it is not it will return result2.
7==5 ? 4 : 3 // returns 3, since 7 is not equal to 5.
7==5+2 ? 4 : 3 // returns 4, since 7 is equal to 5+2.
5>3 ? a : b // returns the value of a, since 5 is greater than 3.
a>b ? a : b // returns whichever is greater, a or b. // conditional operator
Example:
class ConditionalOpt
{
public static void main(String args[])
{
int n1 = 5;
int n2 = 3;
}
}
o/p :Greater Number= 5
Comma operator ( , )
• The comma operator (,) is used to separate two or more expressions that are
included where only one expression is expected.
• When the set of expressions has to be evaluated for a value, only the rightmost
expression is considered.
For example, the following code:
a = (b=3, b+2);
• Would first assign the value 3 to b, and then assign b+2 to variable a. So, at the end,
variable a would contain the value 5 while variable b would contain value 3.
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
Bitwise AND
Bitwise OR
• Bitwise OR works almost exactly the same way as bitwise AND.
• The only difference is that only one of the two bits needs to be a 1 for that position's
bit in the result to be 1. (If both bits are a 1, the result will also have a 1 in that position.)
• The symbol is a pipe: |. Again, this is similar to boolean logical operator, which is ||.
01001000 |
10111000 =
--------
11111000
and consequently
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
72 | 184 = 248
The Bitwise Complement
• The bitwise complement operator, the tilde, ~, flips every bit.
• A useful way to remember this is that the tilde is sometimes called a twiddle, and
the bitwise complement twiddles every bit: if you have a 1, it's a 0, and if you have a 0, it's a
1.
• This turns out to be a great way of finding the largest possible value for an unsigned
number:
unsigned int max = ~0;
Bitwise Exclusive-Or (XOR)
• There is no boolean operator counterpart to bitwise exclusive-or, but there is a
simple explanation.
• The exclusive-or operation takes two inputs and returns a 1 if either one or the
other of the inputs is a 1, but not if both are.
• That is, if both inputs are 1 or both inputs are 0, it returns 0. Bitwise exclusive-or,
with the operator of a carrot, ^, performs the exclusive-or operation on each pair of bits.
Exclusive-or is commonly abbreviated XOR.
• For instance, if you have two numbers represented in binary as 10101010 and
01110010 then taking the bitwise XOR results in 11011000. It's easier to see this if the bits
are lined up correctly:
01110010 ^
10101010
--------
11011000
Example
class BitwiseOpt
{
public static void main(String args[])
{
int n1 = 110;
int n2 = 101;
System.out.println(n1 & n2);
System.out.println(n1 | n2);
System.out.println(~n2);
System.out.println(n1 ^ n2);
}
}
o/p:100 111 010 011
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
• Type casting operators allow you to convert a datum of a given type to another.
• There are several ways to do this in JAVA.
• The simplest one, which has been inherited from the C language, is to precede the
expression to be converted by the new type enclosed between parentheses (()):
int i;
float f = 3.14;
i = (int) f;
• The previous code converts the float number 3.14 to an integer value (3), the
remainder is lost. Here, the typecasting operator was (int).
• Another way to do the same thing in JAVA is using the functional notation:
preceding the expression to be converted by the type and enclosing the expression
between parentheses:
i = int ( f );
3 - Control Statements
The if Statement
• Like most languages, JAVA uses the keyword if to implement the decision control
instruction.
• The general form of if statement looks like this:
if(conditions)
{
//body of the statements;
}
• The keyword if tells the compiler that what follows is a decision control instruction.
• The condition following the keyword if is always enclosed within a pair of
parentheses.
• If the condition, whatever it is, is true, then the statement is executed.
• If the condition is not true then the statement is not executed; instead the program
skips past it.
Expression is true if
x == y x is equal to y
x != y x is not equal to y
x < y x is less than y
x > y x is greater than y
x <= y x is less than or equal to y
x >= y x is greater than or equal to y
statement-x;
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
Example:
class SimpleIf
{
public static void main(String args[])
{
int num = Integer.parseInt(args[0]);
}
}
else
{
// body of else statement;
}
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
Example:
class IfElseDemo
{
public static void main(String args[])
{
int num = Integer.parseInt(args[0]);
int r = num % 2;
if(r == 0)
{
System.out.println("Even Number");
}
else
{
System.out.println("Odd Number");
}
}
}
The if-else statement allows a choice to be made between two possible alternatives.
Sometimes a choice must be made between more than two possibilities. For
example the sign function in mathematics returns -1 if the argument is less than
zero, returns +1 if the argument is greater than zero and returns zero if the
argument is zero. The following JAVA statement implements this function:
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
if (x < 0)
sign = -1;
else
if (x == 0)
sign = 0;
else
sign = 1;
This is an if-else statement in which the statement following the else is itself an if-
else statement.
If x is less than zero then sign is set to -1,
however if it is not less than zero the statement following the else is executed. In
that case if x is equal to zero then sign is set to zero and otherwise it is set to 1.
When writing nested if-else statements to choose between several alternatives use some
consistent layout such as the following:
if ( condition1 )
statement1 ;
else if ( condition2 )
statement2 ;
...
else if ( condition-n )
statement-n ;
else
statement-e ;
Example:
class NestedIfDemo
{
public static void main(String args[])
{
int n1 = Integer.parseInt(args[0]);
int n2 = Integer.parseInt(args[1]);
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
int n3 = Integer.parseInt(args[2]);
Break:-
• The break statement ends execution of the nearest enclosing loop or conditional
statement in which it appears.
• Control passes to the statement that follows the ended statement, if any.
break;
• The break statement is used with the conditional switch statement and with the do,
for, and while loop statements.
• In a switch statement, the break statement causes the program to execute the next
statement after the switch statement. Without a break statement, every statement from the
matched case label to the end of the switch statement, including the default clause, is
executed.
• In loops, the break statement ends execution of the nearest enclosing do, for, or
while statement. Control passes to the statement that follows the ended statement, if any.
• Within nested statements, the break statement ends only the do, for, switch, or
while statement that immediately encloses it. You can use a return or goto statement to
transfer control from more deeply nested structures.
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
Continue:
The continue statement passes control to the next iteration of the nearest enclosing do, for,
or while statement in which it appears, bypassing any remaining statements in the do, for,
or while statement body.
Syntax
jump-statement:
continue;
The next iteration of a do, for, or while statement is determined as follows:
• Within a do or a while statement, the next iteration starts by reevaluating the
expression of the do or while statement.
• A continue statement in a for statement causes the first expression of the for
statement to be evaluated. Then the compiler reevaluates the conditional expression and,
depending on the result, either terminates or iterates the statement body. See The for
Statement for more information on the for statement and its nonterminals.
Switch Statements
• You saw how to write if and if/else statements.
• These can become quite confusing when nested too deeply, and JAVA offers an
alternative.
• Unlike if, which evaluates one value, switch statements allow you to branch on any
of a number of different values.
• The general form of the switch statement is:
switch (option)
{
case valueOne: statement;
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
break;
case valueTwo:
statement;
break;
....
case valueN:
statement;
break;
default:
statement;
break;
}
• option is any legal JAVA expression, and the statements are any legal JAVA
statements or block of statements.
• switch evaluates expression and compares the result to each of the case values.
Note, however, that the evaluation is only for equality; relational operators may not be
used here, nor can Boolean operations.
• If one of the case values matches the expression, execution jumps to those
statements and continues to the end of the switch block, unless a break statement is
encountered.
• If nothing matches, execution branches to the optional default statement.
• If there is no default and there is no matching value, execution falls through the
switch statement and the statement ends.
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
4 - Loops In JAVA
Types Of Loops.
Example:
class WhileDemo
{
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
int j=10;
System.out.println();
while(j >= 1)
{
System.out.print(j+"\t");
j--;
}
}
}
Do-while Loop:-
initialization;
do
{
//body of do-while loop;
Increament/Decreament;
}while(condition);
Eg
int i=1;
do
{
System.out.println(i);
i++;
}while(i<=10);
Example: Example:
int i=1;
int i=1; do
{
while(i <= 10) System.out.println(i);
{ i++;
System.out.print(i+"\t"); }while(i<=10);
i++;
}
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
For loop:-
The for loop is used to execute same sequence of statements for the predetermined number
of times. The general form of the for loop is: -
Syntex:-
for(initialization;condition;increament/decreament)
{
//body of for loop;
}
1- Initialization (Assingment operator "=")
2- Condition (Relationan Operator )
3- Increament/Decreament (Increament and Decreament operator "++" and "--")
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
Example:-
for(int i=1;i<=10;i++)
{
System.out.println(i);
}
Program List
WAP to find the factorial of number entered by the user?
class FactDemo
{
public static void main(String args[])
{
int num = Integer.parseInt(args[0]);
while(num > 0)
{
fact = fact * num;
num--;
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
/*
for(int i=1;i<=num;i++)
{
fact = fact * i;
}
*/
/*
for(int j=num;j>0;j--)
{
fact = fact * j;
}
*/
System.out.println("Facttorial="+fact);
}
}
for(int i=1;i<=num;i++)
{
int fact = 1;
for(int j=1;j<=i;j++)
{
fact = fact * j;
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
}
System.out.println(i+" "+fact+" ");
}
}
}
while(num > 0)
{
int r = num % 10;
rev = (rev * 10) + r;
num = num / 10;
}
System.out.println("Reverse="+rev);
if(rev == temp)
{
System.out.println("Pallindrome Number");
}
else
{
System.out.println("Not a Pallindrome");
}
}
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
for(int i=1;i<=num;i++)
{
int count = 0; // Note
for(int j=2;j<i;j++)
{
if(i%j == 0)
{
count++;
break;
}
}
if(count == 0)
{
System.out.println(i+" ");
}
}
}
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
if(sum == temp)
{
System.out.println("Armstrong Number");
}
else
{
System.out.println("Not a Armstrong Number");
}
}
}
WAP to generate the Fibonacci series between 0 to till the range entered by the user?
class FibDemo
{
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
int s = 1;
System.out.print(f+" ");
System.out.print(s+" ");
for(int i=3;;i++)
{
int next = f + s;
if(next > num)
{
break;
}
else
{
System.out.print(next+" ");
f = s;
s = next;
}
}
}
}
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
/*
WAP to print
*
**
***
****
*****
*/
class Patter1
{
public static void main(String args[])
{
for(int i=1;i<=10;i++)
{
for(int j=1;j<=10;j++)
{
/*
WAP to print
*****
****
***
**
*
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
*/
class Patter2
{
public static void main(String args[])
{
for(int i=5;i>0;i--)
{
for(int j=1;j<=i;j++)
{
System.out.print("*"+" ");
}
System.out.println();
}
}
}
/*
WAP to print
1
23
456
7 8 9 10
11 12 13 14 15
*/
class Patter3
{
public static void main(String args[])
{
int a=1;
for(int i=1;i<=5;i++)
{
for(int j=1;j<=i;j++)
{
System.out.print(a +" ");
a++;
}
System.out.println();
}
}
}
/*
WAP to print
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
1
01
010
1010
10101
*/
class Patter4
{
public static void main(String args[])
{
int a=1;
for(int i=1;i<=5;i++)
{
for(int j=1;j<=i;j++)
{
System.out.print(a+" ");
a = a *(-1) + 1;
}
System.out.println();
}
}
}
/*
WAP to print
*****
****
***
**
*
*/
class Patter5
{
public static void main(String args[])
{
for(int i=1;i<=5;i++)
{
for(int j=1;j<i;j++)
{
System.out.print(" ");
}
for(int k=i;k<=5;k++)
{
System.out.print("*"+" ");
}
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
System.out.println();
}
}
}
/*
WAP to print
*****
*****
*****
*****
*****
*/
class Patter1
{
public static void main(String args[])
{
for(int i=1;i<=10;i++)
{
for(int j=1;j<=10;j++)
{
{
public static void main(String args[])
{
double a , b , c , d , e ;
double temp , r1 , r2 ;
int select ;
a=2;b=3;c=6;
temp = (b * b) - (4 * a * c) ;
if (temp > 0)
select = 0 ;
else
if (temp == 0)
select = 1 ;
else
select = 2 ;
switch (select)
{
case 0 :
temp = Math.sqrt (temp) ;
r1 = (-b + temp) / (2 * a) ;
r2 = (-b - temp) / (2 * a) ;
System.out.println("The roots are Real and Unequal.\n");
System.out.println("The roots are : "+r1+" "+r2);
break ;
case 1 :
r1 = -b / (2 * a) ;
r2 = r1 ;
System.out.println("The roots are Real and Equal.\n");
System.out.println("The roots are : "+r1+" "+r2);
break ;
case 2 :
temp = -temp ;
temp = Math.sqrt (temp) ;
temp = temp / (2 * a) ;
r1 = -b / (2 * a) ;
System.out.println("The roots are Real and Imaginary.\n");
System.out.println("The roots are : "+r1+"+ j"+temp+" , "+r1+"- j"+temp);
break ;
}
}
}
/*
program to print
A B C D C B A
A B C B A
A B A
A
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
*/
class Pattern
{
public static void main(String args[])
{
int i=0,j=6,k=0;
char x='A';
while((j/2)>=0)
{
for(i=0;i<=(j/2);i++)
System.out.print(" "+((char)(x+i)));
i=i-2;
for(;i>=0;i--)
System.out.print(" "+((char)(x+i)));
j=j-2;
k=k+1;
System.out.print("\n");
for(i=0;i<=k;i++)
System.out.print(" ");
}
}
}
WAP to accept a number from the user and check whether it is prime or not?
class PrimeDemo
{
public static void main(String args[])
{
int num = Integer.parseInt(args[0]);
int count = 0;
for(int i=2;i<=num/2;i++)
{
if(num % i == 0)
{
count++;
break;
}
}
if(count == 0)
{
System.out.println("Prime Number");
}
else
{
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
WAP to accept a number from the user and find the reverse of that number?
class Reverse
{
public static void main(String args[])
{
int intNum = Integer.parseInt(args[0]);
int rev = 0;
/*
for(;intNum>0;)
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
{
int r = intNum % 10;
rev = rev * 10 + r;
*/
while(intNum > 0)
{
int r = intNum % 10;
rev = rev * 10 + r;
}
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
Arrays
An array is a data structure consisting of a numbered list of items, where all the items are
of the same type.
Array is a collection of similar data with same name...
Array is a user defined reference data type...
In Java, the items in an array are always numbered from zero up to some maximum
value, which is set when the array is created. For example, an array might contain 10
integers, numbered from zero to 9.
The items in an array can belong to one of Java's primitive types. They can also be
references to objects.
The length of an array is established when the array is created. After creation, its length is
fixed.
DataType: Determines the type of the value that array should store (int,float etc)
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
Steps:
1) Declaration Of an Array.
2) Initialization of an Array.
3) Displaying Array Elements.
1) Declaration Of an Array.
This step is achieved by using syntax as follows.
Initialization of an Array.
This step is achieved by using assignment operator.
num[0] = 1;
num[1] = 2;
num[2] = 3;
num[3] = 11;
num[4] = 33;
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
// Second Way
If this statement were missing, the compiler would print an error like the following, and
compilation would fail:
The next few lines assign values to each element of the array:
anArray[0] = 100; // initialize first element
anArray[1] = 200; // initialize second element
anArray[2] = 300; // etc.
Each array element is accessed by its numerical index:
System.out.println("Element 1 at index 0: " + anArray[0]);
System.out.println("Element 2 at index 1: " + anArray[1]);
System.out.println("Element 3 at index 2: " + anArray[2]);
Alternatively, you can use the shortcut syntax to create and initialize an array:
int[] anArray = {100, 200, 300, 400, 500, 600, 700, 800, 900, 1000};
Here the length of the array is determined by the number of values provided
between { and }.
class Array1
{
public static void main(String args[])
{
/*
int num[] = new int[5];
num[0] = 1;
num[1] = 2;
num[2] = 3;
num[3] = 11;
num[4] = 33;
*/
// OR
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
System.out.println("Length="+len);
for(int i=0;i<num.length;i++)
{
System.out.println("Array Index "+i+" "+num[i] );
}
}
}
When an array declaration uses two subscript to declare an array then it is called as
two or double dimensional array.
This type of array is used to print or manipulate the matrix structure.
It defines the number of rows and columns as its size.
Syntax:
DtatType Name OfArry[][];
NameOfArry = new DataType[Size1][size2];
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
OR
Where
DataType determines the type of the value that array stored(int,float double etc).
NameOfArray is any user defined name.
new operator is used to allocate the memory for array elements.
Size1 refers to the rows.
Size2 refers to the columns.
Example:
/*
Two Dimensional Array:
when array decleration uses two subscript to declare an array then it is called as two
dimensional array...
datatype[][] ArrayName = new datatype[size][size1];
int[][] intNum = new int[2][2];
*/
class TwoDArray
{
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
// Creating an array
/*
intNum[0][0] = 3;
intNum[0][1] = 3;
intNum[1][0] = 3;
intNum[1][1] = 3;
*/
int[][] intNum = {
{3,3,5},
{4,5,6},
{4,5,6}
};
for(int i=0;i<intNum.length;i++)
{
for(int j=0;j<intNum.length;j++)
{
System.out.print(intNum[i][j]+" ");
}
System.out.println();
}
}
}
class TwoDArrayUserInput
{
public static void main(String args[]) throws IOException
{
int[][] intNum = new int[2][2]; //Decleration Of Array...
intNum[i][j] = Integer.parseInt(br.readLine());
}
}
for(int i=0;i<intNum.length;i++)
{
for(int j=0;j<intNum.length;j++)
{
System.out.print(intNum[i][j]+" ");
}
System.out.println();
}
}
}
Addition Of Matrix:
import java.io.*;
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
class AddMatrix
{
public static void main(String args[]) throws IOException
{
int[][] intNum1 = new int[2][2];
intNum1[i][j] = Integer.parseInt(br.readLine());
}
}
intNum2[i][j] = Integer.parseInt(br.readLine());
}
}
System.out.println("First Matrix:");
for(int i=0;i<intNum1.length;i++)
{
for(int j=0;j<intNum1.length;j++)
{
System.out.print(intNum1[i][j]+" ");
}
System.out.println();
}
System.out.println("Second Matrix:");
for(int i=0;i<intNum2.length;i++)
{
for(int j=0;j<intNum2.length;j++)
{
System.out.print(intNum2[i][j]+" ");
}
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
System.out.println();
}
for(int i=0;i<intNum2.length;i++)
{
for(int j=0;j<intNum2.length;j++)
{
intSum[i][j] = intNum1[i][j] + intNum2[i][j];
}
}
System.out.println("Sum Of Matrix:");
for(int i=0;i<intNum2.length;i++)
{
for(int j=0;j<intNum2.length;j++)
{
System.out.print(intSum[i][j]+" ");
}
System.out.println();
}
}
}
import java.io.*;
class SumOfDiagonal
{
public static void main(String args[]) throws IOException
{
int[][] intNum1 = new int[2][2];
intNum1[i][j] = Integer.parseInt(br.readLine());
}
}
System.out.println("First Matrix:");
for(int i=0;i<intNum1.length;i++)
{
for(int j=0;j<intNum1.length;j++)
{
System.out.print(intNum1[i][j]+" ");
}
System.out.println();
}
int sum = 0;
for(int i=0;i<intNum1.length;i++)
{
for(int j=0;j<intNum1.length;j++)
{
if(i == j)
{
sum = sum + intNum1[i][j];
}
}
}
Multidimensional array
Finally, you can use the built-in length property to determine the size of any array. The
code
System.out.println(anArray.length);
will print the array's size to standard output.
import java.io.*;
class ArrayInput
{
for(int i=0;i<intNum.length;i++)
{
System.out.println("Array Element="+i+" "+intNum[i]);
}
}
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
/*
WAP to accept 10 numbers from the user and find the largest of 10 number ?
*/
import java.io.*;
class Large5Num
{
for(int i=0;i<intNum.length;i++)
{
System.out.println("Array Element="+i+" "+intNum[i]);
}
for(int i=1;i<intNum.length;i++)
{
if(intLarge < intNum[i])
{
intLarge = intNum[i];
}
}
System.out.println("Largest Number="+intLarge);
}
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
import java.io.*;
class BubbleSort
{
public static void main(String args[]) throws IOException
{
int[] intNum = new int[5]; // Decleration Of Array
for(int i=0;i<intNum.length;i++)
{
for(int j=i+1;j<intNum.length;j++)
{
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
Strings
The String class represents character strings. All string literals in Java programs, such as
"abc", are implemented as instances of this class.
Strings are constant; their values cannot be changed after they are created. String buffers
support mutable strings. Because String objects are immutable they can be shared. For
example:
String str = "abc";
is equivalent to:
char data[] = {'a', 'b', 'c'};
String str = new String(data);
CONSTRUCTORS
String() Initializes a newly created String object so that
it represents an empty character sequence.
String(char chars[] ) Constructs a new String by decoding the
specified array of bytes using the platform's
default charset.
String(char chars[], int startIndex, int numChars) Creates a string with start index and number of
Characters.
String(String obj) Creates the string with specified object obj.
Methods:
charAt(int index)
Char Returns the character at the specified index.
Int compareTo(String anotherString)
Compares two strings lexicographically.
Int compareToIgnoreCase(String str)
Compares two strings lexicographically, ignoring case differences.
Address :- 1244/3 Shinde House, Barkat Ali Dargah Road, Wadala(E) Mumbai-37
Prof. Shahid Ansari(9821-77-1054)
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
int length()
Returns the length of this string.
String
replace(char oldChar, char newChar)
Returns a new string resulting from replacing all occurrences of oldChar in this
string with newChar.
Address :- 1244/3 Shinde House, Barkat Ali Dargah Road, Wadala(E) Mumbai-37
Prof. Shahid Ansari(9821-77-1054)
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
boolean
startsWith(String prefix, int toffset)
Tests if this string starts with the specified prefix beginning a specified index.
String
toLowerCase()
Converts all of the characters in this String to lower case using the rules of the
default locale.
String toString()
This object (which is already a string!) is itself returned.
String
toUpperCase()
Converts all of the characters in this String to upper case using the rules of the
default locale.
String
trim()
Returns a copy of the string, with leading and trailing whitespace omitted.
Example:
class StringDemo
{
public static void main(String args[])
{
Address :- 1244/3 Shinde House, Barkat Ali Dargah Road, Wadala(E) Mumbai-37
Prof. Shahid Ansari(9821-77-1054)
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
System.out.println("Str="+str);
System.out.println("Str1="+str1);
System.out.println("Str2="+str2);
System.out.println("Str="+str);
System.out.println(str5.trim());
}
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
StringBuffer Class:
Constructors:
StringBuffer()
Constructs a string buffer with no characters in it and an initial capacity of 16 characters.
StringBuffer(int length)
Constructs a string buffer with no characters in it and an initial capacity specified by the
length argument.
StringBuffer(String str)
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
Constructs a string buffer so that it represents the same sequence of characters as the
string argument; in other words, the initial contents of the string buffer is a copy of the
argument string.
Methods
StringBuffer append(boolean b)
Appends the string representation of the boolean argument to the
sequence.
StringBuffer append(char c)
Appends the string representation of the char argument to this sequence.
StringBuffer append(char[] str)
Appends the string representation of the char array argument to this
sequence.
StringBuffer append(char[] str, int offset, int len)
Appends the string representation of a subarray of the char array
argument to this sequence.
StringBuffer append(double d)
Appends the string representation of the double argument to this
sequence.
StringBuffer append(float f)
Appends the string representation of the float argument to this sequence.
StringBuffer append(int i)
Appends the string representation of the int argument to this sequence.
StringBuffer append(long lng)
Appends the string representation of the long argument to this sequence.
StringBuffer append(Object obj)
Appends the string representation of the Object argument.
StringBuffer append(String str)
Appends the specified string to this character sequence.
StringBuffer append(StringBuffer sb)
Appends the specified StringBuffer to this sequence.
StringBuffer appendCodePoint(int codePoint)
Appends the string representation of the codePoint argument to this
sequence.
int capacity()
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
Example:
class StringBufferDemo1
{
public static void main(String args[])
{
System.out.println("String="+sb);
System.out.println("Capacity="+sb.capacity());
System.out.println("String="+sb1);
System.out.println("Capacity="+sb1.capacity());
System.out.println("String="+sb3);
System.out.println("Capacity="+sb3.capacity());
// ******Methods******
obj = "ABCDEFGH".toString();
sb.append(obj);
System.out.println("String="+sb);
System.out.println("Length Of sb="+sb.length());
System.out.println("Capacity="+sb.capacity());
System.out.println("Reverse="+sb5.reverse());
sb3.delete(2,8);
System.out.println("String After Deletion="+sb3);
System.out.println("After Insertion="+sb6);
}
}
Copying Arrays
The System class has an arraycopy method that you can use to efficiently copy data
from one array into another:
The following program, ArrayCopyDemo, declares an array of char elements, spelling the
word "decaffeinated". It uses arraycopy to copy a subsequence of array components into a
second array:
class ArrayCopyDemo {
public static void main(String[] args) {
char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e',
'i', 'n', 'a', 't', 'e', 'd' };
char[] copyTo = new char[7];
Array of Objects
A 2D array of objects is an array of an array of references to objects:
7 - Exception Handling
The term exception is shorthand for the phrase "exceptional event."
Definition: An exception is an event, which occurs during the execution of a program, that
disrupts the normal flow of the program's instructions.
When an error occurs within a method, the method creates an object and hands it off to
the runtime system.
The object, called an exception object, contains information about the error, including its
type and the state of the program when the error occurred.
Creating an exception object and handing it to the runtime system is called throwing an
exception.
After a method throws an exception, the runtime system attempts to find something to
handle it.
The set of possible "somethings" to handle the exception is the ordered list of methods
that had been called to get to the method where the error occurred.
The list of methods is known as the call stack (see the next figure).
The runtime system searches the call stack for a method that contains a block of code that
can handle the exception. This block of code is called an exception handler.
The search begins with the method in which the error occurred and proceeds through the
call stack in the reverse order in which the methods were called.
When an appropriate handler is found, the runtime system passes the exception to the
handler.
An exception handler is considered appropriate if the type of the exception object thrown
matches the type that can be handled by the handler.
The exception handler chosen is said to catch the exception.
If the runtime system exhaustively searches all the methods on the call stack without
finding an appropriate exception handler, as shown in the next figure, the runtime system
(and, consequently, the program) terminates.
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
………………..
……………….
}
try{
System.out.println("inside procA");
throw new RuntimeException("demo");
}finally{
System.out.println("procA's finally");
}
}
try{
System.out.println("inside procB");
return;
}
finally{
System.out.println("procB's finally");
}
}
try{
System.out.println("inside procC");
}
finally{
System.out.println("procC's finally");
}
}
try{
procA();
}catch(Exception e){
System.out.println("Exception caught");
procB();
procC();
Output Screen:
inside procA
procA's finally
Exception caught
inside procB
procB's finally
inside procC
Throws Keyword:-
throws " is a keyword defined in the java programming language. Keywords are basically
reserved words which have specific meaning relevant to a compiler in java programming
language likewise the throw keyword indicates the following :
The throws keyword in java programming language is applicable to a method to indicate
that the method raises particular type of exception while being processed.
-- The throws keyword in java programming language takes arguments as a list of the
objects of type java.lang.Throwables class.
-- when we use the throws with a method it is known as ducking. The method calling a
method with a throws clause is needed to be enclosed within the try catch blocks.
Example to use the throws keyword in a class:
import java.io.IOException;
public class Class1{
public method readingFile(String file)
throws IOException{
<statements>
if (error){
throw new IOException("error
reading file");
}
}
}
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
Objects:
An Object is a collection of data members and associated member functions also known as
methods.
Syntax:
Class_Name Object_Name;
Object_Name = new Class_Name();
OR
Class_Name Object_Name= new Class_Name();
Example:
Suppose the class name is Student then
Student s = new Student();
Classes:
Classes are data types based on which objects are created.
Objects with similar properties and methods are grouped together to form a Class.
Thus a Class represent a set of individual objects.
Characteristics of an object are represented in a class as Properties.
The actions that can be performed by objects becomes functions of the class and is
referred to as Methods.
For example consider we have a Class of Cars under which Santro Xing, Alto and WaganR
represents individual Objects. In this context each Car Object will have its own, Model, Year of
Manufacture, Colour, Top Speed, Engine Power etc., which form Properties of the Car class and
the associated actions i.e., object functions like Start, Move, Stop form the Methods of Car
Class.
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
No memory is allocated when a class is created. Memory is allocated only when an object is
created, i.e., when an instance of a class is created.
Syntax:
Class Class_Name
{
The keyword ‘private’ is optional if data or functions are not associated with this keyword then
they are assumed as private by default.
The keyword ‘private’ and ‘public’ are called as “Access Specifier”
Private data can only available within the same class.Public data can be accessed outside the
class.
Example:
class student
{
int rollno;
char name[30];
float per;
Example:
class Student
{
public String name ;
public int rollno ;
public float per ;
void display()
{
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
System.out.println("Name="+name);
System.out.println("Roll No="+rollno);
System.out.println("Percentage="+per);
}
}
class StudentDemo
{
public static void main(String args[])
{
Student SObj = new Student();
SObj.input("Junaid",12,99.77F);
SObj.display();
Example:
class Student
{
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
sObj.input("ABC",2,23.77F)
sObj.display();
}
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
Arrays of Objects
import java.util.*;
class Manager
{
int no_of_projects;
String name;
void putData()
{
System.out.println("No_Of_Projects="+no_of_projects);
System.out.println("Manager Name="+name);
}
}
class ManagerDemo
{
public static void main(String args[])
{
Manager[] mObj = new Manager[3];
for(int i=0;i<3;i++)
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
for(int j=0;j<3;j++)
{
mObj[1].putData();
}
}
}
Static data members are not part of objects of a given class type; they are separate
objects.
As a result, the declaration of a static data member is not considered a definition.
The data member is declared in class scope, but definition is performed at file scope.
These static members have external linkage. The following example illustrates this:
It is initialized to zero when the first object of the class is created. On other initialization
is permitted.
Only one copy of that member is created for the entire class and other objects share that
copy.
It is visible only within the class but its life time is in the entire program.
Example:
/*
Static Data Members and Member Functions
*/
class StaticDemo
{
static int count;
int code=7;
void displayCount()
{
System.out.println("Count="+count);
System.out.println("Code="+code);
}
public static void main(String args[])
{
StaticDemo sd = new StaticDemo();
sd.displayCount();
//System.out.println("Code="+code);
System.out.println("Count="+count);
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
Static function is defined by using the keyword static before the member function that is to be
declared as static function.
General syntax:
A static function can have access to only other static data or member declared in the
class.
A static function can be called using class name instead of objects.
A normal member function is accessed using the object and an operator called the dot member
access operator. The functions declared static or static functions are accessed using only the class
name and the scope resolution operator, unlike in normal member functions where these are not
used.
Example:
class StaticMember
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
{
static int code;
int count = 2;
static void display()
{
System.out.println("Code="+code);
}
void show()
{
System.out.println("Count="+count);
System.out.println("Code="+code);
}
}
class StaticMemberTest
{
public static void main(String args[])
{
StaticMember sm = new StaticMember();
StaticMember.display();
sm.show();
}
}
Constructors:
Eample:
class ConsDemo
{
int a,b;
public ConsDemo()
{
a = 0;
b = 1;
}
void show()
{
System.out.println("a="+a);
System.out.println("b="+b);
}
}
class ConsDemoTest
{
cd.show();
}
}
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
Types Of Constructors:
Default Constructors
Parameterized Constructor:
JAVA allows to achieve by passing arguments to the constructor function when the
objects are created.
The construtor that can take arguments are called Parametarized constructor.
Syntax:
class <cname>
{
//data
public: cname(arguments);
.........
.........
};
Examples:
class student
{
char name[20];
int rno;
public: student(char,int);
};
student :: student(char n,int r)
{
name=n;
rno=r;
}
Example:
import java.util.*;
class ParaDemo
{
int a,b;
{
this.a = a;
this.b = b;
}
void show()
{
System.out.println("a="+a);
System.out.println("b="+b);
}
}
class ParaDemoTest
{
public static void main(String args[])
{
this keyword:
The keyword this is useful when you need to refer to instance of the class from its
method.
The keyword helps us to avoid name conflicts.
As we can see in the program that we have declare the name of instance variable and
local variables same.
Now to avoid the confliction between them we use this keyword.
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
Here, this section provides you an example with the complete code of the program for the
illustration of how to what is this keyword and how to use it.
In the example, this.length and this.breadth refers to the instance variable length and breadth
while length and breadth refers to the arguments passed in the method. We have made a program
over this. After going through it you can better understand.
Here is the code of the program:
class Rectangle{
int length,breadth;
void show(int length,int breadth){
this.length=length;
this.breadth=breadth;
}
int calculate(){
return(length*breadth);
}
}
public class UseOfThisOperator{
public static void main(String[] args){
Rectangle rectangle=new Rectangle();
rectangle.show(5,6);
int area = rectangle.calculate();
System.out.println("The area of a Rectangle is : " + area);
}
}
A visible advantage of declaring a java variable as static final is, the compiled java class
results in faster performance.
Before an object is garbage collected, the runtime system calls its finalize() method. The intent is
for finalize() to release system resources such as open files or open sockets before getting
collected.
Function Overloading:-
• Java enables you to create more than one function with the same name.
• This is called function overloading.
• The functions must differ in their parameter list, with a different type of parameter, a
different number of parameters, or both. Here's an example:
is overloaded with three different parameter lists. The first and second versions differ in the types
of the parameters, and the third differs in the number of parameters.
• The return types can be the same or different on overloaded functions.
• You should note that two functions with the same name and parameter list, but different
return types, generate a compiler error.
• Function overloading i s also called function polymorphism. Poly means many, and
morph means form: a polymorphic function is many-formed.
Example:
class OverloaingDemo
{
void add(int num1, int num2)
{
int sum = num1 + num2;
System.out.println("Sum Of Integer Variables=" + sum);
}
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
class TestLoading
{
public static void main(String args[])
{
od.add(5,6);
od.add(5.5,6.6);
}
}
Constructor overloading
If you have constructor with same name and different arguments then its
called constructor overloading.
class Room
{
double length,breadth,height;
Room()
{
length=-1;
breadth=-1;
height=-1;
}
Room(double len)
{
length=breadth=height=len;
}
double volume()
{
return length*breadth*height;
}
Nested classes are divided into two categories: static and non-static. Nested classes that are
declared static are simply called static nested classes. Non-static nested classes are called inner
classes.
class OuterClass {
...
static class StaticNestedClass {
...
}
class InnerClass {
...
}
}
A nested class is a member of its enclosing class.
Non-static nested classes (inner classes) have access to other members of the enclosing class,
even if they are declared private.
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
Static nested classes do not have access to other members of the enclosing class. As a member of
the OuterClass, a nested class can be declared private, public,protected,
Why Use Nested Classes?
There are several reasons for using nested classes, among them:
It is a way of logically grouping classes that are only used in one place.
It increases encapsulation.
Nested classes can lead to more readable and maintainable code.
The inner class has access to the enclosing class instance's variables and methods, even private ones,
as seen above. This makes it very different from the nested class in C++, which are equivalent to the
"static" inner classes, see below.
An inner object has a reference to the outer object. The nested object can only be created with a
reference to the 'outer' object. See below.
Example:
class Outer
{
private int a=1;
class Inner
{
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
void showb()
{
System.out.println("a="+a);
}
}
}
class NestedDemo
{
public static void main(String args[])
{
Outer out1 = new Outer();
Outer.Inner in1 = out1.new Inner();
in1.showb();
}
Visibility control:
Public Members:
Public members can be accessed through any object of the class.
When preceding a list of class members, the public keyword specifies that those members are
accessible from any function. This applies to all members declared up to the next access specifier
or the end of the class.
class A
{
Private Members:
All members of a class--data and methods--are private by default. Private members can be access
ed only within methods of the class itself.
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
class A
{
private int pubFunc()
{
return 0;
}
};
Protected Members:
The protected keyword specifies access to class members in the member-list up to the next
access specifier (public or private) or the end of the class definition. Class members declared
as protected can be used only by the following:
Member functions of the class that originally declared these members.
Friends of the class that originally declared these members.
Classes derived with public or protected access from the class that originally declared
these members.
Direct privately derived classes that also have private access to protected members.
class A
{
Protected int pubFunc()
{
return 0;
}
};
/*
WAP to declare a class Book with the following data members
1) name
2) bid
3) auth_name
4) price
*/
import java.io.*;
class Book
{
String name;
int bid;
String Auth_name;
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
int price;
void bookInput()
{
try
{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter The Name Of Book=");
name = br.readLine();
System.out.println("Enter The Book ID=");
bid = Integer.parseInt(br.readLine());
System.out.println("Enter The Author Name=");
Auth_name = br.readLine();
System.out.println("Enter The Price=");
price = Integer.parseInt(br.readLine());
}
catch(IOException e)
{
System.out.println(e);
}
}
void display()
{
System.out.println("Book Name="+name);
System.out.println("Book ID="+bid);
System.out.println("Author Name="+Auth_name);
System.out.println("Price="+price);
}
class BookDemo
{
public static void main(String args[])
{
Book[] b = new Book[3];
for(int i=0;i<3;i++)
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
{
b[i].bookInput();
}
for(int i=0;i<3;i++)
{
b[i].display();
}
}
}
Manager Example:
import java.util.*;
class Manager
{
int no_of_projects;
String name;
void putData()
{
System.out.println("No_Of_Projects="+no_of_projects);
System.out.println("Manager Name="+name);
}
}
class ManagerDemo
{
public static void main(String args[])
{
Manager[] mObj = new Manager[3];
for(int i=0;i<3;i++)
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
for(int j=0;j<3;j++)
{
mObj[1].putData();
}
}
}
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
9 - Inheritance
Definitions:
The idea of inheritance is simple but powerful: When you want to create a new class
and there is already a class that includes some of the code that you want, you can derive
your new class from the existing class.
A class that is derived from another class is called a subclass (also a derived class,
extended class, or child class).
The class from which the subclass is derived is called a superclass (also a base class or a
parent class).
A subclass inherits all the members (fields, methods, and nested classes) from its
superclass. Constructors are not members, so they are not inherited by subclasses, but the
constructor of the superclass can be invoked from the subclass.
is implicitly a subclass of Object.
Classes can be derived from classes that are derived from classes that are derived from
classes, and so on, and ultimately derived from the topmost class, Object. Such a class is
said to be descended from all the classes in the inheritance chain stretching back to
Object.
An Example of Inheritance
Here is the sample code for a possible implementation of a Bicycle class that was presented
in the Classes and Objects lesson:
public class Bicycle {
}
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
Types of Inheritance:
Simple / Single
Multilevel
Single Inheritence:
One Super Class and one base class .
In "single inheritance," a common form of inheritance, classes have only one base class.
Syntax:
Class Class_Name
{
Access Specifier:
Data_Members Declaration;
Member_Function Declaration;
}
Class Class_Name1 : AccessSpecifier Class_Name
{
Access Specifier:
Data_Members Declaration;
Member_Function Declaration;
Example:
class Parent
{
public :
float height;
char hair_color[30] ;
char eye_color[30];
}
class child : public Parent
{
// Details of child;
}
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
public class A
{
}
public class B extends A
{
}
Multilevel Inheritance
The multilevel inheritance is the process of creating a new class from already derived class. Here
the exsiting derived class is intermediate base class. Newly created class is derived class.
Diagramatical representation:
public class A
{
}
public class B extends A
{
}
public class C extends B
{
}
e.g.
class A {
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
int x;
int y;
int get(int p, int q){
x=p; y=q; return(0);
}
void Show(){
System.out.println(x);
}
}
class B extends A{
void Showb(){
System.out.println("B");
}
}
class C extends B{
void display(){
System.out.println("C");
}
public static void main(String args[]){
A a = new A();
a.get(5,6);
a.Show();
}
}
A java variable can be declared using the keyword final. Then the final variable can be
assigned only once.
A variable that is declared as final and not initialized is called a blank final variable. A
blank final variable forces the constructors to initialize it.
Java classes declared as final cannot be extended. Restricting inheritance!
Methods declared as final cannot be overridden. In methods private is equal to final, but
in variables it is not.
final parameters – values of the parameters cannot be changed after initialization. Do a
small java exercise to find out the implications of final parameters in method overriding.
Java local classes can only reference local variables and parameters that are declared as
final.
A visible advantage of declaring a java variable as static final is, the compiled java class
results in faster performance.
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
Interfaces
An interface in the Java programming language is an abstract type that is used to specify
an interface (in the generic sense of the term) that classes must implement.
Interfaces are declared using the interface keyword, and may only contain method
signatures and constant declarations (variable declarations that are declared to be both
static and final).
An interface may never contain method definitions.
Interfaces cannot be instantiated. A class that implements an interface must implement all
of the methods described in the interface, or be an abstract class.
One benefit of using interfaces is that they simulate multiple inheritance.
All classes in Java (other than java.lang.Object, the root class of the Java type
system) must have exactly one base class; multiple inheritance of classes is not allowed.
Furthermore, a Java class may implement, and an interface may extend, any number of
interfaces; however an interface may not implement an interface.
interface Bounceable
{
void setBounce(); // Note the semicolon:
// Interface methods are public
and abstract.
// Think of them as prototypes
only; no implementations are allowed.
}
The syntax for implementing an interface uses this formula:
... implements InterfaceName[, another interface, another,
...] ...
Classes may implement an interface. For example,
public class Lion implements Predator {
super keyword
The super is java keyword. As the name suggest super is used to access the members of
the super class.It is used for two purposes in java.
The first use of keyword super is to access the hidden data variables of the super class
hidden by the sub class.
E.g. Suppose class A is the super class that has two instance variables as int a and float b.
class B is the subclass that also contains its own data members named a and b. then we
can access the super class (class A) variables a and b inside the subclass class B just by
calling the following command.
super.member;
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
Here member can either be an instance variable or a method. This form of super most
useful to handle situations where the local members of a subclass hides the members of a
super class having the same name. The following example clarify all the confusions.
class A{
int a;
float b;
void Show(){
System.out.println("b in super class: " + b);
}
class B extends A{
int a;
float b;
B( int p, float q){
a = p;
super.b = q;
}
void Show(){
super.Show();
System.out.println("b in super class: " + super.b);
System.out.println("a in sub class: " + a);
}
Output:
C:\>java B
b in super class: 5.0
b in super class: 5.0
a in sub class: 1
super(param-list);
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
Here parameter list is the list of the parameter requires by the constructor in the super
class.
super must be the first statement executed inside a super class constructor.
If we want to call the default constructor then we pass the empty parameter list. The
following program illustrates the use of the super keyword to call a super class
constructor.
class A{
int a;
int b;
int c;
A(int p, int q, int r){
a=p;
b=q;
c=r;
}
}
class B extends A{
int d;
B(int l, int m, int n, int o){
super(l,m,n);
d=o;
}
void Show(){
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
}
Method Overriding:-
In a class hierarchy, when a method in a subclass has the same name and type signature
as a method in its superclass, then the method in the subclass is said to override the
method in the superclass.
When an overridden method is called from within a subclass, it will always refer to the
version of that method defined by the subclass.
The version of the method defined by the superclass will be hidden.
Consider the following:
// Method overriding.
class A {
int i, j;
A(int a, int b) {
i = a;
j = b;
}
// display i and j
void show() {
System.out.println("i and j: " + i + " " + j);
}
}
class B extends A {
int k;
B(int a, int b, int c) {
super(a, b);
k = c;
}
// display k – this overrides show() in A
void show() {
System.out.println("k: " + k);
}
}
class Override {
public static void main(String args[]) {
B subOb = new B(1, 2, 3);
subOb.show(); // this calls show() in B
}
}
When show( ) is invoked on an object of type B, the version of show( ) defined within B
is used. That is, the versio n of show( ) inside B overrides the version declared in A. If
you wish to access the superclass version of an overridden function, you can do so by
using super. For example, in this version of B, the superclass version of show( ) is
invoked within the subclass' version. This allows all instance variables to be displayed.
Dynamic Method Dispatch:
Dynamic method dispatch (also known as dynamic binding) is the process of mapping
a message to a specific sequence of code (method) at runtime.
This is done to support the cases where the appropriate method can't be determined at compile-
time (i.e. statically).
Dynamic dispatch is only used for code invocation and not for other binding processes
class A {
void callme() {
System.out.println("Inside A's callme method");
}
}
class B extends A {
void callme() {
System.out.println("Inside B's callme method");
}
}
class C extends A {
void callme() {
System.out.println("Inside C's callme method");
}
}
class Dispatch {
public static void main(String args[]) {
A a = new A(); // object of type A
B b = new B(); // object of type B
C c = new C(); // object of type C
A r; // obtain a reference of type A
r = a; // r refers to an A object
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
r = b; // r refers to a B object
r.callme(); // calls B's version of callme
r = c; // r refers to a C object
r.callme(); // calls C's version of callme
}
}
10 - Multithreading :
Multitasking:-
Multitasking allow to execute more than one tasks at the same time, a task being a
program.
In multitasking only one CPU is involved but it can switches from one program to
another program so quickly that's why it gives the appearance of executing all of the
programs at the same time.F
Multitasking allow processes (i.e. programs) to run concurrently on the program. For
Example running the spreadsheet program and you are working with word processor
also.
Multitasking is running heavyweight processes by a single OS.
Multithreading :
Multithreading is a technique that allows a program or a process to execute many tasks
concurrently (at the same time and parallel). It allows a process to run its tasks in
parallel mode on a single processor system
In the multithreading concept, several multiple lightweight processes are run in a single
process/task or program by a single processor.
For Example, When you use a word processor you perform a many different tasks such
as printing, spell checking and so on. Multithreaded software treats each process as a
separate program.
In Java, the Java Virtual Machine (JVM) allows an application to have multiple threads of
execution running concurrently.
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
Threads can be part of a group. A thread group enables you to manage related threads
collectively. For example, you can obtain an array of the threads in the group.
Java’s multithreading system is built upon the Thread class and its companion interface,
Runnable. Thread encapsulates a thread of execution. To create a new thread, your
program will either implement the Runnable interface or extend Thread. Both Runnable
and Thread are packaged in java.lang. Thus, they are automatically available to all
programs.
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
Inside run( ), you will define the code that constitutes the new thread. It is important to
understand that run( ) can call other methods, use other classes, and declare variables just like
the main thread. The only difference is that run( ) establishes the entry point for another,
concurrent thread of execution within your program. This thread will end when run( ) returns.
Once you have created an instance of a class that implements Runnable, you create a thread by
constructing an object of type Thread, passing in the Runnable instance. To start the thread
running, you will call start( ) on the Thread object, as described in the next section.
The Thread class encapsulates a thread. It is packaged in java.lang and implements the
Runnable interface. Therefore, a second way to create a thread is to extend Thread and
override the run( ) method. Thread also defines several methods that help manage threads.
Here are the ones used in this chapter:
The Methods Defiend by InputStream
Creating a Thread
When a thread is created, it must be permanently bound to an object with a run() method.
When the thread is started, it will invoke the object's run() method. More specifically, the
object must implement the Runnable interface.
There are two ways to create a thread. The first is to declare a class that extends Thread. When
the class is instantiated, the thread and object are created together and the object is
automatically bound to the thread. By calling the object's start() method, the thread is started
and immediately calls the object's run() method. Here is some code to demonstrate this
method.
// This class extends Thread
class BasicThread1 extends Thread {
// This method is called when the thread runs
public void run() {
}
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
}
// Create and start the thread
Thread thread = new BasicThread1();
thread.start();
The second way is to create the thread and supply it an object with a run() method. This object
will be permanently associated with the thread. The object's run() method will be invoked when
the thread is started. This method of thread creation is useful if you want many threads sharing
an object. Here is an example that creates a Runnable object and then creates a thread with the
object.
/**
* This method is executed when the start() method is called on the thread
* so here you will put the 'thread code'.
*/
public void run() {
System.out.println("Thread executed!");
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Thread thread = new MyThread();
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
thread.start();
}
}
/**
* As in the previous example this method is executed
* when the start() method is called on the thread
* so here you will put the 'thread code'.
*/
public void run() {
System.out.println("Thread executed!");
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Stopping a Thread
The proper way to stop a running thread is to set a variable that the thread checks occasionally.
When the thread detects that the variable is set, it should return from the run() method.
Note: Thread.suspend() and Thread.stop() provide asynchronous methods of stopping a thread.
However, these methods have been deprecated because they are very unsafe. Using them
often results in deadlocks and incorrect resource cleanup.
// Create and start the thread
MyThread thread = new MyThread();
thread.start();
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
Runnable (Ready-to-run) state – A thread start its life from Runnable state. A thread first enters
runnable state after the invoking of start() method but a thread can return to this state after
either running, waiting, sleeping or coming back from blocked state also. On this state a thread
is waiting for a turn on the processor.
Running state – A thread is in running state that means the thread is currently executing. There
are several ways to enter in Runnable state but there is only one way to enter in Running state:
the scheduler select a thread from runnable pool.
Dead state – A thread can be considered dead when its run() method completes. If any thread
comes on this state that means it cannot ever run again.
Blocked - A thread can enter in this state because of waiting the resources that are hold by
another thread.
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
As we have seen different states that may be occur with the single thread.
A running thread can enter to any non-runnable state, depending on the circumstances.
A thread cannot enters directly to the running state from non-runnable state, firstly it
goes to runnable state. Now lets understand the some non-runnable states which may
be occur handling the multithreads.
Sleeping – On this state, the thread is still alive but it is not runnable, it might be return
to runnable state later, if a particular event occurs. On this state a thread sleeps for a
specified amount of time. You can use the method sleep( ) to stop the running state of a
thread.
Blocked on I/O – The thread waits for completion of blocking operation. A thread can enter on
this state because of waiting I/O resource. In that case the thread sends back to runnable state
after availability of resources.
Blocked for joint completion – The thread can come on this state because of waiting the
completion of another thread.
Blocked for lock acquisition – The thread can come on this state because of waiting to acquire
the lock of an object.
void sleep( ) Suspends a thread for a specified amount of time (in milliseconds).
Boolean isAlive( ) This method is used to determine the thread is running or not.
int activeCount( ) This method returns the number of active threads in a particular
thread
group and all its subgroups.
void interrupt( ) The method interrupt the threads on which it is invoked.
void yield( ) By invoking this method the current thread pause its execution temporarily
and
allow other threads to execute.
void join( ) :-
This method and join(long millisec) Throws InterruptedException. These two methods are
invoked on a thread. These are not returned until either the thread has completed or it is timed
out respectively.
Thread Priority :-
As mentioned, you can call a Thread object's interrupt() method to interrupt the
corresponding thread if it is sleeping or waiting.
The corresponding thread will "wake up" with an IOException at some point in the
future. See thread interruption for more details.
setPriority() / getPriority()
Sets and queries some platform-specific priority assignment of the given thread.
When calculating a priority value, it's good practice to always do so in relation to the
constants Thread.MIN_PRIORITY, Thread.NORM_PRIORITY and Thread.MAX_PRIORITY.
In practice, values go from 1 to 10, and map on to some machine-specific range of
values: nice values in the case of Linux, and local thread priorities in the case of
Windows.
These are generally the range of values of "normal" user threads, and the OS will
actually still run other threads beyond these values (so, for example, you can't preempt
the mouse pointer thread by setting a thread to MAX_PRIORITY!).
In Java, thread scheduler can use the thread priorities in the form of integer value to each of its
thread to determine the execution schedule of threads . Thread gets the ready-to-run state
according to their priorities. The thread scheduler provides the CPU time to thread of highest
priority during ready-to-run state.
Priorities are integer values from 1 (lowest priority given by the constant
Thread.MIN_PRIORITY) to 10 (highest priority given by the constant Thread.MAX_PRIORITY).
The default priority is 5(Thread.NORM_PRIORITY).
Constant Description
Thread.MIN_PRIORITY The maximum priority of any thread (an int value of 10)
Thread.MAX_PRIORITY The minimum priority of any thread (an int value of 1)
Thread.NORM_PRIORITY The normal priority of any thread (an int value of 5)
The methods that are used to set the priority of thread shown as:
Method Description
When a Java thread is created, it inherits its priority from the thread that created it. At any
given time, when multiple threads are ready to be executed, the runtime system chooses the
runnable thread with the highest priority for execution. In Java runtime system, preemptive
scheduling algorithm is applied. If at the execution time a thread with a higher priority and all
other threads are runnable then the runtime system chooses the new higher priority thread for
execution. On the other hand, if two threads of the same priority are waiting to be executed by
the CPU then the round-robin algorithm is applied in which the scheduler chooses one of them
to run according to their round of time-slice.
Thread Scheduler
In the implementation of threading scheduler usually applies one of the two following
strategies:
Preemptive scheduling – If the new thread has a higher priority then current running
thread leaves the runnable state and higher priority thread enter to the runnable state.
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
To make a method synchronized, simply add the synchronized keyword to its declaration:
c--;
}
Note that constructors cannot be synchronized — using the synchronized keyword with a
constructor is a syntax error. Synchronizing constructors doesn't make sense, because only the
thread that creates an object should have access to it while it is being constructed.
Warning: When constructing an object that will be shared between threads, be very careful
that a reference to the object does not "leak" prematurely. For example, suppose you want to
maintain a List called instances containing every instance of class. You might be tempted to add
the line
instances.add(this);
to your constructor. But then other threads can use instances to access the object before
construction of the object is complete.
Synchronized methods enable a simple strategy for preventing thread interference and
memory consistency errors: if an object is visible to more than one thread, all reads or writes to
that object's variables are done through synchronized methods. (An important exception: final
fields, which cannot be modified after the object is constructed, can be safely read through
non-synchronized methods, once the object is constructed) This strategy is effective, but can
present problems with liveness, as we'll see later in this lesson.
Instead of let the programmers to design their own locks, manage the synchronization blocks,
and apply the synchronization rules, Java offers a synchronization monitor on each instance of
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
the Object class, so it can be used as a synchronization lock. Since all classes are sub classes of
Object, all objects in Java can be used as synchronization locks.
All the statements in the method become the synchronized block, and the class object is the
lock.
Synchronized Instance Method:
class class_name {
synchronized type method_name() {
statement block
}
}
All the statements in the method become the synchronized block, and the instance object is the
lock.
Synchronized Statement:
class class_name {
type method_name() {
synchronized (object) {
statement block
}}}
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
11 - Packages
A Java package is a mechanism for organizing Java classes into namespaces similar to
the modules of Modula.
Java packages can be stored in compressed files called JAR files, allowing classes to
download faster as a group rather than one at a time.
Programmers also typically use packages to organize classes belonging to the same
category or providing similar functionality.
A package provides a unique namespace for the types it contains.
Classes in the same package can access each other's package-access members.
Using packages
In a Java source file, the package that this file's class or classes belong to is specified with the
package keyword. This keyword is usually the first keyword in source file.[1]
package java.awt.event;
To use a package's classes inside a Java source file, it is convenient to import the classes from
the package with an import declaration. The following declaration
import java.awt.event.*;
imports all classes from the java.awt.event package, while the next declaration
import java.awt.event.ActionEvent;
imports only the ActionEvent class from the package. After either of these import declarations,
the ActionEvent class can be referenced using its simple class name:
ActionEvent myEvent = new ActionEvent();
Classes can also be used directly without an import declaration by using the fully qualified name
of the class. For example,
java.awt.event.ActionEvent myEvent = new java.awt.event.ActionEvent();
Classes within a package can access classes and members declared with default access
and class members declared with the protected access modifier.
Default access is enforced when neither the public, protected nor private access
modifier is specified in the declaration.
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
By contrast, classes in other packages cannot access classes and members declared with
default access.
Class members declared as protected can be accessed from the classes in the same
package as well as classes in other packages that are subclasses of the declaring class.
Package naming conventions
Packages are usually defined using a hierarchical naming pattern, with levels in the
hierarchy separated by periods (.) (pronounced "dot").
Although packages lower in the naming hierarchy are often referred to as
"subpackages" of the corresponding packages higher in the hierarchy, there is no
semantic relationship between packages.
The Java Language Specification establishes package naming conventions to avoid the
possibility of two published packages having the same name.
The naming conventions describe how to create unique package names, so that
packages that are widely distributed will have unique namespaces.
This allows packages to be separately, easily and automatically installed and catalogued.
In general, a package name begins with the top level domain name of the organization
and then the organization's domain and then any subdomains listed in reverse order.
The organization can then choose a specific name for their package. Package names
should be all lowercase characters whenever possible.
For example, if an organization in Canada called MySoft creates a package to deal with
fractions, naming the package ca.mysoft.fractions distinguishes the fractions package
from another similar package created by another company.
If a US company named MySoft also creates a fractions package, but names it
us.mysoft.fractions, then the classes in these two packages are defined in a unique and
separate namespace.
Creating and Using Packages
To make types easier to find and use, to avoid naming conflicts, and to control access,
programmers bundle groups of related types into packages.
Suppose you write a group of classes that represent graphic objects, such as circles,
rectangles, lines, and points. You also write an interface, Draggable, that classes
implement if they can be dragged with the mouse.
//in the Draggable.java file
public interface Draggable {
...
}
Importing Claass:
But when you try to make an instance of class A in class B it whines about duplicates or
something.
package tools;
import java.io.*;
public Encryptor()
{}
public Encryptor(String s)
{
s = key;
import java.io.*;
import java.util.*;
import tools.*;
class Encryptortest
{
public static void main (String []args)
throws IOException {
Default package. Altho all Java classes are in a directory, it's possible to omit the package
declaration. For small programs it's common to omit it, in which case Java creates what it calls a
default package. Sun recommends that you do not use default packages.
Package declaration syntax
Package1(RectA.java)
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
package area;
public class RectA
{
double a;
a=len*brd;
}
Package 2(CircleA.java)
package area;
public class circleA
{
double areac,pi=3.14;
public circleA(double r)
{
areac=pi*r*r;
}
public void show()
{
System.out.println("The area of Circle is : "+areac);
}
}
Class File(CalArea.java)
import area.*;
class CalArea
{
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
Java.lang Package
Math class
1) random()
2) round()
3) pow()
4) sqrt()
5) abs()
6) max()
7) log()
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
import java.util.*;
class MathClassDemo
{
public static void main(String args[])
{
System.out.println("Square Root="+Math.sqrt(11));
int num = -3;
System.out.println("Absolute Value="+Math.abs(num));
System.out.println("Maximum Value="+Math.max(10.22,10.33));
System.out.println("Log value="+Math.log(10));
}
}