0% found this document useful (0 votes)
28 views127 pages

Module 1 Introduction Part 1

Uploaded by

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

Module 1 Introduction Part 1

Uploaded by

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

Programming in JAVA

LECTURE 1
Dr Vijay K. Trivedi
Objectives

❏ To understand the basic concepts of Java and Java flow


control
❏ To create Java technology applications that leverage the
object-oriented features of the Java language, such as
encapsulation, inheritance, and polymorphism
❏ To Implement error-handling techniques using exception
handling and creating high- performing multi-threaded
applications
❏ To Implement input/output (I/O) functionality to read from
and write to data and text files and understand advanced
I/O streams
❏ To Perform multiple operations on database tables using
both JDBC and JPA technology and Java Collections
framework
Students who complete this course will be able to

❏ Analyze the Java flow control using essentials of Java


programming.
❏ Solve simple business problems using an object-oriented
approach
❏ Demonstrate synchronization among different processes
using a multithreading approach and exception handling
techniques
❏ Implement Java Input and Output streaming using Java
packages
❏ Develop and create real-time applications using JDBC and
JPA technology
Student Outcomes (SO):

❏ An ability to apply the knowledge of mathematics, science


and computing appropriate to the discipline
❏ An ability to analyse a problem, identify and define the
computing requirements appropriate to its solution.
❏ An ability to design, implement and evaluate a system /
computer‐based system, process, component or program to
meet desired needs.
Module 1

● Java Introduction
Java Hello World, Java JVM, JRE and JDK, Difference
between C & C++, Java Variables, Java Data Types, Java
Operators, Java Input and Output, Java Expressions &
Blocks, Java Comment
● Java Flow Control
Java if...else, Java switch Statement, Java for Loop,
Java for-each Loop, Java while Loop, Java break
Statement, Java continue Statement
Today’s Agenda

An Introduction to JAVA

• Necessity Of Programming

• What Is Java ?

• Important Features

• History Of Java

• Where Java stands today ?

• Java Ecosystem
Why Do We Need Programming ?

• To communicate with digital machines and make them work


accordingly

• Today in the programming world , we have more than 900


languages available.

• And every language is designed to fulfill a particular kind


of requirement
Brief History Of Prog. Lang

⚫ C language was primarily designed to develop “System


Softwares” like Operating Systems, Device Drivers etc .

⚫ To remove security problems with “C” language , C++


language was designed.

⚫ It is an Object Oriented Language which provides data security


and can be used to solve real world problems.

⚫ Many popular softwares like Adobe Acrobat , Winamp Media


Player,Internet Explorer,Mozilla Firefox etc were designed in
C++
Courtsey:http://www.stroustrup.com/applications.html
What is JAVA???...

⚫ JAVA is a Technology(not only a programming language) to


develop Object oriented and Platform Independent
applications.

⚫ Platform Independence

⚫ Technology
Platform Independence

⚫ PLATFORM
⚫ A Platform is an environment in which a program runs.
⚫ In simple terms it is combination of Operating system and Processor.

Platform Operating
System Processor

⚫ Example:- Windows+Intel(i5), Ubuntu+AMD


How many physical machines
Answer:
are there in the figure ? 12 Physical
Machines

Windows Windows(32
Mac Linux
(32 bit) bit)

Windows (64
Linux Mac Linux
bit)

Windows(3 Windows (64 Linux


Mac bit)
2 bit)
How many platforms
are there in the figure ?
Answer:
Only 4

Windows Windows(32
Mac Linux
(32 bit) bit)

Windows (64
Linux Mac Linux
bit)

Windows(3 Windows (64 Linux


Mac bit)
2 bit)
Important Features

⚫ Platform Independent

⚫ Automatic Memory Management

⚫ Secure

⚫ Robust

⚫ Simple

⚫ Multithreaded

⚫ Distributed
Important Features

⚫ Platform Independent
A platform is the environment in which an application
runs.

In other words it is the combination of an OS and a CPU.

