Unit No.1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 47

Java Programming (22412)

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.

It also eliminates operator overloading and multiple inheritance.

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.

1.1 Java Features-:


The primary objective of Java programming language creation was to make it portable, simple
and secure programming language. Apart from this, there are also some excellent features which
play an important role in the popularity of this language. The features of Java are also known as
java buzzwords.

1. A list of most important features of Java language is given below. Simple


2. Object-Oriented
3. Portable
4. Platform independent

Sou.Venutai Chavan Polytechnic,Pune. 1


Java Programming (22412)

5. Secured
6. Robust
7. Architecture neutral
8. Interpreted
9. High Performance
10. Multithreaded
11. Distributed
12. Dynamic

Fig. Java Features

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

Java is an object-oriented programming language. Everything in Java is an object. Object-


oriented means we organize our software as a combination of different types of objects that
incorporates both data and behavior.

Sou.Venutai Chavan Polytechnic,Pune. 2


Java Programming (22412)

Object-oriented programming (OOPs) is a methodology that simplifies software development


and maintenance by providing some rules.

Basic concepts of OOPs are:

1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation

3) Platform Independent

Fig. Platform- Independent

Sou.Venutai Chavan Polytechnic,Pune. 3


Java Programming (22412)

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

API (Application Programming Interface)

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

Sou.Venutai Chavan Polytechnic,Pune. 4


Java Programming (22412)

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

Robust simply means strong. Java is robust because:

o It uses strong memory management.


o There is a lack of pointers that avoids security problems.
o There is automatic garbage collection in java which runs on the Java Virtual Machine to
get rid of objects which are not being used by a Java application anymore.
o There are exception handling and the type checking mechanism in Java. All these points
make Java 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.

Sou.Venutai Chavan Polytechnic,Pune. 5


Java Programming (22412)

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).

9) Compiled and Interpreted :

Fig. Compiled and Interpreted

Java is a two stage system: In a first stage java compiler translates source code into byte code
instructions.

Byte codes are not machine instructions.

Sou.Venutai Chavan Polytechnic,Pune. 6


Java Programming (22412)

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.

Java Programming Environment-:

Fig. Java Development Kit(JDK)


The development tools are part of system known as Java Development kit (JDK)
The classes and methods are part of the Java Standard Library (JSL), also called as the
Application Programming Interface (API).
It includes a large number of development tools and hundreds of classes and methods.

Java Development Kit –


The Java Development Kit comes with a collection of tools that are used for developing and
running Java programs.

 appletviewer (for viewing Java applets)

 Javac (Java Compiler)

 Java (Java interpreter)


 Javap (Java disassemble)

 Javah (for c header files)

Sou.Venutai Chavan Polytechnic,Pune. 7


Java Programming (22412)

 javadoc (for creating HTML documents)

 Java (Java debugger)

Javac(Javacompiler) It is java compiler and used to compile java program. It translates


java source code to byte code files that the interpreter can
understand.
Java(Javainterpreter) It is java interpreter and used to run an applet and application
program by reading and interpreting byte code files.
Appletviewer It enables us to run java applets (without actually using a java-
(viewjavaapplet) compatible browser).
Javah(Cheaderfiles) It generates C header files and source files that are needed to
implement native methods.
Javap(Javadisassembler) It is java disassemble and used to convert byte code files into a
program description.
Jdb(javadebugger) It is used to find errors in our programs
Javadoc(javadocumentforcr It is used to create HTML- format document action from java
eatingHTMLdocuments) source code files

 Application Programming Interface (API)


 Language Support Package
 Utilities Package

 Input/output Package

 Networking Package
 AWT Package

 Applet Package

 Java Components: The Byte Code


The intermediate form of java program is known as byte code.
• When java program is compiled, then java compiler produces an intermediate code for a
machine that does not exist instead of machine code.
• This intermediate form of code is known as byte code.
• By Java interpreter we can interpret this Byte code on any machine and run on any
machine.
• The file which contains this code has .class extension

Sou.Venutai Chavan Polytechnic,Pune. 8


Java Programming (22412)

