Unit 1

You might also like

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

Java Programming(I Scheme 22412)

CHAPTER 1 10 Marks
Basic Syntactical Concepts in Java
• Java is a high-level, general-purpose, and pure object-oriented programming
language. Java applications are typically compiled to bytecode (class file) that can run
on any Java virtual machine (JVM).
• Java was developed by James Gosling at Sun Microsystems of USA in 1991. The
language was initially called Oak. Java was invented for the development of software
for consumer electronic devices like TVs, toasters, etc. The main aim had to make java
simple, portable and reliable.
• Java supports "Write Once, Run Anywhere" (WORA). It means Java can be developed
on any device, compiled into a standard bytecode and be expected to run on any
device with a Java virtual machine (JVM).

Two ways to develop java Programs:


1) Stand-alone applications
2) Applets

1) Stand-alone applications are programs written in Java to carry out certain tasks
on a stand-alone local computer. Executing a stand-alone Java programs involves
two steps:
i. Compiling source code into bytecode program using javac compiler
ii. Executing the bytecode program using java interpreter.

2) Applets are small Java programs developed for Internet applications. An applet
located on a server can be downloaded via Internet and executed on a local
computer using Java capable browser.
Java Editions
Sun has three editions of Java for a given platform or version (the current platform is
Java 2). The editions for the current platform are:
1. J2ME (Micro Edition):
It is used to create programs that run on small handheld devices, such as phones,
PDAs (personal digital assistants), and appliances.
2. J2SE (Standard Edition):
It is used primarily to create programs for desktop computers or for any computer
too large for J2ME and too small for J2EE.
3. J2EE (Enterprise Edition):
It is used to create very large programs that run on servers managing heavy traffic
and complicated transactions. These programs are the backbone of many online
services, such as banking, e-commerce, and B2B (business-to-business) trading
systems.

1
Java Programming(I Scheme 22412)

1.1 Features of Java


Features of Java are as follows:
1) Compiled & Interpreted 6) Distributed
2) Platform Independent 7) Familiar, simple and small
3) Portable 8) Multithreaded and Interactive
4) Object- oriented 9) High performance
5) Robust and secure 10) Dynamic and Extensible
1) Compiled and Interpreted
• Java comes with compilation and interpretation, thus making Java a two-stage
system.
• Java compiler translates Java code to Bytecode instructions. Bytecodes are not
machine instructions.
• Java Interpreter generates machine code that can be directly executed by machine
that is running the Java program.

Compilation Java Java Virtual


Stage Program Compiler Machine

Source Code Bytecode

Interpretation Bytecode Java Machine


Stage Interpreter Code
Virtual Machine Real Machine

2) Platform Independent
• Bytecode and JVM (Java Virtual Machine) makes Java as platform Independent
language.
• Java supports ‘Write Once Run Everywhere’ (WORA) strategy.
• Java programs are portable across operating systems and hardware environments. Java
programs can be easily moved from one computer system to another, anywhere
and anytime. Because of this Java is more popular language for programming on
Internet which interconnects different kind of systems worldwide.

3) Portable
• Java programs are portable across operating systems and hardware environments.
• Java programs can be easily moved from one computer system to another,
anywhere and anytime.
• Java certifies portability in two ways:
1) Java compiler generates the Bytecode and that can be executed on any
machine.
2) Size of primitive data types are machine independent.

4) Object- oriented
• Java is truly object-oriented language.

2
Java Programming(I Scheme 22412)

• Almost everything in Java is an Object. All program code and data exist in objects
and classes.
• Java also has basic OOP properties such as encapsulation, polymorphism, data
abstraction, inheritance etc.
• Java comes with an extensive set of classes, organized in packages.
• The object model in Java is simple and easy to extend.

5) Robust and secure


• Java is a robust language. It provides many securities to ensure reliable code.
• Java strictly checks possible problems or errors at compile time and also at
runtime, and eliminating situations that are error prone.
• It is designed as garbage–collected language. Java also includes the concept of
exception handling.
• 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 gain access to
memory location without proper authorization.

6) Distributed
• Java is designed for the distributed environment of the Internet/LAN, because it
handles TCP/IP protocols.
• Java is called as Distributed language for creating applications on networks.
• It has the ability to share both data and programs. Java applications can open and
access remote objects on Internet easily.

7) Simple, Small and Familiar


• Java is very small and simple language. Java does not use pointer and header
files, goto statements, etc.
• It eliminates operator overloading and multiple inheritance.
• Java is familiar because it uses many constructs of C and C++.

8) Multithreaded and Interactive


• A multithreaded program contains two or more parts that can run concurrently.
Each part of such a program is called a thread, and each thread defines a separate
path of execution.
• Thus, multithreading is a specialized form of multitasking. Java maintains
multithreaded programs.
• This feature is improves the interactive performance of graphical applications.

9) High Performance
• Java performance is very high, mainly due to the use of intermediate bytecode.
• Multithreading enhances the overall execution speed of Java programs.
10) Dynamic and Extensible
• Java is a dynamic language. Java dynamically links new class libraries, methods
and objects.
3
Java Programming(I Scheme 22412)

• Java programs support functions written in other languages such as C and C++.
These functions are known as native methods. Native methods linked dynamically
at runtime.

Bytecode:
• To solve both the security and the portability problems the output of a Java
compiler is not executable code. Rather, it is bytecode.
• Java compiler convert the source code into Intermediate code is called as
bytecode. This machine is called the Java Virtual Machine and it exits only inside
the computer memory.
• Bytecode is a highly optimized set of instructions designed to be executed by the
Java run-time system, which is called the Java Virtual Machine (JVM). Java Virtual
machine exists only inside the computer memory.
• Java program is executed by the JVM also helps to make it secure.
• The use of bytecode enables the JVM to execute programs much faster.

Java Virtual machine:


• Java compiler convert the source code into Intermediate code is called as
bytecode. This machine is called the Java Virtual Machine and it exits only inside
the computer memory. Following figure shows the process of compilation.
Compilation Java Java Virtual
Stage Program Compiler Machine

Source Code Bytecode


• The Virtual machine code is not machine specific.
• The JVM is an interpreter for bytecode.
• The machine specific code is generated by Java interpreter and it acts as an
intermediary between the virtual machine and real machines shown below

Interpretation Bytecode Java Machine


Stage Interpreter Code

Virtual Machine Real Machine


• The programs that are running on JVM must be compiled into a binary format
which is denoted by .class files. JVM will differ from platform to platform.
• The JVM executes .class or .jar files, by either interpreting it or using a just-in-time
compiler (JIT). The JIT is used for compiling and not for interpreting the file. It is
used in most JVMs today to achieve greater speed.

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).
• Java Standard Library (JSL) is also known as the Application Programming Interface
(API).

4
Java Programming(I Scheme 22412)

❖ Java Development kit (JDK) –