For example:
Windows 8+Intel - Core i5 (is a diff. platform)
Linux + AMD -A6(is another diff platform)
Mac + Intel -Core i3(is yet another diff
platform)
Important Features

⚫ Now being platform independent means that an application


developed and compiled over one platform can be executed over
any other platform without any change in the code.

⚫ And , Java has this capability using the concept of “bytecode” and
“JVM”
Important Features

⚫ Whenever we compile a java program , the compiler never


generates machine code.

⚫ Rather it gnerates a machine independent code called the


“bytecode”.

⚫ This bytecode is not directly understandable by the platform(OS &


CPU).

⚫ So another special layer of software is required to convert these


bytecode instructions to machine dependent form
Important Features

⚫ This special layer is the JVM , that converts the bytecode to


underlying machine instruction set and runs it.
Important Features

class HelloWorld {
public static void main(String args[ ]) {
System.out.println(“Hello World!”);
}
Java Program
}

Compiler

Interpreter Interpreter Interpreter

Hello World!
Hello Hello World!
World!

Win32 Solaris MacOS 18


Important Features

⚫ Thus any such platform for which a JVM is available can be used
to execute a Java application irrespective of where it has been
compiled.

⚫ This is how java makes itself “Platform Independent” and it also


truly justifies java’s slogan of “WORA”(Write Once Run
Anywhere)
Important Features

⚫ Automatic Memory Management

In languages like C and C++ any dynamic memory which the


programmer allocates using malloc( ) or new has to be
deallocated by himself using free( ) or delete

But Java uses runtime automatic garbage collection


feature where the JVM itself deallocates any dynamic
memory which our program allocated.
Important Features

⚫ Secure

Java does not use pointers explicitly.

Moreover all the programs in java are run under an area known as
the sand box.

This sandbox uses a bytecode verification process to


ensure that code loaded does not violate Java security
constraints.
Important Features

⚫ Robust

Java has very strict rules which every program must


compulsorily follow and if these rules are
violated then JVM kills/terminates the code by
generating “Exception”
Important Features

To understand java’s robustness , guess the output of the


following C/C++ code:

int arr[5];
int i;
for(i=0;i<=9;i++)
{
arr[i]=i+1; // Unpredictable, after i is 5
}
Important Features

⚫ The previous code might show uncertain behaviour in C/C++


i.e. if memory is available after arr[4] , then the code will run
, otherwise it will generate error at runtime.

⚫ On the other hand if in java this code is executed, the JVM


will kill the application as soon as it finds the statement
arr[5]=. . .

⚫ Reason is that in java we are not allowed to access any


array beyond it’s upper/lower index
Important Features

⚫ Simple

Java borrows most of it’s syntax from C/C++ languages.


Moreover it has inherited best points from these
languages and dropped others.

Like it has removed pointers, multiple inheritance etc as


developers of java language found these features to
be security threat and confusing.

Thus if we have basic understanding


of C/C++ languages it is very easy to learn Java
Important Features

⚫ Object Oriented

Java supports all important concepts of OOPs, like

Encapsulation
Inheritance
Polymorphism
Abstraction
Important Features

⚫ Multithreaded

Multithreading means concurrent execution.

In simple terms it means that we can execute more than one


part of the same program parallelly/simultaneously.
QUIZ 6

⚫ Can we say that if we are surfing the internet using our


browser and at the same time we are listening to song in
winamp, the it is multithreading ?

❑ True

❑ False

It is mutlitasking not multithreading


Important Features

⚫ To understand this feature consider the code given below:

main()
{
clrscr();
factorial(5);
prime(8);
evenodd(4);
}
.
.
.
Important Features

⚫ In the previous sample code all 4 functions


clrscr(),factorial(),prime() and evenodd() are independent
of each other but still they will run sequentially i.e. one after
the other.

⚫ This can be improved in java by using multithreading feature


so that each one of these functions can run together.

⚫ Benefits: Reduced execution time , full utilization of CPU


