0% found this document useful (0 votes)
74 views

2017 Java-Chapter 1-2

This document provides an introduction to Java programming including: 1. A brief history of Java from its origins in 1990 at Sun Microsystems to recent releases. 2. An overview of Java features including being compiled and interpreted, platform independent, object-oriented, robust and secure, and multithreaded. 3. Explanations of Java concepts such as identifiers, variables, data types, the Java Virtual Machine, Java environment and development tools, and a simple "Hello World" Java program example.

Uploaded by

negasso birku
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
74 views

2017 Java-Chapter 1-2

This document provides an introduction to Java programming including: 1. A brief history of Java from its origins in 1990 at Sun Microsystems to recent releases. 2. An overview of Java features including being compiled and interpreted, platform independent, object-oriented, robust and secure, and multithreaded. 3. Explanations of Java concepts such as identifiers, variables, data types, the Java Virtual Machine, Java environment and development tools, and a simple "Hello World" Java program example.

Uploaded by

negasso birku
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 19

Chapter - 1

Introduction to java programming

1-1 java basics


1-2 identifiers, keywords, variables, datatypes,
1-3 java operators, simple java programs
1-4 control structures and loop structures

1-1 Java basics


Java is a general-purpose, object-oriented programming language developed by Sun
Microsystems of USA in 1991.Originally called Oak by James Gosling. Java was invented
for the development of software for consumer electronic devices like TVs, micro waves,
etc. The main aim had to make java simple, portable and reliable.
Year Progress
1990 Sun decided to developed software that could be used for electronic devices. And the
project called as Green Project head by James Gosling.
1991 Announcement of a new language named ―Oak
1992 The team verified the application of their new language to manage a list of home
appliances using a hand held device.
1993 The World Wide Web appeared on the Internet and transformed the text-based interface
to a graphical rich environment.
1994 The team developed a new Web browsed called ―Hot Java to locate and run Applets.
1995 Oak was renamed to Java. Many companies such as Netscape and Microsoft announced
their support for Java.
1996 Java language is now famous for Internet programming. JDK 1.0 released
1997 Sun releases Java Development Kit(JDK 1.1)
1998 Sun releases Software Development Kit (JDK 1.2)
1999 Sun releases Java 2 platform Standard Edition (J2SE) and Enterprise Edition(J2EE).
2000 J2SE1.3 with JDK 1.3 was released.
2002 J2SE1.4 with JDK 1.4 was released.
2004 J2SE5 with JDK 5.0 was released.
2006 JSE 6 with JDK 6.0 was released
2011 JSE 7 with JDK 7.0 was released
2014 JSE 8 with JDK 8.0 was released
2017 JSE 9 with JDK 9.0 was released

Features of Java are as follows:


1. Compiled and Interpreted
2. Platform Independent and portable
3. Object- oriented
4. Robust and secure
5. Multithreaded and Interactive

1. Compiled and Interpreted

1
Basically a computer language is either compiled or interpreted. Java comes together both
these approach thus making Java a two-stage system.
Java compiler translates Java code to Bytecode instructions and Java Interpreter generate
machine code that can be directly executed by machine that is running the Java program.
2. Platform Independent and portable
Java supports the feature portability. Java programs can be easily moved from one
computer system to another and anywhere. Changes and upgrades in operating systems,
processors and system resources will not force any alteration in Java programs. This is
reason why Java has become a trendy language for programming on Internet which
interconnects different kind of systems worldwide. Java certifies portability in two ways.
First way is, Java compiler generates the bytecode and that can be executed on any
machine. Second way is, size of primitive data types are machine independent.
3. Object- oriented
Java is truly object-oriented language. In Java, almost everything is an Object. All
program code and data exist in objects and classes. Java comes with an extensive set of
classes; organize in packages that can be used in program by Inheritance. The object
model in Java is trouble-free and easy to enlarge.
4. Robust and secure
Java is a strictly typed language which provides many securities to make certain reliable
code by emphasizing on compile time and run time error checking. It is design as garbage
–collected language, which helps the programmers free from all memory management
problems. Java also includes the concept of exception handling, which detain serious
errors and reduces all kind of threat of crashing the system.
Security is an important feature of Java and this is the strong reason that programmer use
this language for programming on Internet. The absence of pointers in Java ensures that
programs cannot get right of entry to memory location without proper approval.
7. Multithreaded and Interactive
Multithreaded means managing multiple tasks simultaneously. it is possible to write
programs that can do many tasks simultaneously. That means we need not wait for the
application to complete one task before starting next task. This design feature allows
developers to construct smoothly running interactive and graphic applications.