• The JDK comes with a set of tools that are used for developing and running
Java program. It includes following tools:
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 disassembler, which convert byte code into program
description)
5. javah(It is for java C header files)
6. javadoc(It is for creating HTML document)
7. jdb(It is Java debugger )
Tool Description
appletviewer Enables us to run Java applets.
Java interpreter, which runs applets and applications by
java
reading and interpreting bytecode files.
The Java compiler, which translates Java Source code to
javac
bytecode files that the interpreter can understand.
Creates HTML-format documentation from Java source code
javadoc
files.
javah Produces header files for use with the native methods.
Java disassembler, which enables us to convert bytecode files
javap
into a program description.
jdb Java debugger, which helps us to find errors in our programs.

• For example: For compiling and running the program we have to use following
commands:
a) javac (Java compiler)
✓ Java compiler converts the source code or program in bytecode. That is java
compiler convert “.java” file in “.class” file.
✓ To compile the program, execute the compiler, javac, specifying the name of the
source file on the command line
✓ Syntax: C:\javac filename.java
✓ Example :If my filename is abc.java then the syntax will be
C:\javac abc.java
b) java (Java Interpreter)
✓ To actually run the program, you must use the Java application launcher, called
java.
✓ Java interpreter converts bytecode into machine code and executes the
program to produce result.
✓ Syntax: C:\java filename
✓ Example: If my filename is abc.java then the syntax will be

5
Java Programming(I Scheme 22412)

C:\java abc
❖ A First Simple Program
class Sample
{
public static void main(String args[ ])
{
System.out.println ("Welcome to Java");
}
}
The file must be equivalent to the class name containing the main method i.e.
“Sample.java”.
• Class Declaration:
The first line Class Sample , declares a class, which is an object-oriented construct.
Sample is a Java identifier that specifies the name of the class to be defined.
• Opening and Closing Brace:
Every class definition in Java begins with an opening brace “{“ and ends with a
matching closing brace “}”. A class definition in Java does not end with a semicolon.
• The main line:
The third line
public static void main(String args[ ])
defines a method named main. Every Java application program must include the
main() method. This is the starting point for the interpreter to begin the execution of the
program. A Java application can have any number of classes but only one of them
must include a main method to initiate the execution. Java applets will not use the
main method at all.
The keyword public is an access specifier that declares the
public main() method as unprotected and therefore making it accessible
to all other classes.
The keyword static declares this method as one that belongs to
entire class and not a part of any objects. The main() must be
static
declared as static since the interpreter uses this method before
any objects are created.
The type modifier void states that the main() method does not
void
return any value.
String args[ ] declares a parameter named args, which contains
String args[ ]
an array of objects of the class type String
• The output line:
System.out.println (“welcome to Java”);
The println method is a member of the out object, which is a static data member of
System class. This line prints the string
Welcome to Java.

6
Java Programming(I Scheme 22412)

1.2 Defining a Class, Creating Objects and accessing class


members
❖ Defining a Class
• A class is a user defined prototype from which objects are created. It represents
the set of properties or methods that are common to all objects of one type.
• A class is a collection of objects of similar type. Once defined, this new data type
can be used to create objects of that type.
• The class contains two parts i.e. instance variables and methods.
• A class is declared by the keyword class. Class definition form is given below.
• The data or variables defined within a class are called as instance variables
because each instance of the class contains its own separate copy of variables.
The code is contained within the methods.
• Syntax:
[modifier] class Classname
{
//fields declarations
//constructor or method declarations
}

• Modifiers : A class can be public or has default access.


• Class name: The classname is an identifier. The name should begin with an initial
letter capitalized by convention.
• Body: The class body surrounded by braces, { }.
• Constructors are used for initializing new objects. Fields are variables that provide
the state of the class and its objects, and methods are used to implement the
behavior of the class and its objects.
• For example:
class Student
{
int rollno;
String name;
void display()
{
System.out.println(“Roll no=”+rollno);
System.out.println(“Name=”+name);
}
}

❖ Creating Objects:
• Objects are the variables of class. It is a basic unit of Object Oriented
programming and represents the real life entities. Object is the instance of the
class.
• In Java, the new keyword is used to create new objects.
7
Java Programming(I Scheme 22412)

• There are two steps when creating an object from a class −


1. Declaration − A variable declaration with a variable name with an object type.

2. Instantiation/ Initialization − The 'new' keyword is used to create the object.


The 'new' keyword is followed by a call to a constructor.
• Syntax
classname class_var;
class_var = new classname();

or
className objectName = new className(Parameters);

• Example:
Student s1; // Declaration
s1=new Student(); //Instantiation/Initialization

Or
Student s1=new Student(); // Declaration & Instantiation/Initialization
Here, Student ( ) specifies the default constructor of the class
• The new operator dynamically allocates the memory for the object. That is, it
allocates the memory at run time.
Action Result
Declare Student s1; Null

Instantiate s1 = new Student() S1

Student
Fig :Declaring and creating object object

❖ Accessing class members


• Dot operator or member selection operator is used to access the instance variables
and methods of the class.
• We cannot access the instance variables and methods outside of the class without
referring to the object.
• Instance variables and methods are accessed via created objects. To access an
instance variable, following is the fully qualified path.
• Syntax:
/* Now call a variable as follows */
Object.variableName;

/* Now you can call a class method as follows */


Object.MethodName();

• For example: the instance variables and methods of the class ‘Student’ can be
accessed as,
s1.rollno=10;
s1.name=”xyz”;
8
Java Programming(I Scheme 22412)

s1.display();

• Example Program:
class Student
{
int rollno;
String name;
void display()
{
System.out.println(“Roll no=”+rollno);
System.out.println(“Name=”+name);
}
}
Class Demo
{
public static void main(String args[])
{
Student s=new Student ();
s1.rollno=10;
s.name=”xyz”;
s.display();
}
}

1.3 Java Tokens and Data types:


Java Tokens:
• A java Program is made up of Classes and Methods and in the Methods are the
Container of the various Statements And a Statement is made up of Variables,
Constants, operators etc .
• Tokens are the various Java program elements which are identified by the
compiler. A token is the smallest individual unit of a program. Tokens supported in
Java include keywords, variables, constants, special characters, operations etc.
• Following are the tokens used in Java programming language.
1. Keywords
2. Identifiers
3. Literals
4. Operators
5. Separators
1) Keywords:
• Java language has reserved words as keyword.
• Keywords have specific meaning in Java we cannot use them as names for
variables, classes, methods and so … on.
• All keywords are to be written in lower case letters.
• Java is case sensitive.

9
Java Programming(I Scheme 22412)

2) Identifies :
• Identifiers are programmer designed tokens.
• They are used for naming classes, methods, variable objects, labels,
packages and interfaces in a program.
• Java identifiers follow the following rules.