• It is not machine specific.

Fig. Byte Code

 Java Components: Java Virtual Machine


It is a specification that provides runtime environment in which java byte code can be executed.

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.

The JVM performs following operation:

 Loads code
 Verifies code
 Executes code
 Provides runtime environment

Sou.Venutai Chavan Polytechnic,Pune. 9


Java Programming (22412)

Fig.-Java Virtual Machine

Installation of JDK:
Step 1: Verify that it is already installed or not

Step 2: Download JDK

Step 3: Install JDK

Step 4: Set the Permanent Path

Sample program:

Class Test

public static void main(String args[])

System.out.println(“Java is better than C++”);

Sou.Venutai Chavan Polytechnic,Pune. 10


Java Programming (22412)

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.

The Output line:-The only executable statement in the program is System.out.println(“Java is


better than C++”); It is similar to printf() statement of C or cout<< construct of C++. The println
method is a member of the out object which is a static data member of system class. This line
prints the string-

“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)

 Compilation and Exe cution of Java Program

Sou.Venutai Chavan Polytechnic,Pune. 11


Java Programming (22412)

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

public static void main(String args[])

System.out.println(“Hello! ”);

System.out.println(“Welcome to the world of java ”);

System.out.println(“Let us learn java ”);

2. Save this program in a file called “Test.java”.

The name of file must be same as main class name.

Here main class name is Test so save this program in “Test.java” file.

This file is called as source file.

All java source files should have extension .java.

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.

3. Locate/store Test.java file in the bin directory of java compiler.

4. Close notepad and go to dos prompt.

5. Go to bin directory.

6. Compile the program using javac tool of JDK as follows

C:\jdk\bin\ javac Test.java

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.

Sou.Venutai Chavan Polytechnic,Pune. 12


Java Programming (22412)

7. Run the program using the java interpreter as follows: -

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.

An object has three characteristics:

o State: represents the data (value) of an object.


o Behavior: represents the behavior (functionality) of an object such as deposit, withdraw,
etc.
o Identity: An object identity is typically implemented via a unique ID. The value of the
ID is not visible to the external user. However, it is used internally by the JVM to identify
each object uniquely.

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:

o An object is a real-world entity.


o An object is a runtime entity.
o The object is an entity which has state and behavior.
o The object is an instance of a class.

Sou.Venutai Chavan Polytechnic,Pune. 13


Java Programming (22412)

 Steps for creating objects:


A. Declaring an object:
 Also called instantiating a class.
 When an object of a class is created, the class is said to be instantiated.
 Declaring a variable to hold an object is just like declaring a variable to hold a value of
primitive type.
 Declaration does not create new objects. It is simply variable that can refer to an object.
 For example: Rectangle rect1;

 Steps for creating objects:


B. Instantiating an object:
 Creating an object is also referred to as instantiating an object.
 Objects in java are created using the new operator.
 The new operator creates an object of the specified class and retur ns a reference to that
object.
 For example: Rectangle rect1 = new Rectangle ();
Assigns the object reference to the variable. The variable rect1 is now an object of the
rectangle class .
 Steps for creating objects:
C. Initializing an object:
 Classes provide constructor methods to initialize a new object of that type.
 A class may provide multiple constructors to perform different kinds of initialization on
new objects.
 For example: Rectangle rect1=new Rectangle (10, 20);

Defining a Class:

User defined data type.

Once a new data type is defined using a class, it can be used to create objects of that type.

A class is a template for an object and object is an instance of a class.

Sou.Venutai Chavan Polytechnic,Pune. 14


Java Programming (22412)

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

void getdata(int x, int y) //definition of method

