Sie sind auf Seite 1von 74

Chapter 1

Software contains instructions tells to computer


Software are developed by Special tools Programming
Language.
Each language has its own strengths and weaknesses.
A computers component are interconnected by a sub system
called bus.

An encoding scheme is a set of rules that govern how a


computer translates numbers, characters, and symbols into
data the computer can actually work with.

Machine Language-
A computers native language , instructions are in the form of
binary code if you want to give an instruction to computer
you have to enter the instructions as binary code.

Assembly language-
Machine language is very difficult .Assembly language is low
level language. Assembly language uses a short descriptive
word mnemonic.
Assembler is used to translate assembly
language into machine code.
High level language-

A program written in high level language is called source


code or source program and computer cannot execute
source code.
Interpreter
Interpreter reads one statement from source code and
translate into machine code or virtual machine code and then
execute it.

Compiler
Compiler translate the entire source code into machine code
and then machine code is finally executed.
Multiprogramming-
Multiprogramming allows multiple programs to run
simultaneously by sharing the same cpu.

Multithreading-
It allows a single program to execute multiple tasks at same
time like we can edit and save data in word at same time.

Multiprocessing or Parallel Processing-


Use two or more processor together to perform subtasks
concurrently and combine solution of subtask to obtain
result.
Java
Introduction-
Java is simple,object-oriented,distributed,interpreted,robust,
secure,architechture neutral,portable,high-performance,
multi-threaded and dynamic.

Java API-
The application program interface (API) also known as library
contains predefined classes and interface for developing java
program.

Three Editions of java


Java SE - known as Java standard edition to develop client
side application.
Java EE-known as java enterprise edition to develop server
side application such as java servlets.
Java ME-known as java micro edition to develop mobile
application such as for android cell.
Example of simple java program-
public class Welcome {
public static void main(String args[]){
System.out.println(Welcome to Java);
}}

A java compiler translate a java source code file into java byte
code and .class file is executed by JVM (Java Virtual machine).

Java language is a high level language but java bytecode is


low level language. The java byte code is similar to the
machine instructions but is architecture neutral and can run
on any platform that has a java virtual machine.

Virtual machine is a program that interprets java bytecode.

Errors that are detected by compiler are called syntax errors


or compile errors.
Chapter- 2
Java Data types , keywords-
+ is also known as string concatenation operator.
Tracing a program is helpful for understanding how program
works and they are useful tools for finding errors in program.
Reading Input from Keyboard-
At Beginning of program - import java.util.Scanner
The Scanner class in java.util package and it imports the class.
There are two type of import statements Specific import and
wildcard import.
Wildcard import - import java.util.*
This imports all the classes in package.
The information for the classes in an imported package is not
read in at compile time or run time unless the class is used in
the program.

At mid of program- Scanner input = new Scanner(System.in);

Syntax [new Scanner(System.in)] creates an object of Scanner


type.
[Scanner input ]declares that input is a variable whose type is
Scanner.
Identifiers
Identifiers are the names that identify the elements such as
class, methods and variables in a program.
Identifiers are for naming variables, methods, classes and
other items in a program.
Descriptive Identifiers make program easy to read.

Variables-
Variables are for representing data of certain types.
The variable declaration tells the compiler to allocate
appropriate memory space for the variable based on its data
types.

int numbers;
double count,area;
Initialization
int number=1;

Every variable has a scope. The scope of variable is the part


of program where the variable can be referenced.
System.out.println(x=1); is equal to
x=1;
System.out.print(x);
i=j=k=1 is equal to

k=1;
j=k;
i=j;

int x=1.0; is illegal because the data type of x is int. we cannot


assign a double value (1.0) to a int variable without using
type casting.
image
Named constant-
A named constant is an identifier that represent a
permanent value.

final datatype constantname = value;


Ex. - final double PI=3.14159;

Naming conversion are used to make your program easy to


read.