1) They can have alphabets, digits & underscore & dollar sign characters.
2) They must not begin with a digit.
3) Upper case & lower case letters are distinct.
4) They can be of any length.

3) Literal :
• Literals in Java are a sequence of character (digits, letters and other
character) that represent constant values to be stored in variables.
• Types of literals:
i. Integer literals
ii. Floating point literals
iii. Character literals
iv. String literals
v. Boolean literals

4) Operators :
An operator is a symbol that takes one or more argyments and operates on
them to produce a result.

5) Separators :
• Separators are symbols used to indicate where groups of code are divided
and arranged.
Parentheses ( ) Used to enclosed parameters in method definition.
Braces { } 1. Define a block of code for classes methods and
local scope.
2. Automatically initialize values to array.
Brackets [ ] Used to declare array types.
Semicolon ; Used to separate statement.
Comma , Used to separate identifiers in a variable deceleration.

Constants:
✓ Constant is an entity that does not change during the program execution. Constant
means fixed value.
✓ In Java, there are two types of constant as follows:
1. Numeric Constants
• Integer constant
• Real constant
2. Character Constants
10
Java Programming(I Scheme 22412)

• Character constant
• String constant
Integer constant:
✓ An integer constant refers to a series of digits. There are three types of integers:
decimal integer, octal integer, and hexadecimal integer.
1) Decimal Integer: Decimal Integer consists of a set of digits from 0 to 9. Embedded
spaces, commas and characters are not allowed in between digits.
For example: 123
-321
654321
2) Octal Integer: It consists of a set of digits from 0 to 7 with a leading 0.
For example: 011
0425
3) Hexadecimal Integer: A series of digits preceded by 0x or 0X is considered as
hexadecimal integers. They may also include alphabets from A to F or from a to f.
For example: 0x7
0XA
Real constant:
✓ It allows fractional data and it is also called as floating point constant. It is used for
percentage, height, temperature and so on.
✓ For example: 0.0234
0.777
-1.23
✓ A real number may also be expressed in exponential notation (scientific notation).
The general form is
mantissa e exponent

✓ The mantissa is either a real number expressed in decimal notation or an integer.


The exponent is an integer with an optional plus or minus sign.
✓ For example: 7500000000 may be written as 7.5E9 or 75E8

Character Constant
✓ It allows single character within pair of single quote.
✓ For example: ‘A‘ ‘7‘ ‘+’

String Constant
✓ String constant is series of characters within pair of double quotes.
✓ For example: “WELCOME” “1997” “Hello Java”

Backslash character constant:


✓ Java support some special character constant which are given in following table.
Constant Importance
‘\b’ Back space

11
Java Programming(I Scheme 22412)

‘\t’ Tab
‘\n’ New line
‘\\’ Backslash
‘\’’ Single quote
‘\”\ Double quote

Variables:
• The variable is the basic unit of storage. A variable is an identifier that denotes a
storage location used to store a data value.
• A variable is an entity that may change during program execution. A variable can
be used to store a value of any data type.
❖ Rules for variable name:
Variable names may consist of alphabets, digits, underscore and dollar character.
1) They must not begin with a digit.
2) Uppercase and lowercase are distinct. This means that the variable total is not
same as Total or TOTAL.
3) It should not be a keyword.
4) White space is not allowed.
5) Variable names can be of any length.
❖ Declaration of variables:
✓ A variable must be declared before it is used in the program.
✓ Variable declaration does three things:
1) It tells the compiler what the variable name is.
2) It specifies what type of data the variable will hold.
3) The place of declaration decides the scope of the variable.
✓ Syntax: type variable1, variable2, ……….., variablen;

✓ Examples:
int a, b, c; // declares three ints, a, b, and c.
int d = 3, e, f = 5; // declares three more ints, initializing d and f.
byte z = 22; // initializes z.
double pi = 3.14159; // declares an approximation of pi.
char x = 'x'; // the variable x has the value 'x'.

❖ Types of variable:
There are three types of variables in Java.
1) Local Variables: These are declared and used inside methods.
2) Instance Variables: These are declared inside a class but outside any method.
Each object has its own copy of instance variables. So, these variables are created
when objects are instantiated.
3) Static / Class Variables: These are global to the class and doesn’t belong to any
particular object. There is one copy of each static variable is created per class when
the class is loaded.
12
Java Programming(I Scheme 22412)

❖ Giving values to variables (Variable Initialization)


✓ The process of giving initial values to variables is known as initialization.
✓ A variable must be given a value after it has been declared but before it is used in
the expression.
✓ This can be done in two ways.
1. By using assignment statement
2. By reading from the keyboard
1. By using assignment statement
✓ The simple method of giving a value to the variable name is through the
assignment statement as given below:
Variablename=value
✓ For example: Pi = 3.14f;;
yes = ‘y’;
first = 150;
✓ It is also possible to assign a value to a variable at the time of declaration. This
takes the following form:
datatype Variablename=value;
✓ For example:
float Pi = 3.14f;
char yes = ‘y’;
short first = 150;

2. By reading from the keyboard (Dynamic Initialization)


✓ We may also give values to the variables through by using various classes and
their methods. One of the useful classes among them is Scanner.
✓ This class is defined in java.util. So in order to use is in our program we have to
use following import statement at the top of our program.
import java.util.Scanner;
or import java.util.*;
✓ We have to create the object of scanner in following way.
Scanner in = new Scanner(System.in);
✓ System.in is standard input handle i.e. keyboard. ‘in’ is the object of the Scanner
class, which is then used to read any type of the data from keyboard in it.
✓ We have to use any of the following methods according to the requirement.
1. nextBoolean() for reading boolean values
2. nextByte() for reading byte values
3. nextFloat() for reading float values
4. nextDouble() for reading double values
5. nextInt() for reading int values
6. nextShort() for reading short values
7. nextLong() for reading long values
8. next() and nextLine() for reading String values

13
Java Programming(I Scheme 22412)

Data Types:
• A data type is a scheme for representing values.
• The data type defines the type of data that a variable holds.
• There are two types of data types
1. Primitive data type
2. Non-primitive data type
• Java defines eight primitive types of data: byte, short, int, long, char, float,
double, and boolean.

Data Types in Java

Primitive Non-Primitive
(Intrinsic) (Derived)

Numeric Non-Numeric Classes Interfaces Arrays

Integer Floating Point Character Boolean

Fig: Data Types in Java

Size and Ranges of Data Types


Default
Type Size Minimum Value Maximum Value
Value
byte 1 byte -128 (-2^7) 127 (2^7 -1) 0
short 2 bytes -32768 (-2^15) 32767 (2^15 -1) 0
int 4 bytes -2,147,483,648 (-2^31) 2,147,483,647 (2^31 -1) 0
-9,223,372,036,854,775,808 9,223,372,036,854,775,807
long 8 bytes 0l or 0L
(-2^63) (2^63 -1)
float 4 bytes 3.4e-038 3.4e+38 0.0f
double 8 bytes 3.4e-038 1.7e+308 0.0d
character 2 bytes 0 65535 0
boolean 1 bit Either true or false false