Important Features

⚫ Some practical examples where multithreading is used are:

⚫ We can open multiple tabs in the same browser window

⚫ When we use a media player to listen to a song , then there


are multiple activities which take place parallely like moving
of a slider, elapsed time being shown, volume adjustment ,
ability to add or remove songs from the playlist , playing of
the song etc
Important Features

⚫ Distributed

Distributed programming a program uses more than


one computer.

That is, different parts of the same program run on


different computers and communicate over a network.
Important Features

⚫ In Java, this is made possible by a technique called RMI(Remote


Method Invocation)

⚫ RMI allows a method that is running on one computer to call a


method in an object that is on another computer.
Important Features

⚫ Benefits: Programmers working on same project may not be


required to be physically present at the same location
History

⚫ Developed By: James Gosling

⚫ Company Name: Sun Microsystems,


now known as Oracle Sun.

⚫ Original Name: Oak.

James Gosling
⚫ First release: 23 rd
January 1996 and called
JDK(Java Development kit) 1.0
Editions/Flavours Of Java

• When Java was originally released in 1996, it was just Java


and no such thing as “editions” was there.

• But as use of Java increased , then in 1999 , SUN


categorized it into 3 editions called J2SE,J2EE and J2ME .

• Later on in 2006 they changed the naming and called them as


JSE,JEE and JME.

• These editions were named based on the kind of application


which can be developed by learning that edition.
JSE(Java Standard Edition)

• This is the most basic version of Java and it provides us core


concepts of Java language like the data types , operators,
arrays, methods , OOP , GUI (Graphical User Interface )
etc.

• Since it teaches us core concepts of Java that is why many


people call it CORE JAVA , although SUN never gave this
name.

• Used for developing desktop applications like calculators,


media player, chat applications etc
JEE(Java Enterprise Edition)

• The Java EE which stands for Java Enterprise Edition is


built on top of the Java SE platform and is a collection of
libraries used for building "enterprise applications" (usually
web applications).

• In simple terms we can say JEE is used for developing


applications which run on servers.

• Some popular applications developed using JEE are


amazon.in,alibaba.com,irctc.co.in,ideacellular.com,airtel.i
n etc
JME(Java Micro Edition)

• Java ME is the slimmer version of Java targeted towards


small devices such as mobile phones.

• Generally people tend to think of the micro edition as the


mobile edition, in reality, the micro edition is used not just
for mobile phones, but for all kinds of devices, such as
television sets, printers, smartcards and more.

• But as smartphone technology arrived the use of JME has


reduced as Android has superseded it.
Java Editions
JDK v/s JRE v/s JVM

• Understanding difference between JDK,JRE and JVM is


very very important in java for interviews

• These terms stand for:

• JDK: Java Development kit

• JRE: Java Runtime Environment

• JVM: Java Virtual Machine


What Is JVM ?

• JVM is an abstract machine that can execute precompiled


Java programs.

• In simple terms it is the code execution component of java

• It is designed for each platform(OS+CPU) supported by


Java and this means that every platform will have a
different version of JVM
QUIZ

• Why JVM is called a virtual machine ?

JVM is called virtual machine because it is a software layer but it


behaves as if it is a complete machine(platform).

That is all the tasks which are done by a machine while running a
program in other languages like C , are actually done by JVM in Java
.

For example:
Starting The Execution By Calling Main( )
Allocating Memory For The Program
Cleaning Up Memory cleanup etc
What JVM Contains?

• JVM contains following important components

• Interpreter

• Garbage Collector
QUIZ

• Are java compiler and interpreter same?

No , not at all.

The Java compiler converts source code to bytecode and is not a


part of JVM , rather it comes with JDK.

The interpreter lives inside the JVM and converts bytecode to


Machine understandable form
What Is JRE ?

• JRE is an acronym for Java Runtime Environment

• It contains a JVM along with java classes/packages and set


of runtime libraries.

• So the JVM , while running a java program uses the classes


and other libraries supplied by JRE.