Java Virtual machine:


As we know that all programming language compilers convert the source code to machine
code. But Java compiler convert the source code into Intermediate code is called as
bytecode. This byte code is interpreted by a interpreter called the Java Virtual machine
and it exits only inside the computer memory.

2
Java Environment:
Java environment includes a number of development tools, classes and methods. The
development tools are part of the system known as Java Development Kit (JDK) and the
classes and methods are part of the Java Standard Library (JSL), also known as the
Application Programming Interface (API).
Java Development kit (JDK) – The JDK comes with a set of tools that are used for
developing and running Java program. It includes:
1. Appletviewer( It is used for viewing the applet)
2. Javac(It is a Java Compiler)
3. Java(It is a java interpreter)
4. Javap(Java diassembler,which convert byte code into program description)
5. Javadoc(It is for creating HTML document)
Simple Java Program:
//write a java program to display your name
import java.io.*;
class First
{
public static void main(String args[])
{
System.out.println("Dr VASU");
}
}

The file must be named ―FirstProgram.java to equivalent the class name containing the
main method. Java is case sensitive. This program defines a class called ―FirstProgram.
A class is an object oriented term. It is designed to perform a specific task. A Java class is
defined by its class name, an open curly brace, a list of methods and fields, and a close
curly brace.
The name of the class is made of alphabetical characters and digits without spaces, the
first character must be alphabetical.
The line ―public static void main (String [] args ) shows where the program will start
running. The word main means that this is the main method –
The JVM starts running any program by executing this method first.
The main method in ―FirstProgram.java consists of a single statement
System.out.println("This is my first program");
The statement outputs the character between quotes to the console.
Above explanation is about how to write program and now we have to learn where to
write program and how to compile and run the program.
For this reason, the next explanation is showing the steps.
1. Edit the program by the use of Notepad.

3
2. Save the program to the hard disk.
3. Compile the program with the javac command.(Java compiler)
4. If there are syntax errors, go back to Notepad and edit the program.
5. Run the program with the java command.(Java Interpreter)
6. If it does not run correctly, go back to Notepad and edit the program.
7. When it shows result then stop.
About Java programs, it is very important to keep in mind the following points.
 Case Sensitivity - Java is case sensitive which means identifier Hello and hello
would have different meaning in Java.
 Class Names - For all class names the first letter should be in Upper Case.
If several words are used to form a name of the class each inner words first letter
should bein Upper Case.Example class MyFirstJavaClass
 Method Names - All method names should start with a Lower Case letter.
If several words are used to form the name of the method, then each inner word's
first letter should be in Upper Case.Example public void myMethodName()
 Program File Name - Name of the program file should exactly match the class
name.
When saving the file you should save it using the class name (Remember java is
case sensitive) and append '.java' to the end of the name. (if the file name and the
class name do not match your program will not compile).
Example : Assume 'MyFirstJavaProgram' is the class name. Then the file should be
saved as 'MyFirstJavaProgram.java'
 public static void main(String args[]) - java program processing starts from the
main() method which is a mandatory part of every java program..

1-2 identifiers, keywords, variables, datatypes,

Java Identifiers:
All java components require names. Names used for classes, variables and methods are
called identifiers. In java there are several points to remember about identifiers. They are
as follows:
 All identifiers should begin with a letter (A to Z or a to z ), currency character ($)