1) Integer types:
✓ Integer data type can hold the whole numbers, such as 123, -98, and 3456.
✓ In Java, there are four types of integer as follows:
• byte
• short
• int
• long
✓ We can make integer long by adding ‘l’ or ‘L‘ at the end of the number. For
example: 123L or 123l.
✓ The number can be positive number or negative number.
✓ Byte and short data types are used to save space in large arrays

14
Java Programming(I Scheme 22412)

2) Floating Point types:


✓ Integer types are not sufficient to hold data such as distance, heights, weights,
prices, temperature, and so on. To store such data floating point type is used.
✓ There are two types of floating point types: 1) float 2) double
✓ The float type values are single-precision numbers and the double types are
double- precision numbers.
✓ Floating point numbers are treated as double- precision numbers.
✓ To force them to be in single-precision mode, we must append f or F to the
numbers. For example: 1.23f or 1.23F.

3) Character type:
✓ To store character constant, Java provides a character data type called char.
✓ It uses 16-bit Unicode (0 to 65535).
✓ It can hold only a single character. Its default value is null character
✓ Size of char type is 2 bytes.
4) Boolean type:
✓ Boolean type is used when we want to test a particular condition during the
execution of the program.
✓ Boolean type can take only two values: true or false.
✓ This data type is used for simple flags that track true/false conditions.
✓ Default value is false.
✓ Uses only 1bit of storage.
Scope of Variable:
• Java allows variables to be declared within any block. A block defines a scope.
• The area of the program where the variable is accessible (i.e., usable) is
called its scope.
• Variables declared inside a scope are not visible (that is, accessible) to code that is
defined outside that scope.
• Thus, when you declare a variable within a scope, you are localizing that variable
and protecting it from unauthorized access and modification.
• There are three kinds of variables in Java:
1) Local variables
2) Instance variables
3) Class/static variables
• 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.
✓ Access modifiers cannot be used for local variables.
• Instance variables:
✓ Instance variables are variables within a class but outside any method.
15
Java Programming(I Scheme 22412)

✓ 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.
✓ Instance variables are created when an object is created with the use of the
key word 'new' and destroyed when the object is destroyed.

• Class/static variables :
✓ Static variables declared within a class, outside any method are referred to as
class variables.

• For example:
class Demo
{
int x; //instance variable
static int y; //class variable or staic variable
void get(int z) //z is local variable
{
x=z;
}
}

The variable x is declared in Block1 and


available in all the three blocks.
Variable n is declared in Block2 and
available only in Block2, it goes out of
scope at the end of Block2. Similarly,
variable m is accessible only in Block3.

Symbolic Constant
• We have already known certain universal constants. For example, value of Pi (π) in
3.14, value of gravitational constant if 9.81 etc.
• If we want to define the constant in Java one type modifier is used called final.
‘final’ is the keyword used to define the symbolic constant in a Java
program.
• It takes the following form:
final data_type symbolic_name = value;

16
Java Programming(I Scheme 22412)

• The value assigned to the symbolic name is constant and cannot be changed in
any case in the program. At the time of declaration, it is necessary to assign the
value to the variable.
• For example: final double PI = 3.145;
final float GVT= 9.81f;
final int max = 1000;
• We can use the symbolic constants in program in any expression but cannot
modify their value.
• Symbolic names take the same form as variable names. But, they are usually
written in CAPITALS to distinguish them from normal variable names. This is not a
rule.
• They cannot be declared inside a method. They should be used only as class data
members in the beginning of the class.
//Program on Symbolic Constants
class Area1
{ public static void main(String args[]) Output:
{
Area of circle=94.985
final float PI=3.14f;
float r=5.5f;
float area=PI*r*r;
System.out.println ("Area of circle="+area);
}
}

Type Casting:
• Although the automatic type conversions are helpful, they will not fulfill all our
needs. We often face the situation where there is need to store the value of one
type into variable of another type. In such situations, it is necessary to cast or
temporary convert the variable of one type into another type. It is performed by type
casting.
• Casting into a smaller type may result in the loss of data.
• Widening: In automatic type conversion always lower type is converted to higher
type. This type of conversion is called as widening the conversion.
• Narrowing: If we want to convert higher type to lower type then type casting is
necessary. For that purpose the type casting operator is used. This type of
conversion is called as narrowing the conversion.
• It takes the following form.
(target type) Variablename;

Here, target type specifies the desired type to convert the specified value.
For example, if we want to convert int to byte or long ,then
int val = 163;
byte b = (byte) val;
• Without type casting it is not possible to assign higher data value to lower one.

17
Java Programming(I Scheme 22412)

// Program on Type casting


class Casting
{ Output:
public static void main(String args[])
-93
{
int val = 163;
byte b = (byte) val;
System.out.println(b);
}
}
Array and String
Array:
• An array is object that holds a fixed number of values of a single type.
• The length of an array is established when the array is created. After creation, its
length is fixed.
• Each item in an array is called an element, and each element is accessed by its
numerical index. Array index starts from 0(zero).
• Syntax:
datatype arrayname[ ]=new datatype[size];

• For example:
int array[ ]=new int[5];
• Here, array1 is the name of array, which allocates memory for 5 int type elements.
• We can initialize array by using index. such as,
array[0]=100;
array[1]=200;
array[2]=300;
array[3]=400;
array[4]=500;

String:
• Strings are a sequence of characters. In the Java programming language, strings
are objects.
• The Java platform provides the String class to create and manipulate strings.
• Syntax:
String variablename=”value”; or
String variablename=new String(“value”);
• For Example:
String name=”xyz”;
String city=new String(“Solapur”);

1.4 Operators and Expression


• An operator is the symbol that takes one or more arguments and operates on them
to produce a result.
• The constants, variables or expression on which operator operates are called as
operands.
18
Java Programming(I Scheme 22412)

• Java supports a rich set of operators which are used in a program, to manipulate
the data and variables. Operators in Java are classified into number of categories:
1) Arithmetic Operators 5) Logical Operators
2) Assignment Operators 6) Conditional Operators
3) Increment / Decrement Operators 7) Special Operators
4) Relational Operators