• If we do not want to write a java program , and we just want


to run it then we only need a JRE
What Is JDK ?

• JDK stands for Java Development Kit and is a bundle of


software that we can use to develop Java based
applications.

• It includes the JRE, set of library classes, Java


compiler,jar and additional tools needed while developing a
Java application.
JDK,JRE and JVM
QUIZ

• Can I compile a java application if I have a JRE ?

• Yes

• No
Correct Answer: No

• JRE can only be used to run a Java application . It


doesn’t contain the javac tool which is used for
compilation
QUIZ

• Which component is used to compile, debug and execute


java program?
A) JVM
B) JDK
C) JIT
D) JRE

Correct Answer: B
QUIZ

• Which component is used to convert bytecode to machine


specific code ?
A) JVM
B) JDK
C) JIT
D) JRE

Correct Answer: A
QUIZ

• Which component is used to provide a platform to run a java


program ?
A) JVM
B) JDK
C) JIT
D) JRE

Correct Answer: D
Today’s Agenda

Moving Ahead with JAVA

• Different Ways Of Writing A Java Code

• Writng First Java Code Using Notepad

• Different Elements In The Code

• Explanation Of Each Element


Developing Java Programs

Java Program Development

Using Notepad Using an IDE like Netbeans /


Eclipse etc
Typing the code in This approach should be used
notepad and running it after we have understood the
through command prompt. basic working of java .
This approach is good for Because as an IDE hides all
beginners for learning each the basic steps which are very
step thoroughly important to understand
Developing Java Programs
Using Notepad

• Developing and running a program requires three main


steps:

• Writing the source code

• Compiling the code


(Conversion from source code to bytecode)

• Executing the code


(Interpretation of the bytecode)
Step 1-Writing the Source Code

• Select notepad.exe from the list shown in pop up menu of


run command.

• Right click and choose “run as administrator” option.

• Now type the code given in next slide


Step 1-Writing the Source Code

class Test
{
public static void main(String [ ]args)
{
System.out.println(“Hello User”);
}
}
Understanding The Program

First of all we must remember that java is a highly case sensitive


language.

It means that we have to be very careful about uppercase and


lowercase letters while typing the code.

For example, in the previous code three letters are compulsorily


in uppercase and they are
“T” of Test ,
“S” of String and
“S” of System.

This is because in java class names begin with upper case


Understanding The Program

The first statement of our code is:

class Test

Since java is an Object Oriented Language and it strictly supports


Encapsulation so every java program must always contain atleast
one class and whatever we write must appear within the
opening and closing braces of the class
Understanding The Program

The second statement is:

public static void main(String [ ] args)

In java also(like C/C++) the entry point of execution of our program is the
method main( ) which is called by the JVM.

The words shown in blue are keywords and each has a different
meaning and purpose for the method main( ).

Lets understand each of them in detail


Why main( ) is public ?

⚫ “public” is an access modifier and in Object Oriented


Programming any method or variable which is declared public
can be accessible from outside of that class.

⚫ Since main( ) method is public in Java,so, JVM can easily


access and execute it.
Why main( ) is static ?

⚫ Every class can have two kinds of methods , nonstatic and


static.

⚫ A method which is nonstatic can only be called using object of


that class , while a static method can be called without any
object , simply using class name.

⚫ When the JVM makes a call to the main( ) method there is no


object existing for that , therefore it has to have static method to
allow invocation from outside the class.
Why main( ) has
return type void ?

⚫ The keyword void is called return type which indicates that no


value will be returned by the method to it’s caller.

⚫ Since main() method in Java is not supposed to return any


value to the JVM, its made void which simply means main() is
not returning anything.
Can we change/remove
the keywords used with main () ?

⚫ No , not at all.

⚫ This is because main( ) is called by JVM and to allow JVM to


successfully call main( ) these keywords are important.

⚫ If we forget to write these keywords then although the code will


compile but will fail to run.

⚫ All we can do is change the order of public and static but we