or an underscore (-).
 After the first character identifiers can have any combination of characters.
 A key word cannot be used as an identifier.
 Most importantly identifiers are case sensitive.
 Examples of legal identifiers:age, $salary, _value, __1_value
 Examples of illegal identifiers : 123abc, -salary
Java Variables:
We would see following type of variables in Java:
 Local variables: Variables defined inside methods, constructors or blocks are
called local variables. The variable will be declared and initialized within the
method and the variable will be destroyed when the method has completed.

4
 Instance variables (Non static variables): Instance variables are variables within a
class but outside any method. These variables are instantiated when the class is
loaded. Instance variables can be accessed from inside any method, constructor or
blocks of that particular class.
 Class variables (Static Variables): Class variables are variables declared with in a
class, outside any method, with the static keyword.

Java Keywords:
The following list shows the reserved words in Java. These reserved
words may not be used as constant or variable or any other identifier
names.
Abstract Assert boolean break
Byte Case catch char
Class Const continue default
Do Double else enum
Extends Final finally float
For Goto if implements
Import Instanceof int interface
Long Native new package
Private Protected public return
Short Static strictfp super
Switch Synchronized this throw
Throws Transient try void
Volatile While

Comments in Java
Java supports single line and multi-line comments very similar to c and
c++. All characters available inside any comment are ignored by Java
compiler.
public class MyFirstJavaProgram{
/* This is my first java program.
* This is an example of multi-line comments.
*/
public static void main(String []args){
// This is an example of single line comment
/* This is also an example of single line comment. */
System.out.println("Hello World");
}
}

5
Data Types in Java
There are eight primitive data types supported by Java. Primitive data types are predefined
by the language and named by a key word. Let us now look into detail about the eight
primitive data types.
 Byte
 short
 int
 long
 float
 double
 boolean
 char
Java Literals:
A literal is a source code representation of a fixed value. They are represented directly in
the code without any computation.
Literals can be assigned to any primitive type variable. For example:
byte a = 68;
char a = 'A'
String literals in Java are specified like they are in most other languages by enclosing a
sequence of characters between a pair of double quotes. Examples of string literals are:
"Hello World"
"two\nlines"
"\"This is in quotes\""
Java language supports few special escape sequences for String and char literals as well. They are:
Notation Character represented
\n Newline (0x0a)
\b Backspace (0x08)
\s Space (0x20)
\t Tab
\" Double quote
\' Single quote
\\ Backslash

Java Access Modifiers:


Java provides a number of access modifiers to set access levels for classes, variables,
methods and constructors. The four access levels are:
Access Modifiers: default, public, protected, private
1. Visible to the package. The default. No modifiers are needed.
2. Visible to the class only (private).
3. Visible to the world (public).

6
4. Visible to the package and all subclasses (protected).
non Access Modifiers:
Java provides a number of non-access modifiers to achieve many other functionality.
 The static modifier for creating class methods and variables
 The final modifier for finalizing the implementations of classes, methods, and
variables.
 The abstract modifier for creating abstract classes and methods.
 The synchronized and volatile modifiers, which are used for threads.

1.3 java Operators and sample java programs


Java provides a rich set of operators to manipulate variables. We can divide all the Java
operators into the following groups:
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
5. Increment and decrement operators

Arithmetic operators ( +, -, *, /, % )
The five arithmetical operations supported by the java language are:
+ addition
- subtraction
* multiplication
/ division
% modulo
Operations of addition, subtraction, multiplication and division literally correspond with
their respective mathematical operators. The only one that you might not be so used to see
is modulo; whose operator is the percentage sign (%). Modulo is the operation that gives the
remainder of a division of two values. For example, if we write:
a = 11 % 3;
the variable a will contain the value 2, since 2 is the remainder from dividing 11 between
3.

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 :

== Equal to Here there are some examples:


!= Not equal to
1 (7 == 5) // evaluates to false.
> Greater than 2 (5 > 4) // evaluates to true.
< Less than 3 (3 != 2) // evaluates to true.
>= Greater than or equal to 4 (6 >= 6) // evaluates to true.
<= Less than or equal to 5 (5 < 5) // evaluates to false.

7
Logical operators ( !, &&, || )
operator Name
&& Logical AND
|| Logical OR
! Logical NOT

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 || OPERATOR ! OPERATOR
a b a && b a b a || b
true true true true true true a !a
true false false true false true true false
false true false false true true false true
false false 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:
For example:
1 ( (5 == 5) && (3 > 6) ) // evaluates to false ( true && false ).
2 ( (5 == 5) || (3 > 6) ) // evaluates to true ( true || false ).

Assignment operators (=, +=, -=, *=, /=, %=)


When we want to modify the value of a variable by performing an operation on the value
currently stored in that variable we can use assignment operators:
= Assignment
+= Add and assignment
-= Subtract and assignment
*= Multiply and assignment
/= Divide and assignment
%= Modulo divide and assignment
Assignment (=)
The assignment operator assigns a value to a variable.
a = b;
This statement assigns to variable a (the lvalue) the value contained in
variable b (the rvalue).
The following expression is also valid in C++: a = b = c = 5;
It assigns 5 to the all three variables: a, b and c.
expression is equivalent to
value += increase; value = value + increase;

8
a -= 5; a = a - 5;
a /= b; a = a / b;
price *= units + 1; price = price * (units + 1);

Increment and decrement operators (++, --)


Shortening even more some expressions, the increment operator (++) and the decrement
operator (--) increase or reduce by one the value stored in a variable. They are equivalent
to +=1 and to -=1, respectively. Thus:

operator name expression Is equivalent to


++ Increment operator a++ or ++a a=a+1
-- Decrement operator a-- or a-- a= a-1

1 // Add.java- write a java program to display sum of two numbers In put:


2 import java.io.*;
3 import java.util.*; Enter num1:5
4 class Add Enter num2:3
5{
6 public static void main (String args[]) Output:
7 {
8 int num1,num2,sum; SUM=8
9 Scanner s=new Scanner(System.in);
10 System.out.println(”Enter number1:”);
11 num1=s.getInt();
12 System.out.println(”Enter number2:”);
13 num2=s.getInt();
14 sum = num1 + num2;
15 System.out.println(”SUM=”+sum);
16 }
17 }

1 // Average.java- write a java program to display average of three numbers In put:


2 import java.io.*;
3 import java.util.*; Enter a,b,c vaues:5
4 class Average 34
5{
6 public static void main (String args[]) Output:
7 { float a,b,c,sum;
8 Scanner s=new Scanner(System.in); AVERAGE=4.0
9 System.out.println(”Enter a,b,c values:”);
10 a=s.getFloat();
11 b=s.getFloat();
12 c=s.getFloat();
13 avg=(a+b+c)/3;
14 System.out.println(”AVERAGE=”+avg);
15 }
16 }

9
1 // Area.java- write a java program to display area of a circle In put:
2 import java.io.*;
3 import java.util.*; Enter radius:5
4 class Area
5{ Output:
6 public static void main (String args[])
7 { AREA=78.5
8 float r,area;
9 Scanner s=new Scanner(System.in);
10 System.out.println(”Enter radius:”);
11 r=s.getFloat();
12 area=(22/7)*r*r;
13 System.out.println(”AREA=”+area);
14 }
15 }

1.4 Simple control structures and loop structures


A program is usually not limited to a linear sequence of instructions. During its process it
may bifurcate, repeat code or take decisions. For that purpose, JAVA provides control
structures that serve to specify what has to be done by our program, when and under which
circumstances.

A statement_block is a group of statements which are separated by semicolons (;) like all
JAVA statements, but grouped together in a block enclosed in braces: { }:
{ statement_block }= { statement1; statement2; statement3; }
Control structures :
The if Statement:
An if statement consists of a Boolean expression followed by one or more statements.
Syntax:
The syntax of an if statement is:
if(Boolean_expression)
{
//Statements will execute if the Boolean expression is true
}
The if...else Statement:
An if statement can be followed by an optional else statement, which executes when the
Boolean expression is false.
Syntax:
The syntax of a if...else is:
if(Boolean_expression){
//Executes when the Boolean expression is true
}else{
//Executes when the Boolean expression is false
}

10
1 // OddEven.java-write a java program to check given number is odd or even Input:
2 import java.io.*;
3 import java.util.*; Enter n value: 5
4 class OddEven
Output:
5{
6 public static void main (String args[]) 5 is odd number
7 { Input:
8 int n; Enter n value: 6
9 Scanner s=new Scanner(System.in);
10 System.out.println(”Enter n value:”); Output:
11 n=s.getInt();
12 if(n%2==0) 6 is even number
13 System.out.println(n+” is even number”);
14 else
15 System.out.println(n+” is odd number”);
16 }
17 }

Nested if...else Statement:


An if statement can be followed by an optional else if...else statement, which is very
usefull to test various conditions using single if...else if statement.
Syntax:The syntax of a nested if...else is:
if(Boolean_expression 1){
//Executes when the Boolean expression 1 is true
}else if(Boolean_expression 2){
//Executes when the Boolean expression 2 is true
}else if(Boolean_expression 3){
//Executes when the Boolean expression 3 is true
}else {
//Executes when the one of the above condition is true.
}

1 //Largest.java write a java program to find largest of three numbers Input:


2 import java.io.*;
3 import java.util.*; Enter a,b,c values: 5 8 9
4 class Largest
5{ Output:
6 public static void main (String args[])
7 { int a,b,c; 9 is larger number
8 Scanner s=new Scanner(System.in);
9 System.out.println(”Enter a,b,c values:”);
10 a=s.getInt(); b=s.getInt(); c=s.getInt();
11 if(a>b&&a>c)
12 System.out.println(a+” is largest number”);
13 else if(b>a && b>c)
14 System.out.println(b+” is largest number”);
15 else
16 System.out.println(c+” is largest number”);
17 }

11
18 }

The switch Statement:


A switch statement allows a variable to be tested for equality against a list of values. Each
value is called a case, and the variable being switched on is checked for each case.
Syntax:
switch(expression){
case value :
//Statements
break; //optional
case value :
//Statements
break; //optional
//You can have any number of case statements.
default : //Optional
//Statements
}
1 //Word.java write a java program to display given digit in words Input:
2 import java.io.*;
3 import java.util.*; Enter a digit: 6
4 class Word
5{ Output:
6 public static void main (String args[])
7 { int d; SIX
8 Scanner s=new Scanner(System.in);
9 System.out.println(”Enter n value:”);
10 d=s.getInt();
11 switch(d)
12 { case 0: System.out.println(”ZERO”); break;
13 case 1: System.out.println( “ONE”) ; break; Input:
14 case 2: System.out.println( “TWO”) ; break;
15 case 3: System.out.println( “THREE”) ; break; Enter a digit: A
16 case 4: System.out.println( “FOUR”) ; break;
17 case 5: System.out.println( “FIVE”) ; break; Output:
18 case 6: System.out.println( “SIX”) ; break;
19 case 7: System.out.println( “SEVEN”) ; break; INVALID DIGIT
20 case 8: System.out.println( “EIGHT”) ; break;
21 case 9: System.out.println( “NINE”) ; break;
22 default: System.out.println( “ INVALID DIGIT”);
23 }
24 }
25 }
Loop structures:
The while Loop:
A while loop is a control structure that allows you to repeat a task a certain number of
times.Syntax:The syntax of a while loop is:
while(Boolean_expression)
{
//Statements

12
}
The do...while Loop:
A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to
execute at least one time.
Syntax:The syntax of a do...while loop is:
Do
{
//Statements
}while(Boolean_expression);
The for Loop:
A for loop is a repetition control structure that allows you to efficiently write a loop that
needs to execute a specific number of times.
A for loop is useful when you know how many times a task is to be repeated.
Syntax:The syntax of a for loop is:
for(initialization; Boolean_expression; update)
{
//Statements
}
1 //Natural1.java – write a java program to display first Output:
2 numbers using while 1 2 3 4 5 6 7 8 9 10
3 import java.io.*;
4 import java.util.*;
5 class Natural1
6 { public static void main (String args[])
7 { int i;
8 i=1;
9 while(i<=10)
10 {
11 System.out.println(i+”\t”);
12 i++;
13 }
14 }
15 }

