Nothing Special   »   [go: up one dir, main page]

BSC It - Sem IV - Core Java

Download as pdf or txt
Download as pdf or txt
You are on page 1of 141

Class : S.Y.BSc(I.

T) SEM - IV Subject : 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?

 Java is a pure object oriented programming language.

 A Java program is mostly a collection of objects talking to other objects by


invoking each other's methods.

 Every object is of a certain type, and that type is defined by a class or an


interface.

 Most Java programs use a collection of objects of many different types.

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.

 Collectively, the values assigned to an object's instance variables make up the


object's state.
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java

Behavior (methods)

 When a programmer creates a class, He/She creates methods for that class.

 Methods are where the class' logic is stored.

 Methods are where the real work gets done.

 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

 The concept of Write-once-run-anywhere (known as the Platform independent) is


one of the important key feature of java language that makes java as the most
powerful language.

 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.

 Encapsulation: It is the mechanism of combining the information and providing the


abstraction.Encapsulation is the process of hiding the details from the external class.

 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

 The feature Write-once-run-anywhere makes the java language portable provided


that the system must have interpreter for the JVM.
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java

 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

 Java does not use memory pointers explicitly.

 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.

 The bytecode Verifier checks the classes after loading.

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

 We all know that Java is an interpreted language as well. With an interpreted


language such as Java, programs run directly from the source code.

 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

 Another advantage of Java as an interpreted language is its error debugging quality.


Due to this any error occurring in the program gets traced. This is how it is different
to work with 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.

 Although the individual class files may appear to be independent.


 When you run your program, the Java virtual machine loads your program's classes
and interfaces and hooks them together in a process of dynamic linking.

 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:

 Start-up is faster, since there is less code to load initially.


 Running programs link every time with the most up-to-date version of any utility.
 Error detection is lazier, since exceptions are only thrown if there is an attempt to
execute unsafe code.

Why Java is Automatic Garbage Collected?

 When a Java object becomes unreachable to the program, then it is subjected to


garbage collection.

 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.

 When an object is no longer referred to by any variable,java automatically reclaims


memory used by that object.This is known as garbage collection.
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java

 System.gc() method may be used to call it explicitly.

Why Java is Architectural neutral ?

 Java was designed to support applications on networks.


 In general, networks are composed of a variety of systems with a variety of
CPU and operating system architectures.
 To enable a Java application to execute anywhere on the network, the
compiler generates an architecture-neutral object file format--the compiled
code is executable on many processors, given the presence of the Java
runtime system.
 This is useful not only for networks but also for single system software
distribution.
 The Java compiler does this by generating bytecode instructions which have
nothing to do with a particular computer architecture.
 Rather, they are designed to be both easy to interpret on any machine and
easily translated into native machine code
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java

The Execution Process In Java(Java Virtual Machine)

(Java Virtual Machine (JVM))


Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java

 The code is developed in either a plain text editor or an Integrated Development


Environment (IDE) and saved to a file with a .java extension.

 It is then checked for syntax errors by the Java Compiler (javac.exe).

 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.

Java Java Java


Program Compiler Virtual

Java Java Machine


ByteCode Interpret Code

Comments

Comments are basically used for program documentation .


Comments are simply text that is ignored by the compiler, but that may inform the
reader of what you are doing at any particular point in your program.

Types of Comments
There are two types of comments.
1) double-slash (//) comment.
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java

2) slash-star (/*) comment.


The double-slash comment, which will be referred to as a Java style comment, tells
the compiler to ignore everything that follows this comment, until the end of the
line.

The slash-star comment mark tells the compiler to ignore everything that follows
until it finds a star-slash (*/) comment mark.

These marks will be referred to as Java-style comments. Every /* must be matched


with a closing */.
Print Statement In Java:-

System.out.println(“String”);

The above statement is used to print any message on the console.

System is a class which is define in a package java.lang.*.

Out is a object of the class System.

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.

Every variable is mapped to a unique memory address. For example, we have 3


variable v1, v2, v3. They may be assigned the memory addresses 32000, 12456,
67893 respectively. Here is the illustration.
Syntax :
Data type Name_Of_Variable;
Eg:-
int v1; Int v3; Int v3;
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java

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.

Rules for Constructing Variable Names

1. A variable name is any combination of 1 to 31 alphabets, digits or