Data Types-
1. Object-oriented (Class)
2. Non Object-oriented (Eight primitive data type)
Boolean, byte, long, double, float, int, short, char
These are primitive data types.
Reading of diff. data types from keyboard-
byte bytevalue = input.nextByte();
short shortvalue = input.nextShort();
int intvalue = input.next.Int();

Numeric Operations
Addition (+), Subtraction (-), Multiplication (*), Division (/)
Remainder (%)
Integer Literals
87898978L

long ssn=777_8789_989;

here underscore is used to improve readability;

Augmented Assignment Operator


i+=9 implies that i=i+9;
i-=9 that i=i-9;
i*=9 that i=i*9;
i/=9 i=i/9;

Increment and decrement Operators


i++; postfix increment
++i; prefix increment
--i; decrement
i--; postfix decrement;

int j = ++i;
if i=1 then after the syntax j=2 and i will be also 2
int j = i++;
if i=1 then after the syntax i=2 but j will remain same (j=1)

Same procedure will apply for decrement operator.

Numeric Type Conversion-


Floating point number can be converted into integers using
explicit casting.
Casting is an operation that converts a value of one data type
into a value of another data type.
Chapter-3
Boolean Data type
Declares value is either true or false.

true and false are literals just like a number as 10.treated as


reserved words and cannot be used as identifiers in program.

if statements-
Enables a program to specify alternative paths of execution.

