2017 Java-Chapter 1-2
2017 Java-Chapter 1-2
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.
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..
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
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.
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 :
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 ).
8
a -= 5; a = a - 5;
a /= b; a = a / b;
price *= units + 1; price = price * (units + 1);
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 }
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 }
11
18 }
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 }
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 }
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 }
15
exception handling polymorphism, exception handling
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:
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