can’t drop them
What is String [ ] args ?

⚫ String is a predefined class in Java

⚫ So the statement String [ ] args is declaring args to be an array


of Strings.

⚫ It is called command line argument and we will discuss it later.

⚫ For now, just remember that the statement String[ ] args has to
be present with main( ) otherwise code will not run
Can we change/drop
String [ ] args ?

⚫ No , just like keywords used with main() are compulsory ,


similarly String [ ] args is also compulsory.

⚫ All we can do is change the name from args to something else.

⚫ Also we can interchange the array name and [ ] .

⚫ For example: String args[ ], String [ ] args, String [ ]str ,


String str[ ] all are valid
Understanding
System.out.println( )

⚫ Now let’s understand code in the body of the


main( ) method, which will print a message on the console.
Syntax:
System.out.println(“ message ”);

⚫ System is a predefined class .


⚫ out is an object reference (not object).
⚫ println( ) is a method.
⚫ Together all three are used for displaying text on console.
⚫ We will discuss this part in detail once we have covered basics of
Java
Data Types

⚫ Generally, data types are used to create variables where


variables will hold values, as defined in the range of values of
a data type.

⚫ Java supports two categories of data types:

⚪ Primitive data types and

⚪ Non Primitive Data Types


Data Type Categories
Non Primitive Data Types

• Non primitive data types are also called as reference data


types

• A Non Primitive Data Type is used to refer to an object.

• In Java , variables of type class , arrays , enums and


interface are represented as objects.

• We will discuss this in later chapters like Arrays and Classes


and Objects
Primitive Data Types

⚫ There are totally eight primitive data types in Java. They can
be categorized as given below:
⚫ Integer types (Does not allow decimal places)
⚪ byte
⚪ short
⚪ int
⚪ long
⚫ Rational Numbers(Numbers with decimal places)
⚪ float
⚪ double
⚫ Characters
⚪ char
⚫ Conditional
⚪ boolean
Primitive Data Types

• Integer Types
Type Size Range
(In Bytes)
byte 1 -128 to 127

short 2 -32768 to 32767

int 4 -2147483648 to 2147483648

long 8 -9223,372,036,854,775,808
to
9223,372,036,854,775,807
Primitive Data Types

• Rational Numbers
Type Size Range
(In Bytes)
float 4 -3.4 * 1038 to 3.4 * 1038
(6 significant decimal digits)
double 8 -1.7*10308 to 1.7*10308
(15 significant decimal digits)
Primitive Data Types

• Characters
Type Size Range
char 2 0 to 65535
Primitive Data Types

Why Java uses 2 bytes for characters ?

⚫ In Java almost 61 international languages are supported .

⚫ Now, the characters and symbols of these languages cannot be accommodated in


1 byte space in memory ,so Java takes 2 byte for characters.

⚫ Java supports UNICODE but C language supports ASCII code. In ASCII code
we can represent characters of English language, so for storing all English latter
and symbols 1 byte is sufficient.
Primitive Data Types

⚫ But UNICODE character set is superset of ASCII in which all the


characters which are available in 61 international languages are
supported and it contains 65536 characters ranging from 0 to 65535
Primitive Data Types

• Conditional
Type Size Range

boolean JVM true or false


Dependent
Type Conversion

What is type conversion ?

Whenever the compiler encounters a statement where the value


on right side of assignment is different than the variable on left
, then the compiler tries to convert R.H.S to L.H.S and this
automatic conversion done by compiler is called as Type
Conversion.
Type Conversion

For example:
Consider the following statement:
x = y;
In this case two things might happen:-

1 . If data type of both variables are same then value of y


will be assigned to the variable x.

2. But if data type of both variables are different then the value
of y needs to be converted as per the data type of variable x
and this is called “Type Conversion”
Forms Of Type Conversion

In Java ,type conversion is of two types

Type Conversion

Implicit Conversion Explicit Conversion


( automatically done ( specially done by
by compiler) programmer , also
called Type Casting)
Rules For Implicit Conversion