1) Arithmetic Operators
• These include all the operators which are used to perform basic arithmetic
operations. These are listed and explained in the following table.
Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo Division
• These can operate on any built-in numeric data types of java. We cannot use these
operators on boolean type.
• The modulus operator, %, returns the remainder of a division operation.
• When all the operands in an arithmetic expression are integer then it is called as
integer expression. They always return integer value.
For example: x = 10 and y = 3
Then, x + y = 13
x–y=7
x * y = 30
x / y = 3 (decimal part is truncated)
x % y = 1 (remainder of the division)
• When an arithmetic expression involves only real operands is called as real
arithmetic.
• When one of the operands is real and the other is integer, the operation is called as
mixed-mode expression.
• If any one of the operands is floating point, then the operation will generate the
floating point result.
• Thus, 25 / 10.0 will generate result 2.5
// Program on Arithmetic operators
class Arithmetic Output:
{ public static void main(String args[]) a=20
{ int a=20,b=6; b=6
a+b=26
System.out.println ("a="+a);
a-b=14
System.out.println ("b="+b); a*b=120
System.out.println ("a+b="+(a+b)); a/b=3.3333333
System.out.println ("a-b="+(a-b)); a%b=2
System.out.println ("a*b="+(a*b));
19
Java Programming(I Scheme 22412)

System.out.println ("a/b="+((float)a/b));
System.out.println ("a%b="+(a%b));
}
}

2) Relational Operators
• When we want to compare values of two variables for various means, relational
operators are used. After comparing these values we may take several decisions in
the program.
• Java supports six different relational operators. These are listed and
explained in the following table.
Operator Meaning
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
== Equal to
!= Not equal to
• Relational operators can be called as comparison operators.
• For example, we want to find the largest of two integers, we can use ‘>’ operators
to perform comparison.
• The expressions such as, x > 12 or x < y contains the relational operator. So,
they can be termed as relational expression.
• The value of relational expression can be either true or false.
• For example,
if x = 10 and y = 15 then, x < y is true while x > 20 is false

// Program on Relational Operators


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

20
Java Programming(I Scheme 22412)

3) Logical Operators
• There are only three logical operators which are related with the logical decisions.
These are listed in the following table
Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT
• First two operators are used to combine the conditions i.e. to form a compound
conditional expression. Third operator is used to inverse the condition.
• Example of && (Logical AND)
✓ For example,
x > y && k !=12
✓ This is termed as the logical expression or a compound relational
expression. Whole expression also returns the boolean value. That is, the
above expression will return true when the both the conditions (x > y) and (k
!= 12) are true. If any one of these conditions is false the expression will
return false.
• Example of || (Logical OR)
✓ For example,
m == 99 || j <= 10
✓ This logical expression involves the logical OR operator. The expression will
return true only when any one of the conditions (m==99 and j<=10) is true. If
both conditions are false, the whole expression will also return false. That is,
in order to evaluate the expression to true, any one of the condition must be
true.
• Example of ! (Logical NOT)
✓ This is the only unary logical operator and generally used to negate the
condition.
✓ The result of the expression will be inverted. That is, true will become false
and false will become true.
✓ For example, x = 36 then
! (x>40) will return true
! (x==36) will return false

// Program on Logical Operators Output:


a=20
class Logical b=10
{ (a>b)&&(a>15)=true
public static void main(String args[]) (a>b)||(a>25)=true
{ !(a>b)=false
int a=20,b=10;
System.out.println ("a="+a);
System.out.println ("b="+b);
System.out.println ("(a>b)&&(a>15)="+((a>b)&&(a>15)));
System.out.println ("(a>b)||(a>25)="+((a>b)||(a>25)));
System.out.println ("!(a>b)="+!(a>b));
21
Java Programming(I Scheme 22412)

}
}
4) Assignment operators
• Assignment operators are used to assign the value of an expression to
the variable. The general assignment operator is ‘=’. This is used to
assign the value given to its right side to the variable written on left
side.
• Other assignment operators are also known as shorthand assignment
operators.
• These shorthand assignment operators can be used to combine an
arithmetic operation with an assignment.
Operator Example Equivalent Statement
+= x +=10 x=x+10
-= x -=10 x=x-10
*= x *=10 x=x*10
/= x /=10 x=x/10
%= x %=10 x=x%10

// Program on Assignment Operators


class Assign
{
public static void main(String args[])
{ Output:
a = 15
int a = 10,b = 5,c = 3,d=10,e=25; b=3
a+=5; c = 15
b-=2; d=5
c*=5; e=5
d/=2;
e%=10;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
System.out.println("e = " + e);
}
}
5) Increment and Decrement operators
• Java is also having the increment and decrement operators’ i.e. ++ and – –. Both of
these are unary operators.
• The operator ++ adds 1 to the operand and – – subtracts 1 from the operand. They
are only associated with the variable name, not with the constant or the expression.
They can be written in following from:
x++ or x-- (post increment or post decrement)
++x or --x (pre increment or pre decrement)
22
Java Programming(I Scheme 22412)

• When the increment or decrement operator is used before variable, it is called as


pre-increment or pre-decrement operator. And when it is used after variable, it is
called as post-increment or post-decrement operator.
• For example,
z = 14;
y = z++;
Here, the value of variable y will be 14 and z will be 15,

// Program on Increment and Decrement Operators


class IncDec
{
public static void main(String args[])
{
int a = 10, b = 20;
int c, d,e,f;
c =++a;
Output:
System.out.println("\na = " + a);
a = 11
System.out.println("c = " + c); c = 11

d =a++; a = 12
System.out.println("\na = " + a); d = 11
System.out.println("d = " + d);
b = 19
e = 19
e =--b;
System.out.println("\nb = " + b); b = 18
System.out.println("e = " + e); f = 19

f =b--;
System.out.println("\nb = " + b);
System.out.println("f = " + f);
}
}

6) Conditional Operator
• The only ternary operator (operator having three operands) is defined in Java
called as conditional operator.
• The pair ? : is termed as conditional operator. This is used to construct the
conditional expression of the following form:
expression1 ? expression2 : expression3

23
Java Programming(I Scheme 22412)

• When the condition written is true then the expression1 is evaluated else
expression2 is executed. Means, any one of the expression1 and 2 is executed in
any case. It can also be called as if then- else operator.
• For example,
x = 45;
y = 22;
x = (y>25) ? y : 50;
After completion of third statement execution, value of x will become 50. Because,
the condition y>25 is false so first expression will not be executed. Only second
expression is evaluated. That is, 50 will be assigned to variable x.

//Program on Conditional operator: Output


class Conditional x = 25
{ y = 22
public static void main(String args[]) Now, x = 50
{
int x = 45, y = 22;
System.out.println ("x = "+x);
System.out.println ("y = "+y);
x = (y>25)? y: 50;
System.out.println ("Now, x = "+x);
}
}

7) Bitwise Operators
• In order to manipulate the data at the bit level, the bitwise operators are provided in
Java. These operators are used for testing the bits as well as shifting them to left or
right etc.
• Table shows the bitwise operators and their meaning.

• These can be applied to integer types only. That is, they cannot be used along with
float or double value.
• All these operators except one’s complement operator are binary operato rs.
• Shift operators shift the binary equivalent bits of the operand to respective left or
right position.
• >>> operator is one of the special type of bitwise operator which is generally used
for the negative values which will be shifted to right by filling the zeroes to leftmost
positions.
24
Java Programming(I Scheme 22412)