if(Boolean expression)
{
statements;
}
if(n==true)
{

is equivalent to

if ( n)
{

Math.abs(a) Return the absolute value of a.

Generating Random Numbers-


use Math.random(); to obtain a random double value
between 0.0 to 1.0 excluding 1.0

System.exit(status) is defined in system class.


status 0 indicates that program is terminated normally
and a nonzero status indicates abnormal termination.
Logical Operators
The logical operators can be used to create compound
Boolean expression.
Also known as Boolean operators.
Operate on a Boolean value to create new Boolean value.
! This is not operator
&& and operator
|| or operator
^ exclusive or operator

Operator ^
p1 ^ p2
true ^ true will be false.
true ^ false will be true.(both)
false ^ false will be false.

In programming terminology && known as short circuit


operator
|| known as lazy operator.

Switch Statements-
It uses for multiple conditions.
ex. int n = input.nextInt();

switch ( n)
{
case value 1 : ( statement1)
break;
case value2 :(statement2)
break;
default : ( default statement )
break;
value1 and value2 are values of n.
value1 valueN must have same data type.

default case is optional can be used to perform actions when


none of cases matches.
The keyword break is optional , it immediately ends the
switch statement.

Do not forget to use break statement when one is needed.


Once a cased is matched the statements starting from the
matched case are executed until a break statement or and of
switch statement is reached.
Conditional Expression-
(ternary operator )
y=(x>0) ? 1 : -1;
if x is greater than 0 than y=1 otherwise y is equal to -1
Boolean-expression ? expression1 : expression2 ;
if Boolean expression is true than result will expression1
otherwise will expression2;

System.out.println((num % 2 == 0) ? "num is even" : "num


is odd");

Operator Precedence and associativity-


Logical errors are called bugs.
The process of finding errors and correct them is called
debugging.
A common approach to debugging is to use a combination of
method to help the pinpoint the part of program where bug
is located.
hand trace the program (catch errors by reading programs)
insert print statement in order to show the values of
variables.
(That approach will work for small programs)
For complex programs the most efficient way to use a
debugger utility.
JDK includes a command line debugger jdb.
jdb itself a java program, running its own copy of JAVA
interpreter.
Chapter-4
Common Mathematical function-
A method is a group of statements that performs a specific
task.
We have used pow(a,b) to calculate a to the power b.
random() method to generate a random number.
There are other useful Methods in Math class.
Math.PI and Math.E are methods are double constant.

Trigonometric Methods-
sin(radians) Returns trigonometric sine of angle in radian
cos(radians)- .cos.
tan(radians)-tan
toRadians(degree) - returns angle in radians from degree
toDegree (radians) ..degree..radians
asin(a) returns the angle in radians for the inverse of sine.
acos(a)- cos
atan(a)-.tan

Exponent Method-
exp(x) returns e to the power x
log(x)-returns the natural logarithm of x (ln(x))
log10(x) return the base 10 logarithm of x
sqrt(x) return the square root of x
pow(a,b) return a to the power b

The Rounding Methods


ceil(x) x is rounded up to nearest integer and the integer is
returned as double value.
floor(x)- x is rounded down to nearest integer and integer is
returned is double value
rint(x)
round(x)
The min,max and abs method-
Math.max(2, 3) returns 3
Math.max(2.5, 3) returns 4.0
Math.min(2.5, 4.6) returns 2.5
Math.abs(-2) returns 2
Math.abs(-2.1) returns 2.1

a + Math.random() *b returns a random number between a


and a+b excluding a+b
Character data Type and operations
char is used to represent a single character.
char letter = A;
a is string but a is character;

Unicode and ASCII code


Mapping a character to its binary representation is called
encoding.
Unicode originally designed as 16-bit encoding.
a 16-bit Unicode takes two byte preceded by /u and
expressed in four hexadecimal digits that run from /u0000 to
/uFFFF
character 0 Unicode is /u0030
character 9 Unicode is /u0039

char letter = /u0041; here this Unicode is for A sol letter is A

System.out.println(He is\a good boy\ );


output of this is - He is a good boy
\b Backspace
\t - Tab
\n linefeed
\f formfeed
\r carriage return
\\ -Backslash
\ Double Quote

The backslash \ is called an escape character.

char ch = (char)0XAB0041; // The lower 16 bits hex code 0041 is // assigned to ch

isDigit(ch) returns true if character is a digit.


isLetter(ch) if character is a letter.
isLetterOrDigit(ch) if character is letter or digit.
isLowerCase(ch) - if character is lower case
isUpperCase(ch) if character is upper case
toLowerCase(ch) returns lowercase of specified character.
toUpperCase (ch) returns uppercase of specified character.

The String Type


String is a sequence of character.
String java = Hi I am Java;
String is a predefined class in java library just like System and
Scanner Class.
String is not primitive type. It is known as reference type.
Any Java class can be used as a reference type for a variable.
Simple Methods for String
Strings are objects in java.
length()
This method will give the length of String.
String message = Welcome to Java;
System.out.print(Total words is +message.length());
output will be Total words is 15
Welcome to java.length() will give output of also 15
.length() will give 0
Getting Characters From String
s.charAt(index) method is used to retrieve a specific
character from a string s.

Attempting to access characters in a string out of bound of is


a common programming error.

Concatenating Strings -
string s3 = s1.concat(s2);
and a convenient way is
string s3 = s1+s2;
if one of the operands is non string than it is converted to
string;
string s3 = welcome+4;
it will become welcome4;

+= operator can be used


s3+=s2;
than s3 equal to s3+s2;
Converting Strings
Java.toLowerCase();
returns a string java (lower case)
Java.toUpperCase();
returns a string JAVA
trim() is used to eliminate whitespace characters from both
sides of string.
,\n,\t,\r,\f are known as whitespace characters.
Reading a string from console
String s1 =input.next();
and the other way is
String s1 = input.nextLine();
next() method read string until a whitespace appers
nextLine() method read entire line of text and ends when
enter key is pressed.
Reading a character from console
Scanner input = new Scanner(System.in)
String s1 = input.nextLine();
char ch = s1.charAt(0);
System.out.println(Character is +ch);

if(string1==string2)
it doesnt check whether the string1 is equal to string2 it
does only check string1 and string2 refer to the same object.
Comparing of strings
1. equals() method

s1.equals(s2)

if s1 is equal to s2 then it returns true.

2. compareTo() method

s1.compareTo(s2)
if s1 is equal to s2 then it returns 0

if s1 is lexicographically less than s2 it returns ve

if s1 is ,,,,,,,,,,,,,,,,,,,,,,,, greater than s2 retuns +ve

lexicographically == in terms of unicoding

if s1 is abc and s2 is abg

s1.compareTo(s2) will return -4 ( c g);

Another important methods -

equalsIgnoreCase
compareToIgnoreCase

These two methods compare the strings ignoring the


case of letters.

str.startsWith() check if string str starts with

str.endsWith() ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,ends ,,,,,,,

str.contains(s1) check if string str contains string s1.

"Welcome to Java".startsWith("We") returns true.


"Welcome to Java".startsWith("we") returns false.
"Welcome to Java".endsWith("va") returns true.

Obtaining Strings
substring(beginIndex,endIndex)
substring(beginIndex)

if there is no end index than it will go to the end of string.

String message = Welcome to Java;


String message = message.substring(0,11)+HTML;
so now message will be Welcome to HTML

indexOf(s,from index)

Returns the first occurrence of s after the from index

indexOf(s)
Returns the first occurrence of s
lastIndexOf(s,from index)

Returns last index of s before the from index


Conversion between String and Numbers
We can convert a numeric string into a number.
int Intvalue = Integer.parseInt(intString);
where intString is a numeric string such as 12345

To convert a string into a double value


Double.parseDouble(); is used

If the string is not numeric it will cause a run time error.


Integer and Double class are included in java.lang package
so they are automatically imported.

We can convert a number into string by concatenating


String s1 = number + ;
Loops

A loop can be used to tell a program execute statements


repeatedly.
while loop

int count=0;
while(count<100)
{
statement 1;
count++} it runs 100 times.

double item = 1; double sum = 0;


while (item != 0) { // No guarantee item will be 0
sum += item;
item -= 0.1;
}
System.out.println(sum);
Input and output redirections
java Classname < input.txt
This command is called input redirection.The program takes
the input from input.txt
java Classname > output.txt
The command is called output redirection.

The do-while loop-


It is same as the while loop but it executes the loop body first
and then checks the condition to continue the loop.

The for loop -


for(initial condition ; loop continuation condition ; action
after each iteration)
{
}

The initial action initialize control variable.


loop continuation condition is a Boolean expression.
if that Boolean expression is true than loop will execute.
the action after each iteration is executed after every
iteration.
for (int i = 0, j = 0; i + j < 10; i++, j++) {
// Do something
}
The action-after-each-iteration in a for loop can be a list of
zero or more
comma-separated statements. For example:
for (int i = 1; i < 100; System.out.println(i), i++);
This example is correct, but it is a bad example, because it
makes the code difficult to read.

for ( ; ; ) { Equivalent for ( ; true; ) {// Do something} Equivalent while (true) {


// Do something (b) // Do something

} }

(a)
when character is stored under string like above , sequence
of string will be changed.

String s1 = "";
char i = 'A'; char j = 'E';
s1 = i+s1;
s1 = j+s1;
System.out.print(s1);

This will give the output EA not AE;


String s1 = "";
char i = 'A'; char j = 'E';

s1 = i+j+s1;

System.out.print(s1);
This will give output 134 (numeric values) not chracters;
Methods

Methods can be used to define usable codes , organize and


simplify coding.

A method is a collection of statements grouped together to


perform an action.
Defining a method -
A method definition consists of method name , parameters ,
return value type , body .
the method header specifies the modifier , return value type
, method name and formal parameters.
If a method returns a value , it is called value returning
method otherwise is called void method.

The method name and parameter list together constitute the


method signature.
Parameters are optional , a method may contain no
parameter.
the method terminates when return statement is executed.

Calling a method
Calling a method executes code in method.
If a method returns a value a call to method is treated as a
value.
If a method returns a void , a call to method must be a
statement.

Each time a method is invoked , the system creates an


activation record ( activation frame ) that stores the
parameters and the variable for the method and place the
activation record in an area of memory known as a call stack.
A call stack is known as execution stack , runtime stack or
machine stack.

A call stack stores the activation records in a last in , first out


way.
suppose
method m1 calls method m2, and m2 calls method m3.
The runtime system pushes m1s activation
record into the stack, then m2s, and then m3s. After
m3 is finished, its activation record is
removed from the stack. After m2 is finished, its
activation record is removed from the stack.
After m1 is finished, its activation record is removed from
the stack.

Passing arguments by values

When calling a method , you need to provide


arguments in the same order , it is called
parameter order association.

Modularizing Code
Modularizing makes code easy to maintain
and debug and enables the code to reused.

Overloading Methods
overloading methods enables you to define
the methods with the same name as long as
their signatures are different.
Two methods have same name but have
different parameter list within one class , java
compiler determines which method to use
based on method signature.

overload methods must have different


parameter list.
you cannot overloads methods based on
different modifiers or return types.

The Scope of variables


The scope of variable is the part of the
program where the variable can be
referenced.
Method Abstraction and Stepwise
Refinement -
The key to developing a software is to apply
the concept of abstraction.
The client can use a method without knowing
how it is implemented.
The details of implementation are
encapsulated in the method and hidden from
the client who invokes the method.
This is known as information hiding or
encapsulation.
Chapter 7

a single array variable can reference a large collection


of data.
once an array is created , its size is fixed . An array
reference variable is used to access the elements in an
array using an index.
Declaring Array-
elementType[] arrayRefVar ;
Ex
double[] mylist;
This is preferred style in Java and can be declared like
in c/c++;
unlike declaration of primitive data types , the
declaration of array variable does not allocate
any space in the memory of array. It creates only
a storage location for the reference to array.
array and array variable both are different.
double[] mylist = new double[20];
here mylist is an array variable that assigned to an
array that contains 20 element.
Size of an array-
arrayRefVar.length gives length
ex -
mylist.length

size of an array cant be changed after the array is


created.
default value of array element for int array is 0
false for Boolean and \u0000 for char array.

foreach loop
for(double e : mylist)
{
System.out.print(e);}
If mylist is an array than it will print whole array.
Copying array
suppose we have 2 array
if list1 = list2 (assign one array reference to
another)
then this statement does not copy array contents
but merely copy the reference value.
3 ways to copy array
- by for loop
- use arraycopy method in system class
- use clone method

arraycopy mehod in java.lang.System


Syntax is
arraycopy(sourceArray,srcPos,targetArray,tarPos,
length);
srcPos and tarPos are starting point in Source
array and in target array.
The Number of element defined by length.
Passing array to method -

difference in passing primitive data type and


array.
for primitive type arguments value is passed.
and for array the value of argument is referenced
to an array.
Arrays are object in java and jvm stores the object in area of
memory called heap , which is used for dynamic memory
allocation.
Returning an array from a method

Variable length argument list


a variable numbers of arguments of the same type can be
passed to a method and treated as an array.
here we use ellipsis ( . . .) parameter
Searching array -

if an array is sorted , binary search is more efficient than


linear search for finding an element in the array.

Binary search Approach


Binary search is other common search approach for a list of
values.
3 Cases
if the key is less than the middle element than you have
to search in the half of the array.
If the key is equal to the middle element, search ends
with match.
If the key is greater than middle element , you need to
continue to search for the key only in second half of the
array

Sorting arrays -
selection array

In selection sort we first find smallest than replace it with 1st


element than find smallest except 1st element and replace it
with 2nd element and furthermore.
Array Class
java.util.Array
This contains method for searching and sorting , comparing
arrays , filling array elements.

if number is an array than


java.util.Arrays.sort(number);
This will short the whole array.
This will sort from char[1] to char[3-1]
parallel sort is more efficient if a computer has multicore
processor.
java.util.Arrays.binarySearch(number , 11);
This method will return the index of 11 in number array.
if key is not found then it will return (insertionIndex+1)

java.util.Arrays.equals( array1 , array2);


will return true and false.

Command Line Arguments


The main method can receive String from command line
(String[] args)
Main Method is just a normal method.
When main method is invoked the java interpreter creates an
array to hold the command-line argument and pass the
reference to args.
When the main method is invoked, the Java interpreter creates an array
to hold the command-
line arguments and pass the array reference to args. For example, if you
invoke a
program with n arguments, the Java interpreter creates an array like this
one:
args = new String[n];
The Java interpreter then passes args to invoke the main method.
Multidimensional Array
Elements can be accessed through row and column index.

Ragged Arrays-
Rows can have different lengths , this type of array known as
ragged array.
Passing 2 dimensional array to Methods-
Just simple , pass as 1-D array
Object And Classes

Introduction-
Object oriented programming enables you to develop large
scales software and GUI.
Defining classes for Objects-
A class defines the properties and behaviour of an object.
OOP involves programming using objects.
An object has a unique identity , state and behaviour.
The state of an object (also known as properties and
attributes) is represented by data fields with their
current values.
The behaviour of an object (known as its actions) is
defined by methods.

A class is a template , blue print or contract that defines


what an objects data field and methods will be.
The relation between class and object is analogous to recipe
and product.
you can make as many product you want from single recipe.
A java class uses variables to define data fields and metods to
define actions.
A class provide method of special type , known as
constructors , which are invoked to create a new object.

A class is template for creating object.

Lets take an example

class SimpleCircle{
double radius; (data field)

SimpleCircle() /**Construct a circle with radiu 1*/


{radius = 1;}
SimpleCircle(double newradius)
{ radius = newradius; /*Construct a circle with specified no.*/
}
double getarea()
{return radius*radius*Math.pi;}
double getperimeter()

{return 2*Math.Pi*radius;}
void setradius(double newradius)
{radius = newradius;}
}

This is a SimpleCircle Class.


Program that uses this class is client of this class.
You can put two classes into one file but only one class can
be public. Public class must have same name as file name.

The illustration of class templates and objects can be


standardized using Unified Modeling Language (UML)
notation.

We can test a class by adding a method to it.


A constructor is invoked to create an object using new
operator.
Constructor must have same name as class.
Constructor do not have a return type.
Constructor are invoked using new operator when an
object is created. Constructor play the role of initializing
objects.

Constructor can be overloaded (multiple constructor can


have same name but differing signature)
Constructor are used to construct objects.
new ClassName(arguments);
A class normally provides a constructor without arguments
(e.g., Circle()). Such a constructor
is referred to as a no-arg or no-argument constructor.
A class may be defined without constructors. In this case, a
public no-arg constructor with
an empty body is implicitly defined in the class. This
constructor, called a default constructor,
is provided automatically only if no constructors are
explicitly defined in the class.
Accessing objects via Reference variable-
An objects data and methods can be accessed through the
dot(.) operator via objects reference variable.

A class essentially a programmer defined type. A class is a


reference type.
Circle myCircle();
This statement declares the variable myCircle to be of
Circle type.
myCircle = new Circle();
This creates a new object and assign it reference to Circle.
and from both above we can write
Circle mycircle = new Circle();

The variable myCircle holds a reference to a Circle object.

Objct vs Object referencr variable-


An object reference variable actually contains a reference
to the object.
An object reference variable and objects are different but
most of the distinction can be ignored.
myCircle is a variable that contains reference to Circle
object.
Arrays are treated as object in JAVA.
Accessing Objects data and methods-
In OOP , objects member reference to its data field and
methods.
After an object is created , its data can be accessed and its
method can be invoked using dot operator (.)
also known as the object member access operator.

The data field radius is referred to as instance variable ,


because it is dependent on specific instance.

Method getarea() referred to as an instance method.

Remember in Math class we invoked methods from


Math.pow();
but we cant invoke like Circle.getArea();
We have to write like myCircle.getArea(); means we can
invoke through the object.
This is because all the methods in Math class are static ,
which are defined using static keyword.
Java assigns no default value to a local variable inside a
method.

Difference between variable of primitive types and


reference types-

Using Classes From JAVA Library


1. The Date Class

java.util.Date class
From date.getTime() method we get Total milliseconds
elapsed since 1 Jan 1970.

And date.toString()

We get exact Date and Time.

Date class has an another constructer

Date(long elapseTime)

Which can be used to construct a Date object for a given


time in milliseconds elapsed since 1 jan 1970

Random Class-
Math.random()
obtain a double value between 0.0 to 1.0
java.util.Random
This class generate random number of int , float , double ,
Boolean , long.
when you create a random object , you have to specify a
seed or use the default seed.
A seed is a number used to initialize a random number
generator.

If two random object have same seed then they will produce
same random numbers.

Point 2-D Class-


This class in
javafx.geomatry package
import javafx.geomatry.Point2D;
Point2D p1 = new Point2D(5,-7)

p1 object with x coordinate 5 and y -7


same here as p2

now
p1.distance(p2);
This calculate distances b/w p1 and p2
p1.toString(); return x and y of p1

p1.getX(); returns x of p1

Static variables , Constants and methods-

A static variable is shared by all objects of class.


A static method cant access instance member of class.
The data field radius in Circle class is known as instance
member.

Circle circle1 = new Circle();

Circle circle2 = new Circle(5);


radius in circle1 is different from radius in circle2 and also
stored in different memory location.

If you want all the instance of a class to share data use static
variables known as class variables.
Static variables store values for the variables in a common
memory location.
Because of this common location , if one object changes the
value of static variable all object of same class are affected.

Static methods can be called without creating an instance


of the class.

All the methods in Math class are static and main method
is static too.
Instance variables can accessed via reference variable.
Static variable and static methods can be accessed from
reference variable or from their class name.
Ex-
If our class name is TestCircleWithStaticMembers
then
TestCircleWithStaticMembers . numberOfObjects;
Visibility Modifiers-
Visibility modifiers can be used to specify the visibility of a
class and its members.
If no visibility modifier is used , then by default the classes ,
methods and data fields are accessible by any class in the
same package.
This is known as package private or package access.

Packages can be used to organise the classes.


So we need to define following statement
package packagename;

If a class if defined without package , then it is said to be


placed in default package.

Private and Protected Modifiers

The Private modifiers makes method and data fields


accessible only from within its own class.
private modifier applies only to the member of class.

public modifier can apply to a class or member of a class.

public and private modifier on local modifier cause a


compile time error.

In most cases constructor should be public


if you want to prohibit user from creating a instance of
class , use private constructor.

all data-fields and methods are static in Math class of java.


To prohibit user from creating a instance of class we use
private Math(){
}

Data Filed Encapsulation-


make data field private protected data and makes the class
easy to maintain.
In public data field , data fields can be changed by its
clients .
We make data fields private , so that objects outside the
class cant modify data field.
ex-
c1.radius = 10;
this statement can modify radius from outside of class.

The class become difficult maintain and vulnerable to


bugs.
To prevent direct modification of data field , you should
declare the data field prive , by using private modifier.

This is known as data field encapsulation.


A private data field cannot be accessed from outside the
class.
However a client often need to modify the data fields.
We use getter and setter methods referred to as accesser
and mutator.
In this Program setRadius() method is used to change the
radius .
And getRadius() method is used to get the data field radius
value.
We cannot directly access the radius.

The data field radius is declared private. Private data can


be accessed only within their defining class.
so we cant use myCircle.radius in this program that will
cause a compile time error.
Since numberOfObject is static and private so it cant be
modified.
This prevent tempering.

Passing Objects to Methods-


Passing an object to a method is to pass the reference of
the object.

Java use only one mode of passing arguments pass by


value.
public class Test {
public static void main(String[] args) {
int[] a = {1, 2};
swap(a[0], a[1]);
System.out.println("a[0] = " + a[0]
+ " a[1] = " + a[1]);
}
public static void swap(int n1, int n2) {
int temp = n1;
n1 = n2;
n2 = temp;
}
}
The output of this code is a[0] = 1
a[1]= 2

Array of Objects-
An array can hold objects as well as primitive data types.
So following statements will create an array of objects.

Circle[] circlearray = new Circle[10];


This will create an array of 10 objects and we can initialize
by using for loop.

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


{
circlearray[i] = new Circle();
}
Immutable Objects and classes

Das könnte Ihnen auch gefallen