⚫ For implicit conversion there are 2 conditions which must


be true :

⚪ The values must be compatible/convertible.


AND
⚪ The value on RHS of assignment must be smaller than variable
on LHS

If both these rules are followed then Java will implicitly


convert the value otherwise conversion has to be done by
the programmer

Let us understand them in depth


Rule 1 : Convertible

⚫ Convertible means it must be possible for Java to convert a value from one
form to another.

⚫ For example , it is possible for Java to convert a character to an integer using


it’s UNICODE/ASCII value .

⚫ So the following will compile:

⚪ int x=‘A’;

⚫ But it is not possible for java to convert the boolean value “true” to
integer as the values “true” and “false” have no other representation.

⚫ So the following statement will not compile:

⚪ int x=true;
Rule 2 : Smaller

⚫ Smaller means the range of a variable’s data type must be a


smaller than other variable’s range. NOT THE SIZE

⚫ For example , a short data type variable has a range of


-32768 to 32767 which is smaller( proper subset) of the range
of an int variable whose range is -2147483648 to
2147483647, so “short” is considered to be smaller than an
“int”.

⚫ Another example, an int is of 4 bytes and has a range of


-2147483648 to 2147483647 while a float is also of 4 bytes
but has a range of -3.4*1038 to 3.4 *1038 which is greater than
the range of int , so int is smaller than float.
QUIZ

• Is a long data type smaller than float ?

• Yes

• No

• Because the range of long is smaller than range of a float.


Examples

1. byte a=10;
int b;
b=a;
because [range of int > byte]

2. int a=10;
byte b;
b=a;
because [range of byte<int] ------------lossy conversion
b=(byte)a; you have to do explicit conversion
Examples

3. short a=10;
int b;
b=a;
because range of [short<int]

4. int a =10;
short b;
b=a;
because range of [int>short]
b=(short)a;
(you have to do explicit conversion)
Examples

5. int a=10;
long b;
b=a;
because range wise [long >int] so, its correct.
6. long a=10;
int b;
b=a;
because long value can’t assign to int , it’s an error
b=(int)a;
you have to do explicit conversion.
QUIZ

Which of these is necessary condition for automatic type


conversion in Java?

A. The destination type is smaller than source type.

B. The destination type is larger than source type.

C. The destination type can be larger or smaller than source


type.

D. None of the mentioned.

Answer:-B
QUIZ

If an expression contains double, int, float, long, then whole


expression will promoted into which of these data types ?

A. long

B. int

C. double

D. float

Answer:-C
Operators

Pre/
Arithmetic Relational ShortHand Logical Misc
Post

+ > && ++ instanceof


+=
< || --
-
-=
>= !
* *=
<=
Assignment
/ /=
==
%= =
% !=
Few Important Points

⚫ The division operator in Java , just like C language uses two


kinds of division :

⚪ Integer Division : if both operands(Numerator and Denominator)


are integers then result will also be an integer. So 10/4 is 2 not 2.5

⚪ Floating Division: if either operands (Numerator or Denominator


or both) are float or double then result will also be float or double.
So 10/4.0 is 2.5
Few Important Points

⚫ The modulo division operator( % ) in Java , unlike C , works


with float and double data type also.

⚫ So 10%5 will produce 0 as the remainder

⚫ So 10.5 %5.0 will produce 0.5 as the remainder


Displaying Values of
Variables
class Test
{
public static void main(String args[])
{
int a=10;
double b=10.5;
boolean c=true;
System.out.println(a);
System.out.println(b);
System.out.println(c);
}
}
Hence, the same println() used for all data types i.e. println() is an
Displaying value with message

class Test
{
public static void main(String args[ ])
{
String variable
int a=10;
System.out.println(“Value of a is”+a);
}
} Concatenates string
and variables
Polymorphic Behaviour of “+”

⚫ Rule : anything concatenated with a String becomes String


otherwise normal addition will be done
⚫ Some more examples :-
“10” + “5” 105

