Unit 2 - Java
Unit 2 - Java
Programming Practice
Unit II
31-08-2023 Dr.R.Kayalvizhi,
Dr.R.Kayalvizhi, Assistant
AssistantProfessor
Professor//NWC
NWC 2
Java platform features
1. Compiled and Interpreter:- has both Compiled and Interpreter Feature Program of java is First
Compiled and Then it is must to Interpret it. First of all The Program of java is Compiled then
after Compilation it creates Bytes Codes rather than Machine Language. Then After Bytes
Codes are Converted into the Machine Language is Converted into the Machine Language with
the help of the Interpreter So For Executing the java Program First of all it is necessary to
Compile it then it must be Interpreter
2. Platform Independent:- Java Language is Platform Independent means program of java is Easily
transferable because after Compilation of java program bytes code will be created then we have
to just transfer the Code of Byte Code to another Computer. This is not necessary
for computers having same Operating System in which the code of the java is Created and
Executed After Compilation of the Java Program We easily Convert the Program of the java top
the another Computer for Execution.
3. Object-Oriented:- We Know that is purely OOP Language that is all the Code of the java
Language is Written into the classes and Objects So For This feature java is Most Popular
Language because it also Supports Code Reusability, Maintainability etc.
// Constructor
public Circle (double x, double y, double r) {
this.x = x;
this.y = y;
this.r = r;
}
//Methods to return circumference and area
public double circumference() { return 2*3.14*r;}
public double area() { return 3.14 * r * r; }
}
• Encapsulation, safely sealing data within the capsule of the class Prevents programmers from relying on
details of class implementation, so you can update without worry
• Helps in protecting against accidental or wrong usage.
• Keeps code elegant and clean (easier to maintain)
• Private fields or methods for a class only visible within that class. Private members are not visible
within subclasses, and are not inherited.
• Protected members of a class are visible within the class, subclasses and also within all classes that are
in the same package as that class.
• Of the eight primitive types available in Java, the programs in this text use only the following four:
int This type is used to represent integers, which are whole numbers such as 17 or –53.
double This type is used to represent numbers that include a decimal fraction, such as
3.14159265. In Java, such values are called floating-point numbers; the name
double comes from the fact that the representation uses twice the minimum
precision.
boolean This type represents a logical value (true or false).
char This type represents a single character and is described in Chapter 8.
• Most declarations appear as statements in the body of a method definition. Variables declared in this
way are called local variables and are accessible only inside that method.
• Variables may also be declared as part of a class. These are called instance variables and are covered
in Chapter 6.
• The most common operators in Java are the ones that specify arithmetic computation:
+ Addition * Multiplication
– Subtraction / Division
% Remainder
• Operators in Java usually appear between two subexpressions, which are called its operands.
Operators that take two operands are called binary operators.
• The - operator can also appear as a unary operator, as in the expression -x, which denotes the
negative of x.
• This rule has important consequences in the case of division. For example, the
expression
14 / 5
seems as if it should have the value 2.8, but because both operands are of type int, Java computes
an integer result by throwing away the fractional part. The result is therefore 2.
• If you want to obtain the mathematically correct result, you need to convert at least one operand to a
double, as in
(double) 14 / 5
The conversion is accomplished by means of a type cast, which consists of a type name in
parentheses.
run:
Integer outcome was: 3
BUILD SUCCESSFUL (total time: 1 second)
double c = 100;
double f = 9 / 5 * c + 32;
9 / 5 * c + 32
31-08-2023 Dr.R.Kayalvizhi, Assistant Professor / NWC 38
The Pitfalls of Integer Division
You can fix this problem by converting the fraction to a double, either by inserting decimal points or by
using a type cast:
double c = 100;
double f = (double) 9 / 5 * c + 32;
180.0
1.8
9.0
(double) 9 / 5 * c + 32
31-08-2023 Dr.R.Kayalvizhi, Assistant Professor / NWC 39
The Remainder Operator
• The only arithmetic operator that has no direct mathematical counterpart is %, which applies only to
integer operands and computes the remainder when the first divided by the second:
14 % 5 returns 4
14 % 7 returns 0
7 % 14 returns 7
• The result of the % operator make intuitive sense only if both operands are positive. The examples
in this book do not depend on knowing how % works with negative numbers.
• The remainder operator turns out to be useful in a surprising number of programming applications
and is well worth a bit of study.
highest
unary - (type cast)
* / %
+ -
lowest
Thus, Java evaluates unary - operators and type casts first, then the operators *, /, and %, and then
the operators + and -.
• Precedence applies only when two operands compete for the same operator. If the operators are
independent, Java evaluates expressions from left to right.
• Parentheses may be used to change the order of operations.
42
3
2
3
0
2
0 4
3
3 8
0
1
( 1 + 2 ) % 3 * 4 + 5 * 6 / 7 * ( 8 % 9 ) +
31-08-2023 Dr.R.Kayalvizhi, Assistant Professor / NWC
0 42
Assignment Statements
• You can change the value of a variable in your program by using an assignment statement, which has
the general form:
variable = expression;
• The effect of an assignment statement is to compute the value of the expression on the right side of
the equal sign and assign that value to the variable that appears on the left. Thus, the assignment
statement
where op is any of Java’s binary operators. The effect of this statement is the same as
salary *= 2;
31-08-2023 Dr.R.Kayalvizhi, Assistant Professor / NWC 44
Increment and Decrement Operators
• Another important shorthand form that appears frequently in Java programs is the increment
operator, which is most commonly written immediately after a variable, like this:
x++;
The effect of this statement is to add one to the value of x, which means that this statement is
equivalent to
x += 1;
or in an even longer form
x = x + 1;
• The -- operator (which is called the decrement operator) is similar but subtracts one instead of adding
one.
• The ++ and -- operators are more complicated than shown here, but it makes sense to defer the
details until Chapter 11.
• There are six relational operators that compare values of other types and produce a boolean result:
• It is not legal in Java to use more than one relational operator in a single comparison as is often done
in mathematics. To express the idea embodied in the mathematical expression
0 ≤ x ≤ 9
you need to make both comparisons explicit, as in
0 <= x && x <= 9
• The || operator means either or both, which is not always clear in the English interpretation of or.
• Be careful when you combine the ! operator with && and || because the interpretation often differs
from informal English.
/*
31-08-2023
if ( Math.abs(reciporcal * num - 1.0) < 1e-5)
Dr.R.Kayalvizhi, Assistant Professor / NWC 57
Using ==, cont.
• == is not appropriate for determining if two objects have the same value.
• if (s1 == s2)
• determines only if s1 and s2 are at the same memory location.
• If s1 and s2 refer to strings with identical sequences of characters, but stored in different
memory locations
• (s1 == s2) is false.
> compareTo( )
< [lexicographical ordering]
>=
<=
n != 0 && x % n == 0
is not evaluated at all because n != 0 is false. Because the expression
• One of the advantages of short-circuit evaluation is that you can use && and || to prevent execution
errors. If n were 0 in the earlier example, evaluating x % n would cause a “division by zero” error.
• The table below shows all Java operators from highest to lowest precedence, along with their
associativity.
• Most programmers do not memorize them all, and even those that do still use parentheses for
clarity.
• class BankBalance
• Different indentation
first form second form
if (a > b) if (a > b)
if (c > d) if (c > d)
e = f; e = f;
else else
g = h; g = h;
• The action for each case typically ends with the word break.
• The optional break statement prevents the consideration of other cases.
• The controlling expression can be anything that evaluates to an integral type (integer or
character).
• syntax
switch (Controlling_Expression)
{
case Case_Label:
Statement(s);
break;
case Case_Label:
…
default:
…
}
• if statement (1 or 2 branches)
• Multi-branch if-else-if statement (3 or more branches)
• Multi-branch switch statement
• Conditional operator ? :
• syntax
while (Boolean_Expression)
Body_Statement
or
while (Boolean_Expression)
{
First_Statement
Second_Statement
…
}
• class BugTrouble
• example
for (n = 1, p = 1; n < 10; n++)
p=p*n
• Only one boolean expression is allowed, but it can consist of &&s, ||s,
and !s.
• Multiple update actions are allowed, too.
for (n = 1, p = 100; n < p; n++, p -= n)
• rarely used
• If you know how many times the loop will be iterated, use a for loop.
• If you don’t know how many times the loop will be iterated, but
• it could be zero, use a while loop
• it will be at least once, use a do-while loop.
• Generally, a while loop is a safe choice.
• while loop
• do-while loop
• for loop
•Two types
•Single dimensional
• Also known as linear array
• Elements are stored in a single row
•Multidimensional
• It is a combination of two or more arrays or nested arrays
• Arrays of array with each element of the array holding the
reference of other array
• Also called Jagged Arrays
• Syntax Example
0 1 2 3 4 5 6 7 8 9
2 1 11 -9 2 1 11 90 101 2
• We define
• int[] prime=new long[20];
MorePrimes.java:5: incompatible types
found: long[]
required: int[]
int[] primes = new long[20];
^
• The right hand side defines an array, and thus the array variable should
refer to the same type of array
Sample Program
class MinAlgorithm
{
public static void main ( String[] args )
{
int[] array = { -20, 19, 1, 5, -1, 27, 19, 5 } ;
int min=array[0]; // initialize the current minimum
for ( int index=0; index < array.length; index++ )
if ( array[ index ] < min )
min = array[ index ] ;
System.out.println("The minimum of this array is: " + min );
}
}
• Two-Dimensional arrays
• float[][] temperature=new float[10][365];
• 10 arrays each having 365 elements
• First index: specifies array (row)
• Second Index: specifies element in that array (column)
• In JAVA float is 4 bytes, total Size=4*10*365=14,600 bytes
int[][] array2D = { {99, 42, 74, 83, 100}, {90, 91, 72, 88, 95}, {88, 61,
74, 89, 96}, {61, 89, 82, 98, 93}, {93, 73, 75, 78, 99}, {50, 65, 92, 87,
94}, {43, 98, 78, 56, 99} };
//5 arrays with 5 elements each
Syntax
arrayName=new data-type[size1][size2];
Example
intArray=new int[5][5];
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.println(intArray[i][j]);
class B extends A
• Although a subclass includes all of the members of its superclass, it cannot access
those members of the superclass that have been declared as private. For example,
consider the following simple class hierarchy:
• In a class hierarchy, private members remain private to their class.
• This program will not compile because the use of j inside the sum( ) method of B
causes an access violation. Since j is declared as private, it is only accessible by
other members of its own class. Subclasses have no access to it.
• A subclass can call a constructor defined by its superclass by use of the following
form of
• super:
super(arg-list);
• Here, arg-list specifies any arguments needed by the constructor in the superclass.
super( ) must always be the first statement executed inside a subclass’ constructor.
• To see how super( ) is used, consider this improved version of the BoxWeight
class:
• When a class hierarchy is created, in what order are the constructors for the
classes that make up the hierarchy executed? For example, given a subclass
called B and a superclass called A, is A’s constructor executed before B’s,
or vice versa?
• answer is that in a class hierarchy, constructors complete their execution in
order of derivation, from superclass to
subclass.
Further, since super( ) must be the first statement executed in a subclass
constructor, this order is the same whether or not super( ) is used.
If super( ) is not used, then the default or parameterless constructor of each
superclass will be executed
class A {
A() {
class B extends A {
B() {
class C extends B {
C() {
class CallingCons {
C c = new C();
k: 3
System.out.println(msg + k);
class A {
}
int i, j;
}
A(int a, int b) {
i = a;
j = b;
Override {
} public static void main(String args[]) {
// display i and j B subOb = new B(1, 2, 3);
System.out.println("i and j: " + i + " " + j); subOb.show(); // this calls show() in A
} }
}
}
The output produced by this program is shown here:
// Create a subclass by extending class A.
This is k: 3
class B extends A {
i and j: 1 2
int k;
The version of show( ) in B takes a string parameter. This makes its type
B(int a, int b, int c) { signature
• Method overriding forms the basis for one of Java’s most powerful
concepts: dynamic method dispatch.
• Dynamic method dispatch is the mechanism by which a call to an
overridden method is resolved at run time, rather than compile time.
• Dynamic method dispatch is important because this is how Java
implement run-time polymorphism.
} r = c; // r refers to a C object
class B extends A { }
// override callme() }
class C extends A {
// override callme() This program creates one superclass called A and two subclasses of it,
called B and C. Subclasses B and C override callme( ) declared in A.
void callme() { Inside the main( ) method, objects of type A, B, and C are declared. Also, a
reference of type A, called r, is declared. The program then in turn assigns
System.out.println("Inside C's callme method"); a reference to each type of object to r and uses that reference to invoke
} callme( ). As the output shows, the version of callme( ) executed is
determined by the type
}
of object being referred to at the time of the call. Had it been determined by
class Dispatch { the type of the reference variable, r, you would see three calls to A’s
callme( ) method.
public static void main(String args[]) {
double dim2; }
double area() { }
} figref = r;
} }
abstract class A {
void callmetoo() {
class B extends A {
void callme() {
class AbstractDemo {
B b = new B();
b.callme();
b.callmetoo();
Although they are similar to abstract classes, interfaces have an additional capability:
A class can implement more than one interface. By contrast, a class can only inherit a single
superclass (abstract or otherwise).
• the Java run-time system uses the current working directory as its starting point.
• Thus, if your package is in a subdirectory of the current directory, it will be found.
• Second, you can specify a directory path or paths by setting the CLASSPATH
environmental variable.
• Third, you can use the -classpath option with java and javac to specify the path
to your classes.
• Remember, you will need to be in the directory above • • Subclasses in the same package
MyPack when you execute this command. (Alternatively, • • Non-subclasses in the same package
you can use one of the other two options described in
thepreceding section to specify the path MyPack.) • • Subclasses in different packages
• As explained, AccountBalance is now part of the package • • Classes that are neither in the same package nor subclasses
MyPack. This means that it cannot be executed by itself.
That is, you cannot use this command line:
• java AccountBalance • The three access modifiers, private, public, and protected,
provide a variety of ways to produce the many levels of
access required by these categories. Table 9-1 sums up the
AccountBalance must be qualified with its package name. interactions.
class TestIface2 {
c.callback(42);
c.callback(42);
p squared is 1764
• You can use interfaces to import shared constants into multiple classes by simply declaring an
interface that contains variables that are initialized to the desired values.
• When you include that interface in a class (that is, when you “implement” the interface), all of
those
• variable names will be in scope as constants
System.out.println("Yes"); answer(q.ask());
break; answer(q.ask());
case MAYBE: }
System.out.println("Maybe"); }
• One interface can inherit another by use of the keyword extends. The syntax is the
same as for inheriting classes. When a class implements an interface that inherits
another interface, it must provide implementations for all methods required by the
interface inheritance chain.
• Following is an example:
1) Abstract class can have abstract and non-abstract methods. Interface can have only abstract methods. Since Java 8, it can
have default and static methods also.
2) Abstract class doesn't support multiple inheritance. Interface supports multiple inheritance.
3) Abstract class can have final, non-final, static and non-static Interface has only static and final variables.
variables.
4) Abstract class can provide the implementation of interface. Interface can't provide the implementation of abstract class.
5) The abstract keyword is used to declare abstract class. The interface keyword is used to declare interface.
6)Example: Example:
public abstract class Shape{
public abstract void draw(); public interface Drawable{
} void draw();
}