Unit No.1
Unit No.1
Unit No.1
Unit No.1
Basic Syntactical Constructs in Java
CO a. Develop program using Object oriented methodology in Java.
Java-
Java is a general-purpose high-level programming language that helps to build a variety of
applications. Core Java is used to build general applications.
Java is designed to be easy to learn. There are various features that make the java as a simple
language.
Programs are easy to write and debug because java does not use the pointers explicitly.
Java uses many Constructs of C and C++ and therefore Java code "looks like a C++" code. Thus
Java is Simplified version of C++.
History of Java -:
Java is a general-purpose, object-oriented programming language.
It is developed by James Gosling, Patrick Naughton, Chris Warth, Ed Frank and Mike Sheridan
at Sun Microsystems of USA in 1991.
It was originally called “Oak” but was renamed “Java” in 1994.
It was designed for the development of software for consumer electronic devices like TV, VCR,
Toasters, Cable set top boxes, PDA and other electronic machines.
Java acronym for the names of the team members: James Gosling, Arthur Van Hoff, and Andy
Bechtolsheim.
5. Secured
6. Robust
7. Architecture neutral
8. Interpreted
9. High Performance
10. Multithreaded
11. Distributed
12. Dynamic
1) Simple
Java is very easy to learn, and its syntax is simple, clean and easy to understand. According to
Sun, Java language is a simple programming language because:
o Java syntax is based on C++ (so easier for programmers to learn it after C++).
o Java has removed many complicated and rarely-used features, for example, explicit pointers,
operator overloading, etc.
o There is no need to remove unreferenced objects because there is an Automatic Garbage
Collection in Java.
2) Object-oriented
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
3) Platform Independent
Java is platform independent because it is different from other languages like C, C++, etc.
which are compiled into platform specific machines while Java is a write once, run anywhere
language platform is the hardware or software environment in which a program runs.
There are two types of platforms software-based and hardware-based. Java provides a software-
based platform.
The Java platform differs from most other platforms in the sense that it is a software -based
platform that runs on the top of other hardware-based platforms. It has two components:
Runtime Environment
Java code can be run on multiple platforms, for example, Windows, Linux, Sun Solaris, Mac/OS,
etc. Java code is compiled by the compiler and converted into byte code. This byte code is a
platform-independent code because it can be run on multiple platforms, i.e., Write Once and Run
Anywhere (WORA).
1) Secure
Java is best known for its security. With Java, we can develop virus-free systems. Java is secured
because:
o No explicit pointer
o Java Programs run inside a virtual machine sandbox
o Class loader: Classloader in Java is a part of the Java Runtime Environment (JRE) which is
used to load Java classes into the Java Virtual Machine dynamically. It adds security by
separating the package for the classes of the local file system from those that are imported
from network sources.
o Byte code Verifier: It checks the code fragments for illegal code that can violate access right
to objects.
o Security Manager: It determines what resources a class can access such as reading and
writing to the local disk.
Java language provides these securities by default. Some security can also be provided by an
application developer explicitly through SSL, JAAS, Cryptography, etc.
2) Robust
3) Architecture-neutral
Java is architecture neutral because there are no implementation dependent features, for example ,
the size of primitive types is fixed.
In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4 bytes
of memory for 64-bit architecture. However, it occupies 4 bytes of memory for both 32 and 64-
bit architectures in Java.
4) Portable
Java is portable because it facilitates you to carry the Java byte code to any platform. It doesn't
require any implementation.
5) High-performance
Java is faster than other traditional interpreted programming languages because Java byte code is
"close" to native code. It is still a little bit slower than a compiled language (e.g., C++). Java is
an interpreted language that is why it is slower than compiled languages, e.g., C, C++, etc.
6) Distributed
Java is distributed because it facilitates users to create distributed applications in Java. RMI and
EJB are used for creating distributed applications. This feature of Java makes us able to access
files by calling the methods from any machine on the internet.
7) Multi-threaded
A thread is like a separate program, executing concurrently. We can write Java programs that
deal with many tasks at once by defining multiple threads. The main advantage of multi-
threading is that it doesn't occupy memory for each thread. It shares a common memory area.
Threads are important for multi-media, Web applications, etc.
8) Dynamic
Java is a dynamic language. It supports dynamic loading of classes. It means classes are loaded
on demand. It also supports functions from its native languages, i.e., C and C++.
Java supports dynamic compilation and automatic memory management (garbage collection).
Java is a two stage system: In a first stage java compiler translates source code into byte code
instructions.
In a second stage, Java interpreter generates machine code that can be directly executed by the
machine.
The two steps of compilation and interpretation allow for extensive code checking and improved
security.
Input/output Package
Networking Package
AWT Package
Applet Package
JVMs are available for many hardware and software platforms (i.e. JVM is platform dependent).
JVM, i.e., Java Virtual Machine. JVM is the engine that drives the Java code.
Mostly in other Programming Languages, compiler produce code for a particular system but Java
compiler produce Byte code for a Java Virtual Machine.
When we compile a Java program, then byte code is generated. Byte code is the source code that can be
used to run on any platform.
Byte code is an intermediary language between Java source and the host system.
It is the medium which compiles Java code to byte code which gets interpreted on a different machine and
hence it makes it Platform/Operating system independent.
Loads code
Verifies code
Executes code
Provides runtime environment
Installation of JDK:
Step 1: Verify that it is already installed or not
Sample program:
Class Test
Class Declaration: Java is true object-oriented language so everything must be placed inside a
class. Class is a keyword to define a new class.
Opening Brace: The class definition must begin with opening cur ly brace ({) and ends with
closing curly brace (}). The rest of the things defined inside these braces are called member of
the class
The main line: The public static void main(String args[]) defines a method named main. The
program will start execute by calling this main method. All the java program will start execute
by calling the main method. This line contains a number of keywords, public, static and void.
Public:-The keyword public is an access specifier that declares the main method as unprotected
and therefore making it accessible to all other classes. The main() must be declared as public
because it must be called by code outside of its class when the program is started.
Static:-It declares this method as one that belongs to the entire class and not a part of any objects
of the class. The main must always be declared as static since the interpreter uses this method
before any objects are created. It allows main() to be called without having to instantiate a
particular instance of the class. This is necessary since main() is called by the JVM before any
objects are made.
Void:- A keyword simply tells the compiler that the main() does not return values.
In a main() method there is only one parameter ,String args[] . args[] is a name of the parameter
that is an array of the objects of data type String. String store sequences of characters and args
will receive the command line arguments when the program is executed. Any information that
we need to pass to method is received by variables specified with in the set of parentheses that
follow the name of the method. These variables are called parameters. If no parameters are
passed then the parentheses are empty.
“Java is better than C++” to the screen. The println method always appends a new line character
to the end of the string. I.e. any subsequent output will start on a new line. Every statement must
end with a semicolon. (System is a class, out is an object and println is a method)
1. Create a program using any text editor (use notepad editor in Windows Operating System).
Open notepad and enter/edit the following program.
class Test
System.out.println(“Hello! ”);
Here main class name is Test so save this program in “Test.java” file.
Note that if program contains multiple classes the file name must be the classname of the class
containing the main method, i.e. main class name.
5. Go to bin directory.
If errors are there then listing of errors will be displayed and to correct the errors again open the
source file using notepad and correct the program otherwise javac creates “Test.class” file
containing the byte code of the program.
C:\jdk\bin\java Test
Defining Object
An entity that has state and behavior is known as an object e.g., chair, bike, marker, pen,
table, car, etc. It can be physical or logical (tangible and intangible). The example of an
intangible object is the banking system.
For Example, Pen is an object. Its name is Reynolds; color is white, known as its state. It is used
to write, so writing is its behavior.
An object is an instance of a class. A class is a template or blueprint from which objects are
created. So, an object is the instance (result) of a class.
Object Definitions:
Defining a Class:
Once a new data type is defined using a class, it can be used to create objects of that type.
Classes create objects and objects use methods to communicate between them.
Syntax:
class classname[ extends superclassname]
[ fields declaration; ]
[ methods declaration; ]
Example:
class rectangle
{
int length, width;//declaration of variables
{
length = x;
width = y;
Java Tokens
Java Keywords-:
Constant/Literals:
Constants/Literals are an identifier whose value is fixed and does not change during the
execution of the program.
Fig, Constant/Literals:
Data Types:
Data types specify the different sizes and values that can be stored in the variable.
Variables:
A variable is a container which holds the value while the Java program is executed.
2.
3.
4.
5.
6.
Types/Scope of Variables :
Local
Instance
A variable that is declared inside the class but outside the method is called instance variable.
Class/ Static
Dynamic Initialization:
Initializing a variable at run time is called dynamic initialization.
Java allows variables to be initialized dynamically, using any expression valid at the time
the variable is declared.
Array:
An array is a collection of similar types of data.
For example,
If we want to store the names of 100 people then we can create an array of the
String type that can store 100 names.
String:
String is basically an object that represents sequence of char values.
For example:
char[ ] ch={„M‟,‟S‟,‟B‟,‟T‟,‟E‟};
Operators in Java
Operator in Java is a symbol which is used to perform operations. For example: +, -, *, / etc.
There are many types of operators in Java which are given below:
o Arithmetic Operator
o Relational Operator
o Logical Operator
o Increment and Decrement
o Conditional Operators
o Bitwise Operator
o Ternary Operator
Arithmetic operators are used in mathematical expression in the same way that they are used
in algebra.
Example:
{
int a=100;
int b=21;
System.out.println("Addition:="+(a+b));
System.out.println("Subtraction:="+(a-b));
System.out.println("Multiplication:="+(a*b));
System.out.println("Division:="+(a/b));
System.out.println("Modulo:="+(a%b));
}
}
Output
Example:
int number=50;
System.out.println("Number is"+number);
number--;//Decrement number.
System.out.println("Now,number is"+number);
}
}
Output
Example:
c = a++;
System.out.println("Result after Pre Increment a:"+a);
System.out.println("Result after Post Increment c:"+c);
d = --a;
System.out.println("Result after Pre Increment a:"+a);
System.out.println("Result after Pre Decrement d:"+d);
e = a--;
System.out.println("Result after Pre Increment a:"+a);
System.out.println("Result after Post Decrement e:"+e);
}
}
Output
>= Evaluates whether the left operand is x>=y Returns true if x is greater than
greater than or equal to the right or equal to y and false if
operand. otherwise.
<= Evaluates whether the left operand is x<=y Returns true if x is less than or
less than or equal to the right operand. equal to y and false if
otherwise.
Example:
Output
Operators-Bit wise
Bitwise Compliment ~ ~ op
Example-
class demo
{
public static void main(string args[])
{
int a,b;
a=10;
b=2
System.out.println(“AND=” +(a&b));
System.out.println(“OR=” +(a|b));
System.out.println(“EOR=” +(a^b));
&& Logical AND- The logical && operator doesn't check second condition if first
condition is false. It checks second condition only if first one is true.
|| Logical OR- The logical || operator doesn't check second condition if first condition is
true. It checks second condition only if first one is false.
! Logical NOT – An expression is true if both condition are true. It gives (or both) of
them are false.
Example
class Demo_Logical
{
public static void main(String[] args)
{
// && operator
System.out.println((5 > 3) && (8 > 5)); // true
System.out.println((5 > 3) && (8 < 5)); // false
// || operator
System.out.println((5 < 3) || (8 > 5)); // true
System.out.println((5 > 3) || (8 < 5)); // true
System.out.println((5 < 3) || (8 < 5)); // false
// ! operator
System.out.println(!(5 == 3)); // true
System.out.println(!(5 > 3)); // false
}
}
The goal of the operator is to decide which value should be assigned to the variable.
Ternary operator "? :" basically is used for an if-then-else as shorthand as:
Syntax:
Boolean expression? operand1: operand2;
Example:
Output
When several operations occur in an expression, each part is evaluated and resolved in a
predetermined order called operator precedence.
Operator precedence determines the order in which the operators in an expression are evaluated.
When two operators share an operand, the operator with the higher precedence goes first
.
For Example:
Now, take a look at the statement below:
int myint= 12 -4 * 2;
Operators Precedence
postfix increment and decrement ++ --
prefix increment and decrement, and unary ++ --+ -~ !
multiplicative */%
additive +-
shift << >> >>>
relational < > <= >= instance of
equality == !=
bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
logical AND &&
logical OR ||
ternary ?:
assignment = += -= *= /= %=&= ^= |= <<= >>= >>>=
Associativity
When two operators with the same precedence, the expression is evaluated according to its
associativity.
For example,
x=y=z=17 is treated as x=(y=(z=17))), leaving all three variables with the value 17,
since the = operator has right-to-left associativity.
On the other hand, 70/2/3 is treated as (70/2)/3 since the / operator has left-to-right
associativity.
Expression of Evaluation:
An expression is a construct which is made up of literals, variables, method calls and
operators following the syntax of Java.
For example,
class Precedence
{
public static void main(String args[])
{
int result;
result=(20*5)+(10/2)-(3*10);
System.out.println(result);
}
}
Output
Math Function:
Mathematical function such as sin, cos, sqrtused to analyzeof real life problems.
Java supports these basic math functions through Math class defined in the
java.langpackage.
For Example,
Example:
public class JavaMathExample1
{
public static void main(String[] args)
{
double x = 28;
double y = 4;
System.out.println("Maximum number of x and y is: " +Math.max(x, y));
System.out.println("Square root of y is: " + Math.sqrt(y));
System.out.println("Power of x and y is: " + Math.pow(x, y));
System.out.println("Logarithm of x is: " + Math.log(x));
System.out.println("Logarithm of y is: " + Math.log(y));
System.out.println("log10 of x is: " + Math.log10(x));
System.out.println("exp of a is: " +Math.exp(x));
}
Output:
Type casting
Converting one primitive data type into another is known as type casting (type conversion) in
Java.
You can cast the primitive data types in two ways namely, Widening and Narrowing.
A) Widening:
Converting a lower datatype to a higher datatype is known as widening.
In this case the casting/conversion is done automatically therefore, it is known as implicit
type casting.
In this case both data types should be compatible with each other.
Example:
public class demo_W
{
public static void main(String[] args)
{
int a=9;
double b=a; // Automatic casting: int to double
System.out.println(a);
System.out.println(b);
}
}
B) Narrowing
In this case the casting/conversion is not done automatically, you need to convert
explicitly using the cast operator “( )” explicitly.
Therefore, it is known as explicit type casting.
Example:
Output
Java if Statement
Syntax:
if(condition)
{
//code to be executed
}
Example:
}
}
}
Output
if(condition)
{
//code if condition is true
}
else
{
//code if condition is false
}
Example:
class demo_if_else_ex
{
public static void main(String[] args)
{
intnumber = -10;
if (number > 0)
{
System.out.println("The number is positive.");
}
else
{
System.out.println("The number is not positive.");
}
Sou.Venutai Chavan Polytechnic,Pune. 36
Java Programming (22412)
}
}
Syntax:
if(condition1)
{
//code to be executed if condition1 is true
} else if(condition2)
{
//code to be executed if condition2 is true
}
else if(condition3)
{
//code to be executed if condition 3 is true
}
...
else
{
//code to be executed if all the conditions are false
}
Example:
class if_else_if_demo
{
public static void main(String[] args)
{
int number = 0;
if (number > 0)
{
System.out.println("The number is positive.");
}
Output
Here, the inner if block condition executes only when outer if block condition is true.
Syntax:
if(condition)
{
//code
to
be executed if(condition)
{
//code to be executed
}
}
Example
class nested_if
{
public static void main(String args[])
{
double n1 = -1.0, n2 = 4.5, n3 = -5.3, largest;
if (n1 >= n2)
{
if (n1 >= n3)
{
largest = n1;
}
else
{
largest = n3;
}
}
else
{
if (n2 >= n3)
{
largest = n2;
}
else {
largest = n3;
}
}
System.out.println("Largest Number: " + largest);
}
}
Output
The Java switch statement executes one statement from multiple conditions.
It is like if-else-if ladder statement.
The switch statement works with byte,short,int,long,enum types,String and some wrapper
types like byte,short,int,and long.
In other words, the switch statement tests the equality of a variable against multiple values.
Syntax
switch(expression)
{
case value1:
//code to be executed;
break;//optional
case value2:
//code to be executed;
break;//optional
......
default:
code to be executed if all cases are not
matched;
}
Example
public class Switch_demo
{
public static void main(String[] args)
{
Int day = 6;
switch (day)
{
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
}
}
}
Output
Break
The break statement in java is used to terminate from the loop immediately.
When a break statement is encountered inside a loop, the loop iteration stops there, and
control returns from the loop immediately to the first statement after the loop.
Example:
public class BreakDemo
{
public static void main(String args[])
{
for(int i=1;i<=10;i++)
{
if(i==8)
{
break;
}
System.out.println(i);
}
}
}
Output
Continue
The continue statement in Java is used to skip the current iteration of a loop.
We can use continue statement inside any types of loops such as for, while, and do-while
loop.
Example:
Output
While loop
The Java while loop is used to iterate a part of the program several times.
Syntax
while(condition)
{
//code to be executed
}
Example:
Output
do-while loop
The Java do-while loopi s used to iterate a part of the program several times.
If the number of iteration is not fixed and you must have to execute the loop at least once, it
is recommended to use do-while loop.
The Java do-while loop is executed at least once because condition is checked after loop
body.
Syntax:
do
{
//code to be executed
}
while(condition);
Example:
}
}
Output
for loop
The Java for loopis used to iterate a part of the program several times.
If the number of iteration is fixed, it is recommended to use for loop.
Syntax
for(initialization;condition;incr/decr)
{
//statement or code to be executed
}
Example:
public class ForExample
{
public static void main(String args[])
{
for(int i=1;i<=10;i++)
{
System.out.println(i);
}
}
}
Output
Example:
public class ForEachExample
{
public static void main(String args[])
{
//Declaring an array
Int arr[]={1,2,3,7,8,14,15};
//Printing array using for-each loop
for(int i:arr){
System.out.println(i);
}
}
Output