1 //Natural2.java – write a java program to display first Output:


2 numbers using do while 1 2 3 4 5 6 7 8 9 10
3 import java.io.*;
4 import java.util.*;
5 class Natural2
6 { public static void main (String args[])
7 { int i;
8 i=1;
9 do
10 {
11 System.out.println(i+”\t”);
12 i++;
13 } while(i<=10);
14 }
15 }

1 //Natural3.java – write a java program to display first Output:


2 numbers using for loop 1 2 3 4 5 6 7 8 9 10

13
3 import java.io.*;
4 import java.util.*;
5 class Natural3
6 { public static void main (String args[])
7 { int i;
8 for(i=1;i<=10;i++)
9 {
10 System.out.println(i+”\t”);
11 }
12 }
13 }

1 //Factorial1.java- write a java program to find factorial of given number Input:


2 using while loop
3 import java.io.*; ENTER A NUMBER: 5
4 import java.util.*;
5 class Factorial1 Output:
6 { public static void main (String args[])
7 { int i,n,fact=1; Factorial of 5 = 120
8 Scanner s=new Scanner(System.in);
9 System.out.println(”Enter a Number:”); Input:
10 n=s.getInt();
11 i=1; ENTER A NUMBER: 3
12 while(i<=n)
13 { Output:
14 fact= fact *i;
15 i++; Factorial of 3 = 6
16 }
17 System.out.println( “ Factorial of ”+n+”=”+fact);
18 }
19 }

1 //Factorial2.java- write ajava program to find factorial of given number Input:


2 using do while loop
3 import java.io.*; ENTER A NUMBER: 5
4 import java.util.*;
5 class Factorial2 Output:
6 { public static void main (String args[])
7 { int i,n,fact=1; Factorial of 5 = 120
8 Scanner s=new Scanner(System.in);
9 System.out.println(”Enter a Number:”); Input:
10 n=s.getInt();
11 i=1; ENTER A NUMBER: 3
12 do
13 { fact= fact *i; Output:
14 i++;
15 }while(i<=n); Factorial of 3 = 6
16 System.out.println( “ Factorial of ”+n+”=”+fact);
17 }
18 }

14
1 //Factorial3.java- write ajava program to find factorial of given number Input:
2 using for loop
3 import java.io.*; ENTER A NUMBER: 5
4 import java.util.*;
5 class Factorial3 Output:
6 { public static void main (String args[])
7 { int i,n,fact=1; Factorial of 5 = 120
8 Scanner s=new Scanner(System.in);
9 System.out.println(”Enter a Number:”); Input:
10 n=s.getInt();
11 for(i=1; i<=n; i++) ENTER A NUMBER: 3
12 {
13 fact= fact *i; Output:
14 }
15 System.out.println( “ Factorial of ”+n+”=”+fact); Factorial of 3 = 6
16 }
17 }

Chapter 2 - Object Oriented Thinking


2.1 Why Do We Need Object-Oriented Programming?
2.1.1. Procedural Languages
2.1.2 The Object-Oriented Approach
2.2 Characteristics of Object-Oriented Languages
2.2.1 Classes
2.2.2 Objects
2.2.3 Data abstraction
2.2.4 Encapsulation