underscores.
2. The first character in the variable name must be an alphabet or underscore.
3. No commas or blanks are allowed within a variable name.
4. No special symbol other than an underscore (as in gross_sal) can be used in a
variable name.
5. Ex.: si_int

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' '{'

Boolean literals:(predefined values)


true false

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

Unlike C, we can't presume that the value of 1 is equivalent to true and 0 is


equivalent to false in Java. We have to use the values true and false to represent a
Boolean value.
Like
boolean chosen = true;
Remember that the literal true is not represented by the quotation marks around it.
The Java compiler will take it as a string of characters, if its in quotation marks.

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.

We represent string literals as


String myString = "How are you?";
The above example shows how to represent a string. It consists of a series of
characters inside double quotation marks.
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java

Lets see some more examples of string literals:

"" // the empty string


"\"" // a string containing "
"This is a string" // a string containing 16 characters
"This is a " + // actually a string-valued constant expression,
"two-line string" // formed from two string literals
Strings can include the character escape codes as well, as shown here:
String example = "Your Name, \"Sumit\"";
System.out.println("Thankingyou,\nRichards\n");

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

Every variable in Java has a data type.


Data types specify the size and type of values that can be stored within yhe memory.
Java language is rich in data type.
The general syntax for declaring the data type is
Data_type Name_of_variable;
Eg: int num;
Integers hold whole numbers that does not contain a decimal point..

All the following expressions are integers:

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:

45.12 -2344.5432 0.00 .04594


Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java

Type Range*

 char –128 to 127

 unsigned char 0 to 255

 signed char –128 to 127

 int –32768 to 32767

 unsigned int 0 to 65535

 signed int –32768 to 32767

 short int –32768 to 32767

 unsigned short int 0 to 65535


signed short int –32768 to 32767

 long int –2147483648 to 2147483647

 signed long int –2147483648 to 2147483647

 float –3.4E–38 to 3.4E+38

 double –1.7E–308 to 1.7E+308

 long double –3.4E–4932 to 1.1E+4932


Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java

2 - Operators In Java

Operator:

Operators are symbols which take one or more operands or expressions and perform
arithmetic or logical computations.

Java programming language provides several operators to perform different kind to


operations. There are operators for assignment, arithmetic functions, logical functions and
many more.

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.

A few are unary and only take one operand.


• Assignment Operator denoted by =
• Arithmetic operators denoted by +, -, *, /, %
• Compound assignment Operators denoted by +=, -=, *=, /=, %=, >>=, <<=, &=, ^=, |=
• Increment and Decrement operator denoted by ++, --
• Relational and equality operators denoted by ==, !=, >, <, >=, <=
• Logical operators denoted by !, &&, ||
• Conditional operator denoted by ?
• Comma operator denoted by ,
• Bitwise Operators denoted by &, |, ^, ~, <<, >>
• Explicit type casting operato

Assignment Operator

• This is denoted by symbol =.


• This operator is used for assigning a value to a variable.
• The left of the assignation operator is known as the lvalue (left value), which must
be a variable.
• The right of the assignation operator is known as the rvalue (right value). The rvalue
can be a constant, a variable, the result of an operation or any combination of these.

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

The operators used for arithmetic operation sin JAVA are:

• + 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;

int sum = n1 + n2;

int div = n2 / n1;

int mod = n2 % n1;


int diff;
if(n1 > n2)
{
diff = n1 - n2;

}
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

Compound assignment Operators


• This operator is used when a programmer wants to update a current value by
performing operation on the current value of the variable.
• For example:
Old += new is equal to
Old = old + new
Compound assignment operators function in a similar way the other operators +=, -=, *=,
/=, %=, >>=, <<=, &=, ^=, |= function.

Increment and Decrement Operator

• The increment operator is denoted by ++ and the decrement operator by --.


• The function of the increment operator is to increase the value and the decrement
operator is to decrease the value.
• These operators may be used as either prefix or postfix.
• A Prefix operator is written before the variable as ++a or –a.
• A Postfix operator is written after the variable as a++ or a--.

The Functionality of Prefix and Postfix Operators

• 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

But for the postfix operator namely as below:

y=3 //Postfix : Here Value of x is 3 and Value of y is 4


x=y++;
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java

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

Relational and Equality Operators

• 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

Here there are some examples:


(7 == 5) // evaluates to false.
(5 > 4) // evaluates to true.
(3 != 2) // evaluates to true.
(6 >= 6) // evaluates to true.
(5 < 5) // evaluates to false.

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.

Logical operators ( !, &&, || )


• The logical operators, logical AND (&&) and logical OR (||), are used to combine
multiple conditions formed using relational or equality expressions.
• The logical AND operator (&&) returns the boolean value true if both operands are
true and returns false otherwise.

• 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

Logical NOT Operator

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

int ans = n1 > n2 ? n1 : n2;

System.out.println("Greater Number=" +ans);

}
}
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 Operators ( &, |, ^, ~, <<, >> )

• The byte is the lowest level at which we can access data


• Bitwise operators modify variables considering the bit patterns that represent the
values they store.
operator asm equivalent description
& AND Bitwise AND
| OR Bitwise Inclusive OR
^ XOR Bitwise Exclusive OR
~ NOT Unary complement (bit inversion)

Bitwise AND

• The bitwise AND operator is a single ampersand: &.


• A handy mnemonic is that the small version of the boolean AND, &&, works on
smaller pieces (bits instead of bytes, chars, integers, etc).
• A binary AND simply takes the logical AND of the bits in each position of a number
in binary form.
For instance, working with a byte (the char type):
01001000 &
10111000 =
--------
00001000
The most significant bit of the first number is 0, so we know the most significant bit of the
result must be 0; in the second most significant bit, the bit of second number is zero, so we
have the same result. The only time where both bits are 1, which is the only time the result
will be 1, is the fifth bit from the left. Consequently,
72 & 184 = 8

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 operator

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

Both ways of type casting are valid in Java.


Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java

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

if(num >= 10 && num <= 100)


{
System.out.println("Number lies between 10 and 100");
}

}
}

The if-else Statement

• The if statement by itself will execute a single statement, or a group of statements,


when the expression following if evaluates to true. It does nothing when the expression
evaluates to false.
if(condition)
{
//body of if statement;
}

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

Nested if else Statement:

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

if(n1 < n2 || n1 < n3)


{
if(n2 > n3)
{
System.out.println("n2 is greater");
}
else
{
System.out.println("n3 is greater");
}
}
else
{
System.out.println("n1 is greater");
}
}
}

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.

This is an example of the continue statement:


while ( i-- > 0 )
{
x = f( i );
if ( x == 1 )
continue;
y += x * x;
}

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.

(a) Using a for statement


(b) Using a while statement
(c) Using a do-while statement
While Loop:-
A while loop causes your program to repeat a sequence of statements as long as the
starting condition remains true.
syntex :
initialization;
while(condition)
{
//Body of while loop;
//Increament/Decreament;
}
1- Initialization (Assingment operator "=")
2- Condition (Relationan Operator )
3- Increament/Decreament (Increament and Decreament operator "++" and "--")

Example:

class WhileDemo
{
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java

public static void main(String args[])


{
int i=1;

while(i <= 10)


{
System.out.print(i+"\t");
i++;
}

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

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

Eg
int i=1;
do
{
System.out.println(i);
i++;
}while(i<=10);

Difference between while and do…while loop?

While Loop Do..While Loop


While loop is declared with while keyword. Do While loop is declared with do and while
keyword.
While loop first test the condition and then Do while loop first executes the body of the loop
executes the body of the loop. and then test the condition.
In while loop if the condition is false for the first In do while if the condition is false for the first
time then the loop will be terminated. time then the loop executes at least once.
This is an entry controlled loop. This exit controlled loop.
Syntax: Syntax:
initialization; initialization;
while(condition) do
{ {
//Body of while loop; //body of do-while loop;
//Increament/Decreament; Increament/Decreament;
} }while(condition);

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

int fact = 1; // Note

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

WAP to find the series of factorial between 1 to 10?


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

int num = Integer.parseInt(args[0]);

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

WAP to check whether the entered number is palindrome or not?


class PallindromeDemo
{
public static void main(String args[])
{
int num = Integer.parseInt(args[0]);
int temp= num;
int rev = 0;

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

WAP to display series of prime number between 1 to 100?


class PrimeDemoSeries
{
public static void main(String args[])
{
int num = Integer.parseInt(args[0]);

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

WAP to check whether the entered number is Armstrong or not?


class ArmstrongDemo
{
public static void main(String args[])
{
int num = Integer.parseInt(args[0]);
int temp= num;
int sum=0;
while(num > 0)
{
int r = num % 10;

sum = sum + (r*r*r);

num = num / 10;


}

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

public static void main(String args[])


{

int num = Integer.parseInt(args[0]);


int f = 0;

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++)
{

System.out.print("*" +" ");


}
System.out.println();
}
}

/*
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++)
{

System.out.print("*" +" ");


}
System.out.println();
}
}

/* Program to compute roots of quadratic equation */


class Rootsquad
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java

{
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

System.out.println("Not a Prime Number");


}

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 intTemp = intNum;

int rev = 0;

/*

***** First Logic *****

for(;intNum>0;)
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java

{
int r = intNum % 10;

rev = rev * 10 + r;

intNum = intNum / 10;


}

*/

// ***** First Logic *****

while(intNum > 0)
{
int r = intNum % 10;

rev = rev * 10 + r;

intNum = intNum / 10;


}

System.out.println("Reverse =" +rev);


}

}
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java

6- Arrays and Strings

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.

An array of ten elements


 Each item in an array is called an element, and each element is accessed by its numerical
index.
 As shown in the above illustration, numbering begins with 0. The 9th element, for
example, would therefore be accessed at index 8.
Syntax:

DataType Name OfArray[];


ArrayName = new DataType[Size];
OR
DataType NameOfArray[] = new DataType[size];

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

NameOfArray is any user defined name.


Size determines the maximum value that array stores.
New operator is used to allocate the memory for array elements.
Example:
int num[];
num = new int[5];
OR
int num[] = new int[5];

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.

DataType Name OfArray[];


ArrayName = new DataType[Size];
OR
DataType NameOfArray[] = new DataType[size];
DataType: Determines the type of the value that array should store (int,float etc)
NameOfArray is any user defined name.
Size determines the maximum value that array stores.
New operator is used to allocate the memory for array elements.
Example:
int num[];
num = new int[5];
OR
int num[] = new int[5];

Initialization of an Array.
This step is achieved by using assignment operator.

int num[] = new int[5];

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

int num[] = {1,2,3,4,5,6,7,8,9,44,33,2,323};

Creating, Initializing, and Accessing an Array

 One way to create an array is with the new operator.


 The next statement in the ArrayDemo program allocates an array with enough memory
for ten integer elements and assigns the array to the anArray variable.
anArray = new int[10]; // create an array of integers

 If this statement were missing, the compiler would print an error like the following, and
compilation would fail:

ArrayDemo.java:4: Variable anArray may not have been initialized.

 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

int num[] = {1,2,3,4,5,6,7,8,9,44,33,2,323};

int len = num.length;

System.out.println("Length="+len);

for(int i=0;i<num.length;i++)
{
System.out.println("Array Index "+i+" "+num[i] );
}
}
}

Two or Double Dimensional Array:

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

DataType NameOfArray[][] = new DataType[size1][size2];

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.

Internally, Java stores 2 dimensional arrays as an array of arrays:

Example:

int num[][] = new int[3][3];


int num1[][] = new int[3][2];
How to use 2-Dimensional Array:

1) Declaration Of 2-Dimentional Array.


2) Creation Of Memory
3) Displaying an Array Elements.

/*
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

public static void main(String args[])


{
//int[][] intNum = new int[2][2]; //Decleration Of Array...

// 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();
}

}
}

Two Dimensional Array Input:


import java.io.*;
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java

class TwoDArrayUserInput
{
public static void main(String args[]) throws IOException
{
int[][] intNum = new int[2][2]; //Decleration Of Array...

BufferedReader br = new BufferedReader(new InputStreamReader(System.in)) ;

System.out.println("Enter The Matrix Elements=");


for(int i=0;i<intNum.length;i++)
{
for(int j=0;j<intNum.length;j++)
{

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

int[][] intNum2 = new int[2][2];

int[][] intSum = new int[2][2];

BufferedReader br = new BufferedReader(new InputStreamReader(System.in)) ;

System.out.println("Enter The First Matrix Elements=");


for(int i=0;i<intNum1.length;i++)
{
for(int j=0;j<intNum1.length;j++)
{

intNum1[i][j] = Integer.parseInt(br.readLine());
}
}

System.out.println("Enter The Second Matrix Elements=");


for(int i=0;i<intNum2.length;i++)
{
for(int j=0;j<intNum2.length;j++)
{

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

}
}

Sum of diagonal elements of the matrix:


Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java

import java.io.*;
class SumOfDiagonal
{
public static void main(String args[]) throws IOException
{
int[][] intNum1 = new int[2][2];

BufferedReader br = new BufferedReader(new InputStreamReader(System.in)) ;

System.out.println("Enter The First Matrix Elements=");


for(int i=0;i<intNum1.length;i++)
{
for(int j=0;j<intNum1.length;j++)
{

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

System.out.println("Sum Of Diagonal Elements=" +sum);


Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java

Multidimensional array

 A multi-dimensional array of dimension n (i.e., an n-dimensional array or simply n-D


array) is a collection of items which is accessed via n subscript expressions. For example,
in a language that supports it, the element of the two-dimensional array x is
accessed by writing x[i,j].
 You can also declare an array of arrays (also known as a multidimensional array) by
using two or more sets of square brackets, such as String[][] names. Each element,
therefore, must be accessed by a corresponding number of index values.
 In the Java programming language, a multidimensional array is simply an array whose
components are themselves arrays.
 This is unlike arrays in C or Fortran. A consequence of this is that the rows are allowed to
vary in length, as shown in the following MultiDimArrayDemo program:
class MultiDimArrayDemo {
public static void main(String[] args) {
String[][] names = {{"Mr. ", "Mrs. ", "Ms. "},
{"Smith", "Jones"}};
System.out.println(names[0][0] + names[1][0]); //Mr. Smith
System.out.println(names[0][2] + names[1][1]); //Ms. Jones
}
}
The output from this program is:
Mr. Smith
Ms. Jones
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java

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.

How to take input from the user by using an Array?

import java.io.*;
class ArrayInput
{

public static void main(String args[])throws IOException


{
int intNum[] = new int[5];

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

System.out.println("Enter The Array Elements !!!");


for(int i=0;i<intNum.length;i++)
{
intNum[i] = Integer.parseInt(br.readLine());
}

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
{

public static void main(String args[])throws IOException


{
int intNum[] = new int[10];

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

System.out.println("Enter The Array Elements !!!");


for(int i=0;i<intNum.length;i++)
{
intNum[i] = Integer.parseInt(br.readLine());
}

for(int i=0;i<intNum.length;i++)
{
System.out.println("Array Element="+i+" "+intNum[i]);
}

int intLarge = intNum[0];

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

WAP to sort 5 numbers by using Bubble Sort ?

import java.io.*;
class BubbleSort
{
public static void main(String args[]) throws IOException
{
int[] intNum = new int[5]; // Decleration Of Array

BufferedReader br = new BufferedReader(new InputStreamReader(System.in)) ;

System.out.println("Enter The 5 Numbers=");


for(int i=0;i<intNum.length;i++)
{
intNum[i] = Integer.parseInt(br.readLine());
}
for(int i=0;i<intNum.length;i++)
{
System.out.print(intNum[i] +" ");
}

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

if(intNum[i] < intNum[j])


{
int intTemp = intNum[i];
intNum[i] = intNum[j];
intNum[j] = intTemp;
}
}
}
System.out.println();
System.out.println("Sorted Elements Are:");
for(int i=0;i<intNum.length;i++)
{
System.out.print(intNum[i] +" ");
}
}
}
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);

Here are some more examples of how strings can be used:


System.out.println("abc");
String cde = "cde";
System.out.println("abc" + cde);
String c = "abc".substring(2,3);
String d = cde.substring(1, 2);

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

String concat(String str)


Concatenates the specified string to the end of this string.
Boolean contentEquals(StringBuffer sb)
Returns true if and only if this String represents the same sequence of
characters as the specified StringBuffer.
Boolean endsWith(String suffix)
Tests if this string ends with the specified suffix.
Boolean equals(Object anObject)
Compares this string to the specified object.
Boolean equalsIgnoreCase(String anotherString)
Compares this String to another String, ignoring case considerations.
byte[] getBytes()
Encodes this String into a sequence of bytes using the platform's default
charset, storing the result into a new byte array.
void
getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
Copies characters from this string into the destination character array.

int length()
Returns the length of this string.

boolean matches(String regex)


Tells whether or not this string matches the given regular expression.

String
replace(char oldChar, char newChar)
Returns a new string resulting from replacing all occurrences of oldChar in this
string with newChar.

String replaceAll(String regex, String replacement)


Replaces each substring of this string that matches the given regular expression
with the given replacement.

String replaceFirst(String regex, String replacement)


Replaces the first substring of this string that matches the given regular
expression with the given replacement.

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)


Tests if this string starts with the specified prefix.

boolean
startsWith(String prefix, int toffset)
Tests if this string starts with the specified prefix beginning a specified index.

String substring(int beginIndex, int endIndex)


Returns a new string that is a substring of this string.

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

// ******* Constructors ******

String str = new String(); // Empty String

str = "Juned";// assings junaid to str

char data[] = {'s','h', 'a','h','i','d'}; // Declaration of char Array


String str1 = new String(data);// assigns data to str1

String str2 = "Ibrahim"; // directly assiigns Ibrahim to str2

// Display all the declared strings...

System.out.println("Str="+str);
System.out.println("Str1="+str1);

System.out.println("Str2="+str2);
System.out.println("Str="+str);

// ****** Methods ******

System.out.println(str.charAt(1)); // gives the 2 charecter of str


System.out.println(str1.charAt(4));// gives the 5 charecter of str1

System.out.println(str1.codePointAt(0));// gives the corrosponding unicode value

System.out.println(str1.equals(str2)); // conpares two strings


System.out.println(str1.concat(str2)); // concatinate two strings

System.out.println(str1.contains("u")); // if str1 contains u then returns true

System.out.println(str1.equalsIgnoreCase(str2));// compares two string by ignoring case

System.out.println(str1.length());// returns the length of str1

System.out.println(str1.replace('s','i')); // replace s with i of str


System.out.println(str1.replaceAll("shahid","Ibrahim"));// replace shahid with ibrahim
of str1

System.out.println(str1.toUpperCase()); // convets into uppercase


System.out.println(str1.toLowerCase()); // converts into lower case

String str5 = "s h a hid";

System.out.println(str5.trim());
}
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java

StringBuffer Class:

 A string buffer is like a String, but can be modified.


 At any point in time it contains some particular sequence of characters, but the length and
content of the sequence can be changed through certain method calls.
 Every string buffer has a capacity.
 As long as the length of the character sequence contained in the string buffer does not
exceed the capacity, it is not necessary to allocate a new internal buffer array.
 If the internal buffer overflows, it is automatically made larger.

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

Returns the current capacity.


char charAt(int index)
Returns the char value in this sequence at the specified index.
int codePointAt(int index)
Returns the character (Unicode code point) at the specified index.
StringBuffer delete(int start, int end)
Removes the characters in a substring of this sequence.
StringBuffer deleteCharAt(int index)
Removes the char at the specified position in this sequence.
StringBuffer insert(int offset, char c)
Inserts the string representation of the char argument into this sequence.
StringBuffer insert(int offset, char[] str)
Inserts the string representation of the char array argument into this
sequence.
StringBuffer insert(int index, char[] str, int offset, int len)
Inserts the string representation of a subarray of the str array argument
into this sequence.
int length()
Returns the length (character count).
StringBuffer replace(int start, int end, String str)
Replaces the characters in a substring of this sequence with characters in
the specified String.
StringBuffer reverse()
Causes this character sequence to be replaced by the reverse of the
sequence.
String substring(int start)
Returns a new String that contains a subsequence of characters currently
contained in this character sequence.
String substring(int start, int end)
Returns a new String that contains a subsequence of characters currently
contained in this sequence.
String toString()
Returns a string representing the data in this sequence.
void trimToSize()
Attempts to reduce storage used for the character sequence.
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java

Example:

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

// ***** Constructors *****

StringBuffer sb = new StringBuffer();

StringBuffer sb1 = new StringBuffer(100);

StringBuffer sb3 = new StringBuffer("Shahid Ansari");

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******

Object obj = new Object();

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

StringBuffer sb5 = new StringBuffer();


sb5.append(123);
System.out.println("Sb5="+sb5);
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java

System.out.println("Reverse="+sb5.reverse());
sb3.delete(2,8);
System.out.println("String After Deletion="+sb3);

StringBuffer sb6 = new StringBuffer("Amit ");


char[] data = {'B','h','t','t','e'};
sb6.insert(5,data);

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:

public static void arraycopy(Object src,


int srcPos,
Object dest,
int destPos,
int length)
 The two Object arguments specify the array to copy from and the array to copy to.
 The three int arguments specify the starting position in the source array, the starting
position in the destination array, and the number of array elements to copy.
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java

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

System.arraycopy(copyFrom, 2, copyTo, 0, 7);


System.out.println(new String(copyTo));
}
}
The output from this program is:
caffein

Array of Objects
A 2D array of objects is an array of an array of references to objects:

// creates the single reference nums (yellow square)


Square [][] board;

// creates the array of references to arrays (blue squares)


board = new Square[2][];

// creates are arrays of references to objects (red squares).


for (int i=0; i < board.length ; i++)
board[i] = new Square[3]; // create arrays of references to
objects
Note: the above instructions can be combined into the instruction:
Square [][] board = new Square[2][3];
However, we still have not created any objects! To create objects, there is no simple way other
than with loops:
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java

for (int i=0; i < board.length ; i++)


for (int j=0; j < board[i].length ; j++)
board[i][j] = new Square(i,j,color);
Vector
 Vectors are commonly used instead of arrays, because they expand automatically when
new data is added to them.
 Vectors can hold only Objects and not primitive types (eg, int).
 If you want to put a primitive type in a Vector, put it inside an object (eg, to save an
integer value use the Integer class or define your own class).
 If you use the Integer wrapper, you will not be able to change the integer value, so it is
sometimes useful to define your own class.
 Create a Vector with default initial size
Vector v = new Vector();
 Create a Vector with an initial size
Vector v = new Vector(300);
v.add(s); // adds s to the end of the Vector v
There are many useful methods in the Vector class and its parent classes. Here are some of the
most useful. v is a Vector, i is an int index, o is an Object.
Method Description
v.add(o) adds Object o to Vector v
v.add(i, o) Inserts Object o at index i, shifting elements up as necessary.
v.clear() removes all elements from Vector v
v.contains(o) Returns true if Vector v contains Object o
v.firstElement(i) Returns the first element.
v.get(i) Returns the object at int index i.
v.lastElement(i) Returns the last element.
Returns a ListIterator that can be used to go over the Vector. This is a
v.listIterator()
useful alternative to the for loop.
Removes the element at position i, and shifts all following elements
v.remove(i)
down.
v.set(i,o) Sets the element at index i to o.
v.size() Returns the number of elements in Vector v.
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java

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 call stack.

 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

Searching the call stack for the exception handler.


Using exceptions to manage errors has some advantages over traditional error-management
techniques.
Valid Java programming language code must honor the Catch or Specify Requirement. This
means that code that might throw certain exceptions must be enclosed by either of the
following:
 A try statement that catches the exception. The try must provide a handler for the
exception, as described in Catching and Handling Exceptions.
 A method that specifies that it can throw the exception. The method must provide a
throws clause that lists the exception, as described in Specifying the Exceptions
Thrown by a Method.
THE FINALLY KEYWORDS :
 "Finally" creates a block of code that will be executed after try/catch block has completed
and before the code following the try/catch block.
 T he finally is a Java keyword that is used to define a block that is always executed in a
try−catch−finally statement. In java, there are three clauses named try, catch and finally
used as exception handler components. A finally block typically contains cleanup code
that recovers from partial execution of a try block.
try {
/ Normal execution path
……………….
………………
} catch (ExampleException ee) {
/ deal with the ExampleException
……………….
………………
}
finally {
/ This optional section is executed upon
termination of any of the try or catch blocks /above
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java

………………..
……………….
}

 The finally block will execute whether or not an exception is thrown.


 If an exception is thrown, finally block will execute even if no catch statements matches
the exception. Finally is guaranteed to execute, even if no exceptions are thrown.
 Finally block is an ideal position for closing the resources such as file handle or a
database connection etc.
public class FinallyDemo {

static void procA(){

try{
System.out.println("inside procA");
throw new RuntimeException("demo");

}finally{
System.out.println("procA's finally");
}
}

//Return from with in a try block.


static void procB(){

try{
System.out.println("inside procB");
return;
}
finally{
System.out.println("procB's finally");
}
}

//Execute a try block normally.


static void procC(){

try{
System.out.println("inside procC");
}
finally{
System.out.println("procC's finally");
}
}

public static void main(String[] args) {


Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java

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

class MyException extends Exception {


public MyException(String msg){
super(msg);
}
}
public class Test {

static int divide(int first,int second) throws MyException{


if(second==0)
throw new MyException("can't be divided by zero");
return first/second;
}
public static void main(String[] args) {
try {
System.out.println(divide(4,0));
}
catch (MyException exc) {
exc.printStackTrace();
}
}
}
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java

8 - Object Oriented Programming

Objects:

 Object is the basic unit of object-oriented programming.


 Objects are identified by its unique name.
 An object represents a particular instance of a class.
 There can be more than one instance of an object. Each instance of an object can hold its
own relevant data.

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
{

Access Specifier Variable Decleration;


Access Specifier Function Decleration;

Access Specifier Variable Decleration;


Access Specifier Function Decleration;
};

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 input(String s, int r, float p)


{
name = s;
rollno = r;
per = p;
}

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

public String name ;


public int rollno ;
public float per ;

void input(String s, int r, float p)


{
name = s;
rollno = r;
per = p;
}
private void display()
{
System.out.println("Name="+name);
System.out.println("Roll No="+rollno);
System.out.println("Percentage="+per);
}

public static void main(String args[])


{
Student sObj = new Student();

sObj.input("ABC",2,23.77F)
sObj.display();

}
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java

Arrays of Objects

 Any object, whether built-in or user-defined, can be stored in an array.


 When you declare the array, you tell the compiler the type of object to store and the
number of objects for which to allocate room. The compiler knows how much room is
needed for each object based on the class declaration.
 Accessing member data in an array of objects is a two-step process.
 You identify the member of the array by using the index operator ([ ]), and then you add
the member operator (.) to access the particular member variable.

import java.util.*;
class Manager
{
int no_of_projects;
String name;

void getData(int no, String n)


{
no_of_projects = no;
name = n;
}

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

mObj[0] = new Manager();


mObj[1] = new Manager();
mObj[2] = new Manager();

Scanner sc = new Scanner(System.in);

for(int i=0;i<3;i++)
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java

System.out.println("Enter The Name Of Manager=");


String strName = sc.next();
System.out.println("Enter The Number Of Projects=");
int number = sc.nextInt();
mObj[i].getData(number,strName);

for(int j=0;j<3;j++)
{
mObj[1].putData();
}

}
}

Static Data Members:

 Classes can contain static member data and member functions.


 When a data member is declared as static, only one copy of the data is maintained for all
objects of the class.
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java

 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:

Characteristics of static data members:

 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 Member Function:

Static function is defined by using the keyword static before the member function that is to be
declared as static function.

General syntax:

static return_data_type function_name() {//body}

Characteristics of static member function:

 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.

Accessing Static Function:

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:

 Constructors are used in order to initialize the objects.


 A constructor is a special kind of a function which is the member of the class.
 The name of the constructor is same as name of the class.
 A constructor is automatically called when object is created.
 A constructor does not have a return type.
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java

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
{

public static void main(String args[])


{

ConsDemo cd = new ConsDemo();

cd.show();
}

}
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java

Types Of Constructors:

Default Constructors

 In computer programming languages the term “default constructor” refers to


a constructor that is automatically generated in the absence of explicit constructors
 A default constructor is a constructor with no parameters.
 If no constructor is defined by the user then compiler supplies the default constructor.
 Once the constructor is defined by the user then compiler does not supply default
constructor and then user is responsible for defining default constructor.

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;

public ParaDemo(int a,int b)


Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java

{
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[])
{

Scanner sc = new Scanner(System.in);


System.out.println("Enter The Numbers=");
int num1 = sc.nextInt();
int num2 = sc.nextInt();

ParaDemo pd = new ParaDemo(num1,num2);


pd.show();
}
}

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

Output of the program is given below:


C:\java>java
UseOfThisOperator
The area of a Rectangle is : 30

Java Final Keyword


 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. 
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java

 A visible advantage of declaring a java variable as static final is, the compiled java class
results in faster performance. 

Writing a finalize() Method

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.

Java uses finalize() method for Garbage collection.


Your class can provide for its finalization simply by defining and implementing a method in your
class named finalize(). Your finalize() method must be declared as follows:
protected void finalize () throws throwable

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:

int myFunction (int, int);


int myFunction (long, long);
int myFunction (long);
myFunction()

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

void add(double num1, double num2)


{
double sumd = num1 + num2;

System.out.println("Sum Of Double Variables=" + sumd);


}
}

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

OverloaingDemo od = new OverloaingDemo();

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(double l,double b,double h)


{
length=l;
breadth=b;
height=h;
}
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java

Room()
{
length=-1;
breadth=-1;
height=-1;
}

Room(double len)
{
length=breadth=height=len;
}

double volume()
{
return length*breadth*height;
}

Nested Classes / Inner Classes:


The Java programming language allows you to define a class within another class. Such a class is
called a nested class and is illustrated here:
class OuterClass {
...
class NestedClass {
...
}
}

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.

public class OuterClass


{
private String outerInstanceVar;

public class InnerClass


{
public void printVars()
{
System.out.println( "Print Outer Class Instance Var.:" +
outerInstanceVar);
}
}
}

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.

public void testInner()


{
...
OuterClass outer = new OuterClass();
OuterClass.InnerClass inner = outer.new InnerClass();
...
}

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
{

Public int pubFunc()


{
return 0;
}
};

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

Accept these details for three Books?

*/

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