For Example:
A B A&B A|B A^B ~A
0 0 0 0 0 1
0 1 0 1 1 1
1 0 0 1 1 0
1 1 1 1 0 0

//Program on Bitwise operator:

class Bitwise
{
public static void main(String args[])
{
int a = 4, b,c=20,d;
b = a << 2; Output
System.out.println("Original value of a: " + a); Original value of a: 4
System.out.println("after shifting 2 bits at left=" + b); after shifting 2 bits at left=16
Original value of c: 20
d = c >> 2; after shifting 2 bits at right=5
System.out.println("Original value of c: " + c);
System.out.println("after shifting 2 bits at right=" + d);
}
}

8) Special Operators
• Java supports two special operators.
1) instanceof operator 2) Member selection operator or dot operator (.)
• Instanceof operator:
- An instanceof is the keyword called as an object reference binary operator.
This operator allows us to determine whether the object belong to particular
class or not.
- Syntax: objectname instanceof classname;
- For example: apple instanceof Fruit
Returns true if the ‘apple’ is the object of class ‘Fruit’. Otherwise it will return
false.
• Member selection operator
- This is also called as dot operator (.).
- It is used to access the instance variable and methods of the class using
objects.
- For example: company. salary (); //reference to method salary
company. empID=101; //reference to variable empID

25
Java Programming(I Scheme 22412)

Math Functions:
• The java.lang.Math class contains methods for performing basic numeric
operations such as the logarithm, square root, and trigonometric functions.
• These function should be used as
Math.function_name()
• For example: double x=Math.sqrt(81);

Functions Meaning
min(a,b) Returns minimum of a and b.
max(a,b) Returns maximum of a and b
sqrt(x) Returns square root of x.
pow(x,y) Returns x raised to y (xy)
exp(x) Returns e raised to y (ey)
round(x) Returns the integer closest to the argument x.
abs(a) Returns the absolute value of a .
• Here, a and b may be int,long, float or double. x and y are double type parameters.

// Program on Math functions:


Import java.lang.Math.*;
class MathDemo
{
public static void main(String args[])
{
System.out.print("Square root of 81=”+Math.sqrt(81));
System.out.print("2 raised to 3=”+Math.pow(2,3));
System.out.print("minimum of 10 and 20=”+Math.min(10,20));
}
}

Operator Precedence and associativity:


Precedence order.
When two operators share an operand the operator with the higher precedence goes first.
For example, 10 + 2 * 3 is treated as 10 + (2 * 3). Since multiplication has a higher
precedence than addition.

Associativity.
• When an expression has two operators with the same precedence, the expression is
evaluated according to its associativity.
• For example
1) x = y = z = 10 is treated as x = (y = (z = 10)), leaving all three variables with the
value 10, since the = operator has right-to-left associativity .
2) 70 / 2 / 3 is treated as (70 / 2) / 3 since the / operator has left-to-right associativity.

26
Java Programming(I Scheme 22412)

• Following table shows that arithmetic operators are having highest operator
precedence than relational operators.

1.4 Decision Making and looping

Decision Making and Branching


✓ A java program is a set of statements, which are normally executed sequentially in
the order in which they appear.
✓ We have number of situations, where we have to change the order of execution.
✓ Java supports different control flow and branching statements given below.
1. if statement
2. if-else statement
3. else-if ladder
4. switch-case statement
5. Conditional operator statement

Decision making with an ‘if’ statement


✓ The ‘if’ statement is one of the powerful decision-making statement used to control
the flow of execution.
✓ Syntax: if (condition)
{
Statement1 ;
Statement2 ;
}

Here, condition is a Boolean expression. If condition is true, then the statement is


executed. If condition is false, then the statement is bypassed.
✓ For Example:
if(number < 0)
System.out.println(“The number is negative”);

27
Java Programming(I Scheme 22412)

The ‘if-else’ statement


✓ The if-else statement defines both the actions which are to be taken on when
condition is true and when condition is false.
✓ It is an extension of general if statement.
✓ The general form of if-else statement is:
if(condition)
{
statements for condition is true;
}
else
{ statements for condition is false;
}
Statements after the blocks;

✓ If the condition given is true then the statements inside the if-block are executed
otherwise statement inside else-block are executed. That is, any one of the
statements is executed depending upon the status of the condition (i.e. true or
false). After all the statements written after the blocks are executed though the
condition is true or false.

Nested if-else structure


✓ ‘if-else’ structure can also be nested but in such cases ‘if’s must be matched with
respective else.
✓ The general form of nested if-else statement is:
if(condition1)
{ statement1;
if(condition2)
{ statement2;
}
else
{ Statement3;
}
}
else
{ Statement4;
}
Statements after the if-else;

✓ If the condition1 is true statement1 is executed else statement4 is executed.


✓ Means, any one of the stetement1 and statement4 is executed.
✓ Statement2 is executed only when both condition1 and condition2 are true.
✓ Statement3 is executed when condition1 is true and condition2 is false.

Program to find largest of three using nested if-else


class Largest
{
public static void main(String args[])
{
int x = 10, y = 15, z = 12;
if(x > y)
28
Java Programming(I Scheme 22412)

{
if(x > z)
System.out.print(x+" is largest");
else
System.out.print(z+" is largest");
}
else
{
if(y > z)
System.out.print(y+" is largest");
else
System.out.print(z+" is largest");
}
}
}

The else-if ladder


✓ The else-if ladder is way of putting the ‘if’s together when multi-path decisions are
involved.
✓ A multi-path decision is a chain of ‘if’s in which statements are associated with
each ‘else’ is an ‘if’. This construct is known as if-else ladder.
✓ The general form of if-else ladder is:
if(condition1)
statement1;
else if(condition2)
statement2;
else if(condition3)
statement3;
...
else
statement4;

The conditions are evaluated from top of the ladder to the bottom.

Program to find largest of three using else-if ladder

class Largest
{
public static void main(String args[])
{
int x = 10, y = 15, z = 12;
if(x > y && x > z)
System.out.println(x+" is largest");
else if((y > x && y > z) Output:
System.out.println(y+" is largest"); 15 is largest
else if(z > x && z > y)
System.out.println(z+" is largest");
else
System.out.println(“All numbers are equal");
}
29
Java Programming(I Scheme 22412)

The switch-case statement


✓ General form of switch-case statement is shown below:
switch(expression)
{
case value-1: statements-1;
break;
case value-2: statements-2;
break;

default : default block;


}
statement-x;

✓ Switch is the multi-way selection statement. It tests the value of the variable (or
expression) against the list of case values and when match is found, a block of
statements associated with that case are executed.
✓ It is applicable when it is impossible to write the ‘if’ statement many times in the
programs. It is used to create the menu driven program to select from the multiple
choices.
✓ The expression is either an integer or character variable or an expression which is
evaluated to an integer value.
✓ value-1, value-2… are constants, which are also known as case labels. A colon (:)
is given after each case label. When the switch is executed, the value of the
variable is successively compared with the values value-1, value-2….
✓ If the case is found whose value matches with the variable then the statements in
front of respective case are executed.
✓ The ‘break’ statement is written at the end of each case statement to signal the end
of particular case. It causes the exit from the switch statement. It also transfers the
program control out of the switch block to execute the statement-x.
✓ The ‘default’ is executed when there is no match found in the cases.

Program on switch-case
class SwitchCase
{
public static void main(String args[])
{
int ch=3;
switch(ch)
{ case 1:System.out.println("One");
Output:
break;
Three
case 2:System.out.println("Two");
break;
case 3:System.out.println("Three");
break;
case 4:System.out.println("Four");
30
Java Programming(I Scheme 22412)

break;
default:System.out.println("Invalid");
break;
}
}
}

Decision Making and Looping


• A Loop is the cycle of execution.
• Java supports the looping feature which enables us to develop concise programs
containing repetitive process without using unconditional branching statements.
• In the process of looping, a sequence of statement is executed until some condition
of termination of the loop is satisfied.
• Java is having three different loop statements.
1) while loop 2) do-while loop 3) for loop

The while loop


• The syntax of the while loop is given below:
initialization;
while (condition)
{
//body of the loop;
}

• The ‘while’ is an entry controlled loop structure. That is, before the program control
enters the loop, the loop condition is checked. It can also be called as pre-test loop
• If the condition given is evaluated to true then the body of the loop is executed until
the condition satisfies to true. When the condition becomes false, the loop is
terminated. Then statements written after the loop are executed. If condition
doesn’t become true any time then loop will go into infinite iteration execution.

//Program on While loop


class WhileDemo
{
public static void main(String args[])
{
int i = 0;
while(i<10)
{
System.out.println(“I Love Java”);
i++;
}
}
}
It will print “I Love Java” for 10 times.

31
Java Programming(I Scheme 22412)

The do-while loop


• It is post-test loop. That is, the loop is executed first and then the loop condition is
checked. The condition is written at the end of the loop.
• This is also called as exit-controlled loop. That is, exit of the program control from
loop is decided by loop condition.
• Syntax & flowchart of do-while loop statement is,
do
{
//body of the loop;
}
while(condition);

• On reaching the do statement, the body of the loop is executed first.


• Then the loop condition written in ‘while’ is checked. If it is true then program
control will proceed to execute next iteration of the loop else next statements are
executed. When the condition becomes false, the loop gets terminated.

// Program on do-while loop:


class DoWhile
{
public static void main(String args[])
{
int a = 0;
do
{
System.out.println(“I Love Java”);
a++;
}
while (a<10);
}
}
It will print “I Love Java” for 10 times.

The for loop


• The ‘for’ loop is another entry-controlled loop, that provides a more concise loop
control structure. That is, initialization, condition and increment/decrement can be
done in the single loop statement .
• The syntax & flowchart of for loop:

for(initialization; condition; increment/decrement)


{
//Body of the loop;
}

• This loop control structure works as below.


1. Initialization of the control variable is done first, using assignment statements
e.g.:- int i = 0
32
Java Programming(I Scheme 22412)

2. Value of the control variable is tested using the test condition. The test condition is
a relational expression, e.g.: i<10, which determine when the loop will exit. If the
condition is true the body of the loop is executed else loop is terminated
3. After the body of the loop is executed the control transfers back to for statement
and the control variable is incremented using statement such as i= i+1

// Program on for loop


class ForDemo
{
public static void main(String a[])
{
System.out.println("Printing the numbers from 1 to 10");
for(int i = 1; i <=10; i++)
System.out.println(i);
}
}
The above program is to print numbers from 1 to 10.

Enhanced for loop or “for-each” style


• It is also known as “for-each” loop.
• A for-each style loop is designed to cycle through a collection of objects, such as
an array, in strictly sequential fashion, from start to finish.
• The general form of the for-each version of the for is shown here:
for(type itr-var : collection)
statement-block
• Here, type specifies the type and itr-var specifies the name of an iteration variable
that will receive the elements from a collection, one at a time, from beginning to
end.
• With each iteration of the loop, the next element in the collection is retrieved and
stored in itr-var. The loop repeats until all elements in the collection have been
obtained. type must be the same as (or compatible with) the elements stored in the
collection
• The following fragment uses a traditional for loop to compute the sum of the values
in an array:
int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int sum = 0;
for(int i=0; i < 10; i++)
sum += nums[i];
• For example, here is the preceding fragment rewritten using a for-each version of
the for:
int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int sum = 0;
for(int x: nums)
sum += x;

33
Java Programming(I Scheme 22412)

Jump statements
Sometimes while executing the loop it is necessary to skip some part of the loop or exit
from the loop. For this jump statements are used. There are two jump statements
related to loop structures.
1. break statement.
2. continue statement.
1) Break statement:
✓ The break statement has two uses:
1. It terminates a statement sequence in a switch statement.
2. It can be used to exit a loop
✓ When a break statement is encountered inside a loop, the loop is terminated and
program control resumes at the next statement following the loop.
✓ Generally, the ‘break’ statement is associated with an ‘if’ statement. That is, when
the condition is satisfied, the jump will occur.
✓ When used inside a set of nested loops, the break statement will only break out of
the innermost loop.
✓ For example: Using break to exit a loop.
class BreakLoop Output:
{ i: 0
public static void main(String args[]) i: 1
{ i: 2
for(int i=0; i<10; i++)
{
if(i == 3)
break; // terminate loop if i is 3
System.out.println ("i: " + i);
}
}
}

2) Continue Statement:
✓ When we want to continue the next iteration of the loop by skipping some part
inside it, the ‘continue’ statement can be used.
✓ It is also associated with the condition.
✓ General form of the ‘continue’ is:
continue;
✓ When the ‘continue’ is encountered in the loop the program control skips all the
further statements after that in the loop and proceed to execute the next iteration.

✓ For example: Demonstration of the 'continue' statement.


class ContinueDemo
{
public static void main(String args[])
{
for(int i=0; i<10; i++)
34
Java Programming(I Scheme 22412)

{
Output:
if (i == 3) i: 0
continue; //skips further statements if i=3 i: 1
//& continues to next iteration i: 2
System.out.println (“i =”+ i); i: 4
} i: 5
i: 6
}
i: 7
} i: 8
i: 9

Java is strictly or truly object-oriented language due to the following