105
“10” + 5
105
10 + “5”
.610
.5 + .1+“10”
10.5.1
“10” + .5+.1
Concept of default values

⚫ Before we can understand what is the default value of a variable,


we must first understand how many types of variables does Java
supports.

⚫ In Java , we have 3 kinds of variables:


⚪ Local variables
⚪ Class Level variables(also called as Instance members)
⚪ Static variables( we will discuss them with the chapter “Static”)
Concept of default values

⚫ Local variables
Variables declared in a method are called local variables.
These variables cannot be left unassigned else compiler generates
error.
class Test
{
public static void main(String args[])
{
int a;
System.out.println(“Value of a is”+a); Error
}
}
Concept of default values

⚫ Class level Variables :-


Variables which are declared in a class but not inside a particular method.
If these variables are left unassigned then they are assigned with default value 0
or false, depending on their data type.
class Student
{
int roll;
.
.
public void show( )
{
System.out.println(“Roll is"+roll);
}
.
.
.
}
Default Values Chart

Data Type Default Value


boolean false
char \u0000 or simply ‘\0’
int,short,byte / long 0 / 0L
float /double 0.0f / 0.0d
any reference type null

Remember that these values are for class level variables i.e. instance members not
for local variables. Local variables in java do not have any value not even “garbage
value”!
Try this

⚫ Write a program to calculate area and


circumference of a circle. Assume radius to
be an integer and assign it any value of
your choice.
Solution

class Circle
{
public static void main(String [ ] args)
{
int r=10;
double area,circ;
area=3.14*r*r;
circ=2*3.14*r;
System.out.println("Area is "+area);
System.out.println("Circumference is "+circ);
}
}
Using “Math” class
Java has a predefined class called “Math”

The class is available in the package java.lang and contains


methods for performing basic numeric operations like
exponential, square root , trigonometric functions etc

Within the Math class there is a static data member called


PI which returns the pi value of 3.141592653589793
Using “Math” class
Since PI is static , we can access it without creating any object
of Math class.

The syntax for accessing PI is : Math.PI


Using “Math” class
class Example
{
public static void main(String[] args)
{
System.out.println(“Value of PI is "+Math.PI);
}
}
Output:
Using “Math.pow( )”
Math class also contains a static method called pow( )
which returns the value of the first argument raised to the
power of the second argument.

Syntax of calling the method pow( ) is : Math.pow(a,b)

For example:
System.out.println(“Result is:”+Math.pow(2,3));
Output:
Result is 8.0
Improvised version
Using Math class
class Circle
{
public static void main(String [ ] args)
{
int r=10;
double area,circ;
area=Math.PI*Math.pow(r,2);
circ=2*Math.PI*r;
System.out.println("Area is "+area);
System.out.println("Circumference is "+circ);
}
}
⚫ Various Ways Of Accepting Input

⚫ Accepting Inputs through Command Line Arguments

⚫ Wrapper Classes
Accepting Input

⚫ In Java there are 3 ways to accept input from user :-

Through Command Line Arguments

Using Scanner classes

Using GUI Components

* This lecture we will cover command line arguments and the other
two methods will be covered in future lectures .
Using Command Line
Arguments

• Using command line arguments we can accept input when we are


about to execute the program .

• This is where the arguments of method main() come in action.

• Let us take an example to understand this…


Case I

class Test
{
public static void main(String [ ] args)
{
System.out.println(“Hello ”+args[0]);
}
}
…bin> java Test Sachin
Case II

class Test
{
public static void main(String [ ] args)
{
System.out.println(“Hello ”+args[0]);
System.out.println(“Hello ”+args[1]);
}
}
…bin> java Test Sachin Amit
Case III

class Test
{
public static void main(String [ ] args)
{
System.out.println(“Hello ”+args[0]);
System.out.println(“Hello ”+args[1]);
}
}
….bin> java Test Sachin
Case IV

class Test
{
public static void main(String [ ] args)
{
System.out.println(“Hello ”+args[0]);
System.out.println(“Hello ”+args[1]);
System.out.println(“Bye!”);
}
}
….bin> java Test Sachin Amit Sumit
Case V

class Test
{
public static void main(String [ ] args)
{
System.out.println(“Hello ”+args[0]);
System.out.println(“Bye!”);
}
}
….bin> java Test “Sachin Amit”
Case VI
(Passing Integers)
class AddNos
{
public static void main(String [ ] args)
{
System.out.println("First number is "+args[0]);
System.out.println("Second number is "+args[1]);
System.out.println("Their sum is "+args[0]+args[1]);
}
}
….bin> java AddNos 10 20
Why was the output 1020 ?

⚫ Because anything which we pass from “Command prompt” is by


default treated as a String by Java.

⚫ Now since Java is considering the values 10 and 20 as “10” and


“20” , so the operator + concatenated them instead of adding them
mathematically.

⚫ To solve this problem we have to convert the values “10” and “20”
from String to int and this is done using special classes in java
called “Wrapper Classes”
Wrapper Classes

⚫ In java , corresponding to 8 primitive data types we have 8


predefined classes also , called “Wrapper Classes”.

⚫ These classes are available in the package java.lang and have their
names similar to the name of data type.

⚫ For ex: Integer,Character,Float,Boolean etc

⚫ Notice that the first letter in wrapper class name is in uppercase


while in case of data type name it is in lowercase.

⚫ For ex: byte and Byte, long and Long and so on.
Uses Of Wrapper Classes

⚫ Wrapper classes are mainly used for two purposes:

⚪ To represent primitive data types as objects.

⚪ To convert String form of a primitive value to it’s original


form, for ex: “10” to 10
Representing primitives
as objects

⚫ Consider the following statement:

int a=10; // variable a

⚫ Here a is a variable initialized to 10

⚫ But if we want we can convert it into an object by using the


Wrapper Class Integer, as shown below:

Integer obj=a; // variable a converted to object


Converting String
To Primitive

⚫ Another importance of wrapper classes is that they contain special


methods which perform conversion from String to primitive data
type.

⚫ These methods have their name as parseXXX where XXX is the


name of primitive type.

⚫ Also they are static in nature, so they can be directly called by their
class name.

⚫ For Example :- Integer.parseInt(“……”);


String type value
List Of Wrapper Classes

Data Type Wrapper Class Method


int Integer parseInt()

short Short parseShort()

byte Byte parseByte()

long Long parseLong()

float Float parseFloat()

double Double parseDouble()

char Character No parse method


available
boolean Boolean parseBoolean()
Addition Of Number
Using Wrapper Classes

class AddNos
{
public satic void main(String args[])
{
int a,b,c;
a=Integer.parseInt(args[0]);
b=Integer.parseInt(args[1]);
c=a+b;
Syetem.out.println(“First number is ”+a);
Syetem.out.println(“Second number is ”+b);
Syetem.out.println(“Their sum is ”+c);
}
}
Guess the output ?
class AddNos
{
public satic void main(String args[])
{
int a,b,c;
a=Integer.parseInt(args[0]);
b=Integer.parseInt(args[1]);
c=a+b;
Syetem.out.println(“First number is ”+a);
Syetem.out.println(“Second number is ”+b);
Syetem.out.println(“Their sum is ”+c);
}
}
Running:
bin> java AddNos 10 Bhopal
Output
Why did Exception occur ?

• Because the method parseInt( ) can only work with Strings


containing digits.

• If any String contains non integer values then the method


parseInt( ) will throw Exception.

• Even if we pass 20.5 , then also it will throw


“NumberFormatException”
Why did Exception occur ?
How to accept decimal values?

• So if we want to accept decimal values , then we must use the


method parseFloat( ) or parseDouble( ).

• They accept decimal/integer both kinds of values and throw


Exception only if the given values is non-numeric like “bhopal”,
“10a” etc.

You might also like