b[0] = new Book();


b[1] = new Book();
b[2] = new Book();

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 getData(int no, String n)


{
no_of_projects = no;
name = n;
}

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

mObj[0] = new Manager();


mObj[1] = new Manager();
mObj[2] = new Manager();

Scanner sc = new Scanner(System.in);

for(int i=0;i<3;i++)
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java

System.out.println("Enter The Name Of Manager=");


String strName = sc.next();
System.out.println("Enter The Number Of Projects=");
int number = sc.nextInt();
mObj[i].getData(number,strName);

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.

All Classes in the Java Platform are Descendants of Object


 At the top of the hierarchy, Object is the most general of all classes. Classes near the
bottom of the hierarchy provide more specialized behavior.
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java

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 {

// the Bicycle class has three fields


public int cadence;
public int gear;
public int speed;

// the Bicycle class has one constructor


public Bicycle(int startCadence, int startSpeed, int
startGear) {
gear = startGear;
cadence = startCadence;
speed = startSpeed;
}

// the Bicycle class has four methods


public void setCadence(int newValue) {
cadence = newValue;
}

public void setGear(int newValue) {


gear = newValue;
}

public void applyBrake(int decrement) {


speed -= decrement;
}

public void speedUp(int increment) {


speed += increment;
}

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

Java Final Keyword

 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

Abstract Methods and Classes


 An abstract class is a class that is declared abstract—it may or may not include
abstract methods. Abstract classes cannot be instantiated, but they can be subclassed.
 An abstract method is a method that is declared without an implementation (without
braces, and followed by a semicolon), like this:
 abstract void moveTo(double deltaX, double deltaY);
 If a class includes abstract methods, the class itself must be declared abstract, as in:
public abstract class GraphicObject {
// declare fields
// declare non-abstract methods
abstract void draw();}
 When an abstract class is subclassed, the subclass usually provides implementations for
all of the abstract methods in its parent class. However, if it does not, the subclass must
also be declared abstract.

An Abstract Class Example


 In an object-oriented drawing application, you can draw circles, rectangles, lines, Bezier
curves, and many other graphic objects. These objects all have certain states (for
example: position, orientation, line color, fill color) and behaviors (for example: moveTo,
rotate, resize, draw) in common. Some of these states and behaviors are the same for
all graphic objects—for example: position, fill color, and moveTo. Others require
different implementations—for example, resize or draw.
 All GraphicObjects must know how to draw or resize themselves; they just differ in
how they do it. This is a perfect situation for an abstract superclass. You can take
advantage of the similarities and declare all the graphic objects to inherit from the same
abstract parent object—for example, GraphicObject, as shown in the following
figure.

Classes Rectangle, Line, Bezier, and Circle inherit from GraphicObject


First, you declare an abstract class, GraphicObject, to provide member variables and methods
that are wholly shared by all subclasses, such as the current position and the moveTo method.
GraphicObject also declares abstract methods for methods, such as draw or resize, that need
to be implemented by all subclasses but must be implemented in different ways. The
GraphicObject class can look something like this:
abstract class GraphicObject {
int x, y;
...
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java

void moveTo(int newX, int newY) {


...
}

abstract void draw();


abstract void resize();
}
Each non-abstract subclass of GraphicObject, such as Circle and Rectangle, must
provide implementations for the draw and resize methods:
class Circle extends GraphicObject {
void draw() {
...
}
void resize() {
...
}
}
class Rectangle extends GraphicObject {
void draw() {
...
}
void resize() {
...
}
}

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.

[visibility] interface InterfaceName [extends other


interfaces] {
constant declarations
abstract method declarations
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java

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 {

public boolean chasePrey(Prey p) {


// programming to chase prey p (specifically
for a lion)
}

public void eatPrey (Prey p) {


// programming to eat prey p (specifically
for a lion)
}
}
 If a class implements an interface and does not implement all its methods, it must be