reasons.
1. Everything in Java is considered as the object including the source program
because it is written in a class itself.
2. The object model in Java is simple and easy to extend, while simple types, such as
integers, are kept as high-performance non objects.
3. Java implements all of the features of Object oriented programming including
inheritance, polymorphism, dynamic binding etc.
4. The library of Java is created in terms of package. It is a collection of similar
working classes. The methods are defined in the classes. In order to use these
methods we need to import the package in our program.
5. The Java class library (API) itself implemented inheritance of classes in order to re-
use the code.
6. Most of the methods and constructors of the Java classes are overloaded. That is
form of polymorphism.
7. Using interface, we can create the multiple inheritance by avoiding duplication of
data.
8. Java does not support the concept of global variables in any case. Thus data
encapsulation is strictly supported.

The Java programming language is popular on internet due to the


following reasons:
1. Java is used in distributed environments such as internet. Java could be easily
used into the web system.
2. Java is a platform independent language. It’s all applications can run as it on
various operating systems.
3. With the support of the web we can run Java programs someone else’s computer
across the internet.
4. Internet users can use Java to create applet programs and run them locally using
a Java enabled browser.
5. We can create the Servlets in Java. Servlets are small programs that execute on
the server side of a Web connection.
6. Servlets are secure, portable, and easy to use replacement for CGI.
7.

35
Java Programming(I Scheme 22412)

Comparison of Java and C++

Sr.
Java C++
No.
C++ is an extension of C with object
Java is a true and complete object
1 oriented behavior. C++ is not a complete
oriented language.
object oriented language as that of Java.
Java does not provide template
2 C++ offers Template classes.
classes.
C++ achieves multiple inheritance by
Java supports multiple inheritance
3 permitting classes to inherit from multiple
using interface.
classes.
4 Java does not support pointers. C++ supports pointers.
Java does not provide global
5 Global variables can be declared in C++.
variables.
In Java, destruction of objects is In C++, destruction of objects is performed
6
performed in finalize () method. by destructor function.
7 Java doesn’t provide header files. C++ has header files.
Java does not support operator
8 C++ support operator overloading.
overloading.
9 Java provides a true boolean type. C++ does not provide a boolean type.
The char type in Java is a 16-bit type The char type in C++ is an 8-bit type that
10
and uses the Unicode character set maps to the ASCII

Comparison of Java and C


Sr.
JAVA C
No.
1 JAVA is Object-Oriented C is Procedure-Oriented
2 Java is an Interpreted language. C is a compiled language.
3 JAVA uses the bottom-up approach. C uses the top-down approach
JAVA does not support pointers C requires explicit handling of
4
pointers.
5 JAVA supports Method Overloading C does not support overloading at all.
JAVA uses a garbage collector that In C, the memory is managed by the
6 deletes the objects that no longer have user.
any references to them.
JAVA uses the System.out.print & C uses the printf & scanf functions as
7
System.in.read functions. its standard input & output
8 JAVA supports Exception Handling. C does not support Exception
Handling.
9 Java does not support typedefs, defines, C supports typedefs, defines, or a
or a preprocessor. preprocessor.
10 JAVA does not support structures or C supports structures or unions
unions
11 Java provides a true boolean type. C does not support boolean type.

36
Java Programming(I Scheme 22412)

Find factorial of number using for loop


import java.util.*;
class Factorial
{
public static void main(String args[])
{
int fact = 1, num;
Scanner in = new Scanner (System. in);
System.out.println("Enter number : ");
num = in.nextInt();
for(int i = 1 ; i<=num ; i++)
{
fact = fact * i;
}
System.out.println ("Factorial: "+ fact);
}
}
To check given number is even or odd
import java.util.*;
class EvenOdd
{
public static void main(String args[])
{
int num;
Scanner in = new Scanner (System. in);
System.out.println("Enter number : ");
num = in.nextInt();

if(num%2==0)
System.out.println(num+” is even number”) ;
else
System.out.println(num+” is odd number”) ;
}
}
To print even numbers between 1 and 20
import java.util.*;
class Even
{
public static void main(String args[])
{
for(int i=1;i<=20;i++)
{
if(num%2==0)
System.out.println(num+” is even number”) ;
else
System.out.println(num+” is odd number”) ;
}
}
}

37
Java Programming(I Scheme 22412)

To check given number is prime or not


import java.util.*;
class Prime
{
public static void main(String args[])
{
int num,i;
Scanner sc=new Scanner(System.in);
System.out.println("Enter number=");
num=sc.nextInt();

for(i=2;i<num;i++)
{
if(num%i==0)
break;
}
if(i==num)
System.out.println("Prime number");
else
System.out.println("Prime number");

To print prime numbers between 1 and 20


class Prime20
{
public static void main(String args[])
{
int num,i;

for(num=2;num<=20;num++)
{
for(i=2;i<num;i++)
{
if(num%i==0)
break;
}
if(i==num)
System.out.println(num);
}

}
}

38
Java Programming(I Scheme 22412)

To print sum of digits


import java.util.*;
class SumOfDigit
{
public static void main(String args[])
{
int num,rem,sum=0;
Scanner sc=new Scanner(System.in);
System.out.println("Enter number=");
num=sc.nextInt();

while(num>0)
{
rem=num%10;
sum=sum+rem;
num=num/10;
}
System.out.println("Sum of digits="+sum);
}
}
To print number in reverse order
import java.util.*;
class Reverse
{
public static void main(String args[])
{
int num,rem,rev=0;
Scanner sc=new Scanner(System.in);
System.out.println("Enter number=");
num=sc.nextInt();

while(num>0)
{
rem=num%10;
rev=rem+rev*10
num=num/10;
}
System.out.println("Reverse num="+rev);
}
}
Num=123 num=12 num=1
rem 123%10=3 rem 12%10=2 rem 1%10=1
rev 3+0*10=3 rev 2+3*10=32 rev 1+32*10=321
num 123/10=12 num 12/10=1 num 1/10=0

39
Java Programming(I Scheme 22412)

To print fibonacci series


public class Fibonacci
{
public static void main(String args[])
{
int n1=1,n2=1,n3;

System.out.print(n1+"\t"+n2);
for(int i=1;i<=10;i++)
{
n3=n1+n2;
System.out.print("\t"+n3);
n1=n2;
n2=n3;
}
}
}

Questions on Chapter-1
1. Why Java is known as Platform-independent language?
2. Explain why Java is called as true object oriented language.
3. Why Java is popular on Internet?
4. Explain the various features of the java programming language.
5. What do you mean by BYTECODE? What is JVM?
6. What are the different data types in JAVA? Explain each of them with example.
7. Write a program to generate Fibonacci series.
8. Write a program to calculate factorial of a given number.
9. Write a program to print even numbers between 1 and 20.
10. Write a program to check given number is even or odd.
11. Write a program to check given number is prime or not.
12. Write a program to print sum of digits.(if num=123 then sum=6)
13. Write a program to print reverse of a number(if num=123 then reverse=321)
14. Explain Symbolic Constants in Java.
15. Explain typecasting with suitable example.

40

You might also like