2-1 Need for object oriented programming,


Object oriented programming is a concept that was created because of the need to
overcome the problems that were found with using structured programming techniques.
OOP allows decomposing a problem into a number of entities called objects and build data
and methods around these entities. The data of an object is only accessed by the methods
associated with the object
Object Oriented Programming Language procedural Language
Basic building blocks are objects Basic building blocks are functions
Functions and data are tied together. Data is Data and Functions don’t tide with each
hidden and can’t be accessed by the external other.
world. This can be achieved by data Data moves openly around the system
abstraction and encapsulation from function to function.
Functions are not dependent so reusability is Functions are dependent so reusability is
possible. This can be achieved by inheritance not possible
Program can be easily extended and altered It’s very difficult to modify and extend the
complex program
Supports overloading, polymorphism, Does not support overloading,

15
exception handling polymorphism, exception handling

2.2 classes and Objects (instances), data abstraction, encapsulation


Class:
A class simply represents a grouping of similar objects (instances) which have similar set
of properties (attributes) exhibits similar behavior (set of methods) in response to a
received message.

class classname
{
type instance-variable1;
type instance-variable2;
...
type instance-variableN;

type methodname1(parameter-list)
{
// body of method
}
type methodname2(parameter-list)
{
// body of method
}
...
type methodnameN(parameter-list)
{
// body of method
}
}

Object:
An object is Instance which is instantiated (created) by a class with its own attribute values
and methods. Every object is an instance of a class.
An object consists of :
1. State : It is represented by attributes of an object. It also reflects the properties of
an object.

16
2. Behavior : It is represented by methods of an object. It also reflects the response of
an object with other objects.
3. Identity : It gives a unique name to an object and enables one object to interact
with other objects.
When you create a class, you are creating a new data type. You can use this type to declare
objects of that type.
Creating objects of a class is a two-step process.
 Declare a variable of the class type.
 Use the new operator to dynamically allocate memory for an object.

Create a class named Box that includes integer data fields for length, width and height.
Create three constructors that require one, two and three arguments, respectively declare
three objects b1,b2,b3 of type Box:

Box
length: double
width: double
height: double
Box( )
Box(s)
Box(l,w,h)
volume():void
Java implementation of Box class and Box objects:
//ClassDemo.java- write a java program to demonstrate class and object implementation concept
import java.io.*;
class Box
{ private double width;
private double height;
private double length;
Box () // constructor used when no dimensions specified
{
this. width =this. length= this. height=10;
}
Box (double s) // constructor used when cube is created
{
this. width = this. Height = this.length = s;
}
Box (double w, double h, double l) // constructor used when all dimensions specified
{
this.width = w; this.height = h; this.length = l;
}
void volume() // compute and display volume
{
System.out.println(“VOLUME=”+(this.width * this. height * this. length);
}
}

17
class ClassDemo
{
public static void main(String args[])
{ Box b1 = new Box ();
Box b2 = new Box (5);
Box b3 = new Box(5,3,2);
b1.volume();
b2.volume();
b3.volume();
}
}

OUTPUT:

Method: it is an action carried by an agent in response to a received message.


If the receiver accepts the message, it accepts the responsibility to carry out the indicated
action.
In response to a message, the receiver will perform some method to satisfy the request.

Data abstraction: Data abstraction refers to the act of representing the essential
characteristics of an object which differentiate it from other objects.
Classes use the concepts of data abstraction and it is called as Abstract Data Type (ADT).

Encapsulation: Encapsulation means wrapping of data (attributes) and methods into a single
unit (i.e. class). It is most useful feature of class. The data is not easy to get to the outside
world and only those methods which are enclosed in the class can access it.
These methods provide the boundary between Object‘s data and program. This insulation of
data from direct access by the program is called as Data hiding.

Information (data) hiding: An agent sending the request need not know the actual means
by which the request will be honored by receiver agent.

18
19

You might also like