marked as abstract. If a class is abstract, one of its subclasses is expected to implement
its unimplemented methods.
 Classes can implement multiple interfaces
public class Frog implements Predator, Prey { ... }
 Interfaces are commonly used in the Java language for callbacks.
 Java does not allow the passing of methods (procedures) as arguments.

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

public static void main(String[] args){


B subobj = new B(1, 5);
subobj.Show();
}
}

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

public static void main(String args[]){


B b = new B(4,3,8,7);
b.Show();
}
}
Output:
C:\>java B
a=4
b=3
c=8
d=7
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java

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

The output produced by this program is shown here:


k: 3
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java

 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.callme(); // calls A's version of callme

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

 It allows a program to be more responsible to the user. When a program contains


multiple threads then the CPU can switch between the two threads to execute them at
the same time.
 Multithreading is important to Java for two main reasons. First, multithreading enables
you to write very efficient programs because it lets you utilize the idle time that is
present in most programs.
 Most I/O devices, whether they be network ports, disk drives, or the keyboard, are
much slower than the CPU.
 Thus, a program will often spend a majority of its execution time waiting to send or
receive information to or from a device. By using multithreading, your program can
execute another task during this idle time.
 For example, while one part of your program is sending a file over the Internet, another
part can be
 handling user interaction (such as mouse clicks or button presses), and still another can