{
length = x;

width = y;

Java Tokens

A token is the smallest element of a program that is meaningful to the compiler.

Token Meaning Example


Keyword A variable is a meaningful name of int continue
data storage location in computer break public
memory. When using a variable return do
you refer to memory address of while for
computer.
Constant Constants are expressions with a Final int a=20;
fixed value. They are also called as
literals
Syntax: final
data_typevariable_name;

Sou.Venutai Chavan Polytechnic,Pune. 15


Java Programming (22412)

Identifier Identifiers are the names of MYVARIABLE


variables,methods,classes,packages _myvariable
and interfaces. $myvariable
_9pins
andros
??????
String Sequence of characters. char[] ch={'a','t','n','y','l','a'};
Strings=new String(ch);
Special Symbol Symbols other than the Alphabets [](){},;*=
and Digits and white-spaces.
Operators A symbol that represents a specific /+==?
mathematical or non-mathematical
action.

Java Keywords-:

Constant/Literals:

Constants/Literals are an identifier whose value is fixed and does not change during the
execution of the program.

Sou.Venutai Chavan Polytechnic,Pune. 16


Java Programming (22412)

Fig, Constant/Literals:

Sou.Venutai Chavan Polytechnic,Pune. 17


Java Programming (22412)

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.

Sou.Venutai Chavan Polytechnic,Pune. 18


Java Programming (22412)

 A variable is assigned with a data type.


 Variable is a name of memory location.

Rules for naming variable:


1.

2.

3.

4.

5.

6.

Types/Scope of Variables :
 Local

A variable that is declared inside the method is called Local Variable.

 Instance

A variable that is declared inside the class but outside the method is called instance variable.

 Class/ Static

Sou.Venutai Chavan Polytechnic,Pune. 19


Java Programming (22412)

A variable that is declared as static is called as Class/Static variable.

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 and String:

 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.

Syntax: datatype[ ] arrayname;


Example: double[ ] percentage;

In Java, we can initialize arrays during declaration.

For Example: int[ ] age={12,4,5,2,5};

 String:
String is basically an object that represents sequence of char values.

Sou.Venutai Chavan Polytechnic,Pune. 20


Java Programming (22412)

An array of characters works same as Java string.

For example:
char[ ] ch={„M‟,‟S‟,‟B‟,‟T‟,‟E‟};

String s= new String(ch);

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

Operators: Arithmetic Operator

Arithmetic operators are used in mathematical expression in the same way that they are used
in algebra.

Operator Description Example Explanation


+ Addition x=y+z Adds the value of y and z and stores the result in x.
- Subtraction x=y-z Subtracts z from y and store the result in x.
* Multiplication x=y*z Multiplies the values y and z and stores result in x.
/ Division x=y/z Divides y by z and stores the result in x.
% Modulo x=y% z Divides by z and stores the remainder in x.

 Example:

public class Demo


{
public static void main(String args[])

Sou.Venutai Chavan Polytechnic,Pune. 21


Java Programming (22412)

{
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

Operators: Increment and Decrement Operators

Operator Description Example Explanation


++ Increases the value of the operand x++ Equivalent to x=x+1
by one.
-- Decreases the value of the operand x-- Equivalent to x=x-1
by one.

 Example:

public class Demo1

public static void main (String args[])

int number=50;

Sou.Venutai Chavan Polytechnic,Pune. 22


Java Programming (22412)

System.out.println("Number is"+number);

number++; //Increment number.


System.out.println("Now,number is"+number);

number--;//Decrement number.
System.out.println("Now,number is"+number);
}
}

 Output

Operators: Pre-increment and Post-increment Operators Initial value of x


 Pre-increment- If an Increment operator is used in front of an operand, then it is
called as Pre -Increment operator.

 Post-increment- If an Increment operator is used after an operand, then is called Post


Increment operator.

Initial value of x Expression Final value of y Final value of x


3 y=x++ 3 4
3 y=++x 4 4
3 y=x-- 3 2
3 y=--x 2 2

 Example:

public class Increment_Decrement


{
public static void main(String args[])
{
int a=5, b, c, d, e;
b = ++a;

Sou.Venutai Chavan Polytechnic,Pune. 23


Java Programming (22412)

System.out.println("Result after Pre Increment a:"+a);


System.out.println("Result after Pre Increment b:"+b);

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

Operators: Comparison/Relational Operators

Operator Description Example Explanation


== Evaluate whether the operands are x==y Returns true if the values are
equal. equal and false if otherwise.
!= Evaluates whether the operands are x!=y Returns true if the values are
not equal. not equal and false if
otherwise.
> Evaluates whether the left operand is x>y Returns true of x is greater than
greater than the right operand. y and false if otherwise.
< Evaluates whether the left operand is x<y Returns true if x is less than y
less than the right operand. and false if otherwise.

Sou.Venutai Chavan Polytechnic,Pune. 24


Java Programming (22412)

>= 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:

public class Demo_relational_op


{
public static void main(String args[])
{
int a=10;
int b=20;
System.out.println("a==b="+(a==b));
System.out.println("a!=b="+(a!=b));
System.out.println("a>b="+(a>b));
System.out.println("a<b="+(a<b));
System.out.println("b>=a="+(b>=a));
System.out.println("b<=a="+(b<=a));
}
}

 Output

Operators-Bit wise

In Java, an operator is a symbol that performs the specified operations.

 Types of Bitwise Operator

Sou.Venutai Chavan Polytechnic,Pune. 25


Java Programming (22412)

Operators Symbol Uses

Bitwise AND & op1 & op2

Bitwise exclusive OR ^ op1 ^ op2

Bitwise inclusive OR | op1 | op2

Bitwise Compliment ~ ~ op

Bitwise left shift << op1 << op2

Bitwise right shift >> op1 >> op2

Unsigned Right Shift Operator >>> op >>> number of places to shift

 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));

System.out.println(“One‟s Compliment=” +(~a));

System.out.println(“Shift Left=” +(a<<b));

System.out.println(“Shift Right=” +(a>>b));

System.out.println(“Shift Right with Zero Fill==” +(a>>>b));

Sou.Venutai Chavan Polytechnic,Pune. 26


Java Programming (22412)

Operators: Logical Operators

 && 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
}
}