be buffering the next block of data to send.

 The second reason that multithreading is important to Java relates to Java’s


eventhandling model. A program (such as an applet) must respond quickly to an event
and then return. An event handler must not retain control of the CPU for an extended
period of time.
 Two or more threads can communicate with each other through methods that are
defined by Object. These methods are wait( ), notify( ), and notifyAll( ). They enable one
thread to wait on another. For example, if one thread is using a shared resource, then
another thread must wait until the first thread has finished. The waiting thread can
resume execution when the first thread notifies it that the resource is now available.

 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

The Runnable Interface


The java.lang.Runnable interface abstracts a unit of executable code. You can construct a
thread on any object that implements the Runnable interface. Therefore, any class that you
intend to run in a separate thread must implement Runnable. Runnable defines only one
method called run( ), which is declared like this:
void run()

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

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.

class BasicThread2 implements Runnable {


// This method is called when the thread runs
public void run() {
}
}
// Create the object with the run() method
Runnable runnable = new BasicThread2();

// Create the thread supplying it with the runnable object


Thread thread = new Thread(runnable);

// Start the thread


thread.start();

public class MyThread extends Thread {

/**
* 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();
}
}

Implementing the Runnable interface:


public class MyRunnable implements Runnable {

/**
* 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) {

//create a Thread object and pass it an object of type Runnable


Thread thread = new Thread(new MyRunnable());
thread.start();
}
}

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

// Stop the thread


thread.allDone = true;

class MyThread extends Thread {


boolean allDone = false;

// This method is called when the thread runs


public void run() {
while (true) {
if (allDone) {
return;
}
}
}
}
Life Cycle of A Thread
When you are programming with threads, understanding the life cycle of thread is very
valuable. While a thread is alive, it is in one of several states. By invoking start() method, it
doesn’t mean that the thread has access to CPU and start executing straight away. Several
factors determine how it will proceed.
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java

Different states of a thread are :


New state – After the creations of Thread instance the thread is in this state but before the
start() method invocation. At this point, the thread is considered not alive.

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.

static void sleep(long millisecond) throws InterruptedException


Waiting for Notification – A thread waits for notification from another thread. The thread sends
back to runnable state after sending notification from another thread.

final void wait(long timeout) throws InterruptedException


final void wait(long timeout, int nanos) throws InterruptedException
final void wait() throws InterruptedException

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.

Methods that can be applied apply on a Thread Class:

currentThread( ) Thread Returns an object reference to the thread in which it is


invoked.
String getName( ) Retrieve the name of the thread object or instance.
Void start( ) Start the thread by calling its run method.
Void run( ) This method is the entry point to execute thread, like the main method
for applications.
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java

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!).

 Three main issues with thread priorities are that:


 Their behaviour depends on the platform and Java version: e.g. in Linux,
priorities don't work at all in Hotspot before Java 6, and the mapping of Java
to OS priorities changed under Windows between Java 5 and Java 6;
 In trying to use them for some purpose, you may actually interfere with more
sensible scheduling decisions that the OS would have made anyway to
achieve your purpose.
Thread Priorities
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java

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

setPriority() This is method is used to set the priority of thread.


getPriority() This method is used to get the priority of thread.

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

 Time-Sliced (Round-Robin) Scheduling – A running thread is allowed to be execute for


the fixed time, after completion the time, current thread indicates to the another thread
to enter it in the runnable state.
 You can also set a thread's priority at any time after its creation using the setPriority
method. Lets see, how to set and get the priority of a thread.

class MyThread1 extends Thread{


MyThread1(String s){
super(s);
start();
}
public void run(){
for(int i=0;i<3;i++){
Thread cur=Thread.currentThread();
cur.setPriority(Thread.MIN_PRIORITY);
int p=cur.getPriority();
System.out.println("Thread Name :"+Thread.currentThread().getName());
System.out.println("Thread Priority :"+cur);
}
}
}
class MyThread2 extends Thread{
MyThread2(String s){
super(s);
start();
}

public void run(){


for(int i=0;i<3;i++){
Thread cur=Thread.currentThread();
cur.setPriority(Thread.MAX_PRIORITY);
int p=cur.getPriority();
System.out.println("Thread Name :"+Thread.currentThread().getName());
System.out.println("Thread Priority :"+cur);
}
}
}
public class ThreadPriority{
public static void main(String args[]){
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java

MyThread1 m1=new MyThread1("My Thread 1");


MyThread2 m2=new MyThread2("My Thread 2");
}
}
Output of the Program:
C:\nisha>javac ThreadPriority.java
C:\nisha>java ThreadPriority
Thread Name :My Thread 1
Thread Name :My Thread 2
Thread Priority :Thread[My Thread 2,10,main]
Thread Name :My Thread 2
Thread Priority :Thread[My Thread 2,10,main]
Thread Name :My Thread 2
Thread Priority :Thread[My Thread 2,10,main]
Thread Priority :Thread[My Thread 1,1,main]
Thread Name :My Thread 1
Thread Priority :Thread[My Thread 1,1,main]
Thread Name :My Thread 1
Thread Priority :Thread[My Thread 1,1,main]
In this program two threads are created. We have set up maximum priority for the first thread
"MyThread2" and minimum priority for the first thread "MyThread1" i.e. the after executing
the program, the first thread is executed only once and the second thread "MyThread2" started
to run until either it gets end or another thread of the equal priority gets ready to run state.
Synchronization:-
The Java programming language provides two basic synchronization idioms: synchronized
methods and synchronized statements. The more complex of the two, synchronized
statements, are described in the next section. This section is about synchronized methods.

To make a method synchronized, simply add the synchronized keyword to its declaration:

public class SynchronizedCounter {


private int c = 0;

public synchronized void increment() {


c++;
}

public synchronized void decrement() {


Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java

c--;
}

public synchronized int value() {


return c;
}
}
If count is an instance of SynchronizedCounter, then making these methods synchronized has
two effects:
First, it is not possible for two invocations of synchronized methods on the same object to
interleave. When one thread is executing a synchronized method for an object, all other
threads that invoke synchronized methods for the same object block (suspend execution) until
the first thread is done with the object.
Second, when a synchronized method exits, it automatically establishes a happens-before
relationship with any subsequent invocation of a synchronized method for the same object.
This guarantees that changes to the state of the object are visible to all threads.

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.

Java also offers three ways to define synchronized blocks.

Synchronized Class Method:


class class_name {
static synchronized type method_name() {
statement block
}
}

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.

 Definition: A package is a grouping of related types providing access protection and


name space management. Note that types refers to classes, interfaces, enumerations,
and annotation types. Enumerations and annotation types are special kinds of classes
and interfaces, respectively, so types are often referred to in this lesson simply as
classes and interfaces.
 The types that are part of the Java platform are members of various packages that
bundle classes by function: fundamental classes are in java.lang, classes for reading and
writing (input and output) are in java.io, and so on. You can put your types in packages
too.
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java

 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 {
...
}

//in the Graphic.java file


public abstract class Graphic {
...
}

//in the Circle.java file


public class Circle extends Graphic implements Draggable {
...
}

//in the Rectangle.java file


public class Rectangle extends Graphic implements Draggable {
...
}

//in the Point.java file


public class Point extends Graphic implements Draggable {
...
}

//in the Line.java file


public class Line extends Graphic implements Draggable {
...
}

Importing Claass:

Eg: class A class B

i want to import class A into class B


Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java

Class B is a test class

Class a compiles fine.

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 class Encryptor


{
String key;
String estring, dstring;

public Encryptor()
{}

public Encryptor(String s)
{
s = key;

String encrypt(String se)


{
return estring;
}

String decrpyt(String sd)


{
return dstring;
}
}

encryptor test class


Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java

import java.io.*;
import java.util.*;
import tools.*;

class Encryptortest
{
public static void main (String []args)
throws IOException {

BufferedReader stdin = new BufferedReader


(new InputStreamReader(System.in));
Encryptor e1;
// System.out.println(e1.key);
}
}
Packages and Import
Package = directory. Java classes can be grouped together in packages. A package name is the
same as the directory (folder) name which contains the .java files. You declare packages when
you define your Java program, and you name the packages you want to use from other libraries
in an import statement.
Package declaration
The first statement, other than comments, in a Java source file, must be the package
declaration.
Following the optional package declaration, you can have import statements, which allow you
to specify classes from other packages that can be referenced without qualifying them with
their package.

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

The statement order is as follows. Comments can go anywhere.


Package statment (optional).
Imports (optional).
Class or interface definitions.
// This source file must be Drawing.java in the illustration directory.

Package1(RectA.java)
Class : S.Y.BSc(I.T) SEM - IV Subject : Core Java

package area;
public class RectA
{
double a;

public RectA(double len,double brd)


{

a=len*brd;
}

public void show()


{
System.out.println("The area of Rect is :"+a);
}
}

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

public static void main(String args[])


{
circleA c=new circleA(1f);
RectA r = new RectA(3f,4f);
c.show();
r.show();
}
}

First Compile All The package files


Then do this

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[])
{

double rand = Math.random();


System.out.println("Random Number="+rand);
double f = 3.6;
double rund = Math.round(f);
System.out.println("Round Value="+rund);
System.out.println(Math.pow(24,2));

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

}
}

You might also like