Sou.Venutai Chavan Polytechnic,Pune. 27


Java Programming (22412)

Operators: Conditional/Ternary Operators

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:

public class Demo_Ternary


{
public static void main(String args[])
{
int number=13;
//Using ternary operator if(number%2==0)
String output=(number%2==0)?"even number":"odd System.out.println("even
number"; number");
else
System.out.println(output); System.out.println("odd
number");
}
}

 Output

Sou.Venutai Chavan Polytechnic,Pune. 28


Java Programming (22412)

Operator Precedence and Precedence order:

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;

 Operator Precedence Table :


The table lists the precedence of operators in Java; higher it appears in the table, the higher
Its precedence.

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 = += -= *= /= %=&= ^= |= <<= >>= >>>=

Sou.Venutai Chavan Polytechnic,Pune. 29


Java Programming (22412)

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.

Operators Precedence Associativity

postfix increment and ++ -- left to right


decrement
prefix increment and ++ --+ -~ ! right to left
decrement, and unary
multiplicative */% left to right

additive +- left to right

shift << >> >>> left to right

relational < > <= >= instance of left to right

equality == != left to right

bitwise AND & left to right

bitwise exclusive OR ^ left to right

bitwise inclusive OR | left to right

logical AND && left to right

logical OR || left to right

ternary ?: right to left

assignment = += -= *= /= %=&= ^= |= right to left


<<= >>= >>>=

Sou.Venutai Chavan Polytechnic,Pune. 30


Java Programming (22412)

Expression of Evaluation:
An expression is a construct which is made up of literals, variables, method calls and
operators following the syntax of Java.

 Every expression consists of at least one operator and an operand.


 Operand can be either a literal, variable or a method invocation.
 It is common for an expression to have more than one operator.

 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,

Sou.Venutai Chavan Polytechnic,Pune. 31


Java Programming (22412)

Function Description Syntax Example

abs( ) abs( ) method is used to find absolute Math.abs(variable); Math.abs(-2.3);


value of variable.
Output: 2.3

min( ) Min method disused to find minimum Math.min(variable1,variable2) Math.min(2,8);


value betweenvariable1andvariable2.
Here variable can be output = 2
double,float,int

and long datatype

max ( ) Max method disused to find maximum Math.max(variable1,variable2) Math.max(2,8);


value between variable1 and variable2.
Here variable can be Output: 8
double,float,int

and long datatype

sqrt() Sqrt method is used for finding square Math.sqrt(variable) Math.sqrt(9);


root of a number.
Here variable is double datatype Output: 3

exp ( ) Euler's number e raised to the power of a Math.exp(variable) Math.exp(2);


variable.
Here variable is double datatype Output:
7.38905609893
065

round() Rounds to the nearest integer. Math.round(variable)


Math.round(variable) Math.round(1.0Math.round(
2)=1 Math.round(
Math.round(-
2.1)=-2

Sou.Venutai Chavan Polytechnic,Pune. 32


Java Programming (22412)

 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.

Sou.Venutai Chavan Polytechnic,Pune. 33


Java Programming (22412)

 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

 Converting a higher datatype to a lower datatype is known as 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:

public class demo_E


{

Sou.Venutai Chavan Polytechnic,Pune. 34


Java Programming (22412)

public static void main(String args[])


{
double a = 9.78;
int b= (int) a; // Explicit casting: double to int
System.out.println(a);
System.out.println(b);
}
}

Output

Java if Statement

 The Java if statement tests the condition.

 It executes the if block if condition is true.

Syntax:
if(condition)
{
//code to be executed
}

Example:

public class if_demo


{
public static void main(String args[])
{
int age=20;
if (age > 18)
{
System.out.println("age is greater than 18");

Sou.Venutai Chavan Polytechnic,Pune. 35


Java Programming (22412)

}
}
}

Output

Java if-else Statement


Java if-else statement also tests the condition.
 It executes the if block if condition is true otherwise else block is executed.
Syntax:

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)

}
}

Java if-else –if Statement


The if-else-if ladder statement executes one condition from
Multiple statements.

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.");
}

Sou.Venutai Chavan Polytechnic,Pune. 37


Java Programming (22412)

else if (number < 0)


{
System.out.println("The number is negative.");
}
else
{
System.out.println("The number is 0.");
}
}
}
}

Output

Java nested if Statement


 The nested if statement represents the if block within another if block.

 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[])

Sou.Venutai Chavan Polytechnic,Pune. 38


Java Programming (22412)

{
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

Java switch Statement

 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.

Sou.Venutai Chavan Polytechnic,Pune. 39


Java Programming (22412)

 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;

Sou.Venutai Chavan Polytechnic,Pune. 40


Java Programming (22412)

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);
}
}
}

Sou.Venutai Chavan Polytechnic,Pune. 41


Java Programming (22412)

 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:

Public class ContinueDemo


{
Public static void main(String[]args)
{
for(int i=1;i<=10;i++)
{
if(i==5)
{
continue;
}
System.out.println(i);
}
}
}

 Output

Sou.Venutai Chavan Polytechnic,Pune. 42


Java Programming (22412)

While loop

 The Java while loop is used to iterate a part of the program several times.

 If the number of iteration is not fixed, it is recommended to use while loop.

 Syntax

while(condition)
{
//code to be executed
}

 Example:

public class WhileExample


{
public static void main(String args[])
{
int i=1;
while(i<=10)
{
System.out.println(i);
i++;
}
}
}

Sou.Venutai Chavan Polytechnic,Pune. 43


Java Programming (22412)

 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:

public class DoWhileExample


{
public static void main(String args[])
{
int i=1;
do
{
System.out.println(i);
i++;
}
while(i<=10);

Sou.Venutai Chavan Polytechnic,Pune. 44


Java Programming (22412)

}
}

 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);
}
}
}

Sou.Venutai Chavan Polytechnic,Pune. 45


Java Programming (22412)

 Output

For each loop


 The for-each loop is used to traverse array or collection in java.
 It is easier to use than simple for loop because we don't need to increment value.
 Syntax
for(Type var:array)
{
//code to be executed
}

 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);
}
}

Sou.Venutai Chavan Polytechnic,Pune. 46


Java Programming (22412)

 Output

Sou.Venutai Chavan Polytechnic,Pune. 47

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy