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

Basics of Java

OBJECT ORIENTED PROGRAMMING USING JAVA

LECTURER: Dr. KRUNAL PATEL


MBIT ENGGINEERING COLLEGE
NEW VALLABH VIDYANAGAR
What is PC?

Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 2


What is PC?

Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 3


What is PC?

Heart of the
processor :

Which does
all thinking
for the
computer

Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 4


What is PC?

How does it
understand
this media ??

Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 5


What is PC?

It only knows
the 0’s and 1’s

Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 6


What is PC?

Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 7


What is PC?

Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 8


What is PC?

Most
elementary
form of
language for
software
development

Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 9


What is PC?

Converted into machine code


and feed that into processor

Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 10


What is PC?

Convert C code into assembly code Convert assembly code to machine code

Now a days compiler comes bundled with assembler


Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 11
What is Platform?

Operating
+ Processor = Platform
System

Combination of OS and Processor is called a platform

Most common Platforms are :


Window + intel, Power Pc + MAC OS –X, AMD + linux

Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 12


What is Java?
• Java is a programming language and a platform.

• Java is a high level, robust, secured and object-oriented programming language.

• Platform: Any hardware or software environment in which a program runs, is


known as a platform. Since Java has its own runtime environment (JRE) and API, it
is called platform.

Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 13


What is Platform?

Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 14


What is Java?

Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 15


What is Java?

Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 16


What is Java?

Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 17


What is Java?

Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 18


Where it is used?
• Desktop Applications such as acrobat reader, media player, antivirus etc.
• Web Applications such as irctc.co.in etc.
• Enterprise Applications such as banking applications.
• Mobile
• Embedded System
• Smart Card
• Robotics
• Games etc.

Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 19


Types of Java Applications
There are mainly 4 type of applications that can be created using java
programming:
1) Standalone Application
It is also known as desktop application or window-based application. An
application that we need to install on every machine such as media player,
antivirus etc. AWT and Swing are used in java for creating standalone
applications.

2) Web Application
An application that runs on the server side and creates dynamic page, is called
web application. Currently, servlet, jsp, struts, jsf etc. technologies are used for
creating web applications in java.

Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 20


Types of Java Applications
3) Enterprise Application
An application that is distributed in nature, such as banking applications etc. It
has the advantage of high level security, load balancing and clustering. In java,
EJB(Enterprise Java Beans) is used for creating enterprise applications.

4) Mobile Application
An application that is created for mobile devices. Currently Android and Java ME
are used for creating mobile applications.

Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 21


James Gosling

• James Gosling is generally credited as


the inventor of the Java programming
language
• He was the first designer of Java and
implemented its original compiler and
virtual machine
• He is also known as the Father of Java
• He was the Chief Technical Officer of Sun
Microsystems

22
History of Java
• Java history is interesting to know.
• The history of java starts from Green Team. Java team members (also known
as Green Team), initiated a revolutionary task to develop a language for digital
devices such as set-top boxes, televisions etc.
• For the green team members, it was an advance concept at that time. But, it was
suited for internet programming. Later, Java technology as incorporated by
Netscape.
• Currently, Java is used in internet programming, mobile devices, games, e-
business solutions etc. There are given the major points that describes the history
of java.

Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 23


History of Java
• James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language
project in June 1991. The small team of sun engineers called Green Team.

• Originally designed for small, embedded systems in electronic appliances like set-
top boxes.

• Firstly, it was called "Greentalk" by James Gosling and file extension was .gt.

• After that, it was called Oak and was developed as a part of the Green project.

Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 24


History of Java
Why Oak name for java language?

• Why Oak? : Oak is a symbol of strength and chosen as a national tree of many
countries like U.S.A., France, Germany, Romania etc.
• In 1995, Oak was renamed as "Java" because it was already a trademark by Oak
Technologies.

Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 25


History of Java
Why they choose java name for java language?

• The team gathered to choose a new name. The suggested words were "dynamic",
"revolutionary", "Silk", "jolt", "DNA" etc.
• They wanted something that reflected the essence of the technology:
revolutionary, dynamic, lively, cool, unique, and easy to spell and fun to say.
• According to James Gosling "Java was one of the top choices along with Silk".
• Since java was so unique, most of the team members preferred java.
• Java is an island of Indonesia where first coffee was produced (called java coffee).

Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 26


History of Java
• Notice that Java is just a name not an acronym.
• Originally developed by James Gosling at Sun Microsystems (which is now a
subsidiary of Oracle Corporation) and released in 1995.
• In 1995, Time magazine called Java one of the Ten Best Products of 1995.
• JDK 1.0 released in(January 23, 1996).

Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 27


Java Version History

Source: Wikipedia

Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 29


What is Java?
A multi-platform, network-centric, object-oriented programming language

• Multi-platform
• It can run on almost any computer platform

• Network-centric
• Designed with network in mind – “the network is the computer”
• Designed for building applications for the Internet

• Object-oriented
• It incorporates object-oriented programming model

30 Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT


Java Platform Editions
• A Java Platform is the set of APIs, class libraries, and other programs used in
developing Java programs for specific applications

There are 3 Java Platform Editions


1. Java 2 Platform, Standard Edition (J2SE)
• Core Java Platform targeting applications running on workstations
2. Java 2 Platform, Enterprise Edition (J2EE)
• Component-based approach to developing distributed, multi-tier enterprise
applications
3. Java 2 Platform, Micro Edition (J2ME)
• Targeted at small, stand-alone or connectable consumer and embedded
devices
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 31
Java Development Kit (JDK)
• The Java platform is formed from two components:

1. Java Application Programming Interface (Java API)


2. Java Virtual Machine (JVM).

§ The Java API is a set of libraries that you can use to accomplish tasks like
creating graphical user interfaces (GUIs), performing file input/output (I/O),
or establishing network communication.

§ The JVM is in charge of executing your code in a specific environment.

Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 32


Java Development Kit (JDK)
• A Java Development Kit (JDK) is a program development environment for writing
Java applications.

• It consists of a runtime environment that "sits on top" of the operating system


layer as well as the tools and programming that developers need to compile,
debug, and run applications written in the Java language.

Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 33


Java Development Kit (JDK)
• The Java Runtime Environment (JRE), also known as Java Runtime, is part of the
Java Development Kit (JDK), a set of programming tools for developing Java
applications.

• The Java Runtime Environment provides the minimum requirements for


executing a Java application; it consists of the

• Java Virtual Machine (JVM)


• core classes, and
• supporting files.

Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 34


Java Development Kit (JDK)

JDK
JRE
MyProgram.java
Java API
Java Virtual Machine
Hardware - Based Platform

Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 35


Java Development Kit (JDK)
• Java Development Kit (JDK)
• Is a set of Java tools for developing Java programs
• Consists of Java API, Java Compiler, and JVM

• Java Application Programming Interface (API)


• Is prewritten code, organized into packages of similar topics

• Java Virtual Machine (JVM)


• Is an execution engine that runs compiled Java byte code

Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 36


Java features
• Simple and Powerful
• Object Oriented
• Portable
• Architecture Neutral
• Distributed
• Multi-threaded
• Robust
• Secure/Safe
• Interpreted
• High Performance
• Dynamic programming language platform.

Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 37


Java as Object Oriented
• “Objects all the way down”
• All most everything in java is an Object.
• All program code and data will reside within objects and class.
• Simple and Familiar: “C++ Lite”
• No Pointers!
• Garbage Collector
• Dynamic Binding
• Single Inheritance with “Interfaces”

Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 38


Java as Portable
• Unlike other language compilers, Java complier generates code (byte codes) for
Universal Machine.
• Java Virtual Machine (JVM): Interprets bytecodes at runtime
• Architecture Neutral
• Higher Level Portable Features: AWT, Unicode

Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 39


Java is Portable:
Running on Different Platforms
class HelloWorld {
public static void main(String args[ ]) {
System.out.println(“Hello World!”); Java Program
}
}
Compiler

Interpreter Interpreter Interpreter

Hello
Hello Hello
World!
World! World!

Win32 Solaris MacOS 40


Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
Java

Write Once, Run Anywhere

Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 41


Architecture Neutral & Portable
• Java Compiler -Java source code to bytecode

• Bytecode - an intermediate form, closer to machine representation

• A Java Virtual Machine on any target platform interprets the bytecode

• Porting the java system to any new platform involves writing an interpreter that
supports the Java Virtual Machine

• The interpreter will figure out what the equivalent machine dependent code to
run
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 42
Java as High Performance
• JVM uses bytecodes
• Small binary class files
• Just-in-time Compilers
• Multithreading
• Native Methods

Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 43


Java in the World of Distributed Computing
• Class Loader
• Lightweight Binary Class Files
• Multithreading
• Dynamic
• Good communication constructs
• Secure

Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 44


Java as Secure
• Language designed as safe
• Strict compiler
• Dynamic Runtime Loading (Verifier)
• Runtime Security Manager

Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 45


Difference between C/C++ & Java
C/C++ Java
C/C++ are not platform independent Java is platform independent
There is a need of pre-processor directives There is no pre-processor directives

It supports pointer Doesn’t support Pointer


It allows default argument Java doesn’t allow default argument
It supports goto and sizeof operators It doesn’t support goto and sizeof

There is delete operator There is no delete operator


It provides operator overloading Java doesn’t support operator overloading

It supports structure and union There is no structure and union

Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 46


Java Architecture
• Java’s Architecture comes from four separate but intertwined
technologies:

1. the Java Programming Language


2. the Java class file format
3. the Java API, or Application Programming Interface
4. the Java Virtual Machine

Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 47


Java Architecture
• Source programs are written in the Java Programming Language.

All procedural code falls within methods.

Programs are compiled into Java class files.

Classes run in the Java Virtual Machine.

Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 48


Java Program Life Cycle
Compile-time Runtime Class
Environment Environment Loader Java
Bytecode Class
Verifier Libraries
Java
Source
(.java)

Just in
Java
Time
Interpreter
Java Compiler
Bytecodes
Java
move locally Virtual
Java
Compiler or through machine
network
Runtime System

Java
Operating System
Bytecode
(.class )
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT Hardware 49
Bytecode Verifier
• Called when class is first loaded in runtime environment
• Verifies bytecodes meet certain set of properties
• Verified code runs faster
• After verification, interpreter defines memory layout

Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 50


Class Loader
• Unique “Namespace” for each origin
• Local namespace classes are called “built-ins”
• Prevents class “spoofing”

Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 51


Security Manager
• Prevents unauthorized disk read/writes
• Restricts network access
• Other access restrictions (native methods)
• Implementation is browser dependent

Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 52


Security and the “Sandbox

Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 62


C and C++ are famous for speed.
• One reason they are fast is because C and C++ don’t do things like
checking the bounds of arrays.

• In C or C++, a program can walk off the edge of an array and invade
the memory space beyond.

• Hackers love that about C and C++.

Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 63


Security and the “Sandbox”
• Another weakness of C/C++, that is a favourite among Hackers, is the
Buffer Overflow.

• In this attack, the Hacker floods too much data into a buffer and
whatever overflows it is turned loose on the system.

• Java solves these problems

Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 64


Security and the “Sandbox”
• How Java Combats malicious code:

ü Java checks array boundaries


ü Java halts Buffer Overflows
ü Java has Garbage collection to get rid of objects that are no longer used.
ü Java’s compiler checks to make sure the code is safe before it runs.

• Gosling built security into Java, using a concept known as the


“Sandbox.”

Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 65


Local Code Security and the
“Sandbox

All Code , both Local and Remote, Must Pass Security Policy

JDK 1.2 Security Model

SANDBOX

Vulnerable System Resources (files, etc) Even


Local Code is Not Trusted

Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 66


Steps To Writing A Java Program
5 Steps To Writing A Java Program:

1. Write it in a Text Editor


2. Compiler creates bytecode
3. The “Class loader” places the . class file in memory.
4. The “Bytecode Verifier” makes sure the code adheres to Java’s security
rules.
5. The JVM Interpreter reads bytecode and makes platform native code.

Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 67


Objects in Java
• A class object is compiled Java code that contains its own data
variables, called members, and sections of procedural code called
methods.

• If you have programmed in COBOL, a method is like a paragraph you


perform.

• If you have programmed in C or C++, a method is like a function your


program calls.

Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 71


Objects in Java
• The combination of the data variables and
the methods that are used to
read,
write
or modify
those variables
is called a class.

Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 72


Objects in Java
• Java has a rich collection of Class Libraries.

• These are also known as the Java API or Application Programming


Interface.

• To program in Java, you must


i.) Learn the Language, and
ii.) Learn the Class Libraries.

Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 73


Objects in Java
• These class libraries greatly simplify your job as a Java programmer.

• They help you to write complex programs quickly.

• To master Java, you must master these class libraries.

Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 74


Compiling A Java Program
• You have created a Java program called
Hello.java
• To compile it, you run the JDK supplied utility called:
javac
C:javac Hello.java

• If this was successful, a file called: Hello.class will be produced.

Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 75


First Java Program
• The two largest varieties of Java programs:

Applications
Applets

Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 76


First Java Program
• A Java Application is a free-standing program that is capable of
running directly in the Java Virtual Machine.

• A Java Applet is a mini-program that is much more limited in its


abilities. An Applet can only run within the context of an HTML
browser.

Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 77


Example
• // HelloWorld.java Our first Java Application

public class HelloWorld


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

We have added the method “main”. All methods are lower case. main is a special method--
it actually runs the program.
In any application, you are always guaranteed that method main will run.
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 78
Compiling and Running a Java Program
To Compile:
C:>javac HelloWorld.java
To Run:
C:>java HelloWorld
O/P:
Hello World!

To run your compiled enter lowercase java HelloWorld on the command


line.
Notice, the “.class” extension is omitted.
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 79
Some Escape Sequences For Formatting
Escape sequence Description

\t Horizontal tab

\r Carriage return

\n New line

\” Double quote

\\ Backslash
Example Formatting Codes
• Name of the online example: FormattingExample.java

public class FormattingExample


{
public static void main (String [] args)
{
System.out.print("lol\tz\n");
System.out.println("hello\rworld");
System.out.println("\"Geek\" talk slash (\\) com");
}
}

Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 81


Variables
• Variable declaration:
• Creates a variable in memory.
• Specify the name of the variable as well as the type of information that it will
store.
E.g. int num;
• Although requiring variables to be explicitly declared appears to be an
unnecessary chore it can actually be useful for minimizing insidious logic
errors.
• Using variables
• Only after a variable has been declared can it be used.
• E.g., num = 12;

Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 82


Variables
Variable names must conform to the rules for identifiers:

• they must begin with a letter,


• after that they can contain digits, dollar signs and underscores.
• Java uses Unicode for its characters, so any “letter” that is valid for a
word in any world language is therefore valid for a name in Java.

Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 83


Declaring Variables
Syntax
• Format:
<type of information> <name of variable>;

• Example:
char myFirstInitial;

• Variables can be initialized (set to a starting value) as they’re declared:


char myFirstInitial = ‘j’;
int age = 30;

Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 84


Some Built-In Types Of Variables In Java
Type Description
byte 8 bit signed integer
short 16 but signed integer
int 32 bit signed integer
long 64 bit signed integer
float 32 bit signed real number
double 64 bit signed real number
char 16 bit Unicode character (ASCII and
beyond)
boolean 1 bit true or false value
String A sequence of characters between
double quotes ("")

Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 85


Primitive Data Types
• Java is a Strongly-typed language. That means, every variable must be declared as
a type.
• In Java, there are 8 primitive types:
• 6 of those refer to numbers
--4 for integers types,
--2 for floating-point types,
• 1 is the character type char, used for characters in Unicode encoding, and
• 1 is a boolean type for true or false values.

Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 86


Primitive Data Types

Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 87


Primitive Data Types

Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 88


Primitive Data Types

Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 89


Primitive Data Types

Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 90


Primitive Data Types

Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 91


Primitive Data Types

Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 92


Primitive Data Types

Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 93


Primitive Data Types

Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 94


Java Math Operators
• Addition +
• Subtraction –
• Multiplication *
• Division /
• Modulus %

• All are binary operators, i.e., they work with two numbers. They are
executed according to the rules for operator precedence.

(There is no operator for exponentiation in Java)


Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 95
Java Math Operators
Multiplication *

• What happens if you multiply variables of different types?

int x = 2;
double y = 3.889, sum = 0.000;
sum = y * x;

• The integer will be temporarily converted to a double and two doubles will
be multiplied.
• Afterwards, the original integer is unchanged.
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 96
Java Math Operators
• Rules for Temporary Conversions

1st Priority: If either of the operands is of type double, then the other one is converted
to double for the calculation.
2nd Priority: Otherwise, if either of the operands is of type float, then the other one is
converted to float for the calculation.
3rd Priority: Otherwise, if any of the operands is of type long, then the other one is
converted to long for the calculation.

Note: these conversions are automatic because none of them result in a loss of accuracy.
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 97
Java Math Operators
• Static Casts
So, what happens when you desire to convert a double to a float? Information will inevitably be
lost.
• You accomplish this using a cast.

• Here, a value of just 3 will be used for y.


• If you want to round y, you a method from class Math:

Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 98


Java Math Operators
Division /

• Division can lead to unexpected results:

If both operands are integers, then the result of the division is


also an integer.

Any fractional part of the division is discarded.

Therefore: 17/3 = 5
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 99
Java Math Operators
Modulus %

• The modulus operator is confusing at first, but eventually it becomes


your good friend.
• In contrast to the division operator, it returns the remainder of any
division. The modulus operator can only be used when both operands
are integers.
17 % 3 = 2
You say this “17 modulus 3 equals 2”
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 100
Comparison Operators
• These are used for selection structures:

equality ==
not equal !=
greater than >
less than <
greater than or equal >=
less than or equal <=

Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 101


Comparison Operators
• The equality operator is a common source of mistakes:
equality ==
• Note that two equal signs are always used.
• The single equal sign [ = ] is only used for assignment, that is,
assigning the value on the right to the variable on the left.

num1 = 33;

Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 102


Post/Pre Operators
The name of the online example is: Order1.java

public class Order1


{
public static void main (String [] args)
{
int num = 5;
System.out.println(num);
num++;
System.out.println(num);
++num;
System.out.println(num);
System.out.println(++num);
System.out.println(num++);
}
}

Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 103


Post/Pre Operators (2)
The name of the online example is: Order2.java

public class Order2


{
public static void main (String [] args)
{
int num1;
int num2;
num1 = 5;
num2 = ++num1 * num1++;
System.out.println("num1=" + num1);
System.out.println("num2=" + num2);
}
}

Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 104


Accessing Pre-Created Java Libraries
• It’s accomplished by placing an ‘import’ of the appropriate library at the top of your
program.

Syntax:
import <Full library name>;

• Example:
import java.util.Scanner;

Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 106


Getting Text Input
• You can use the pre-written methods (functions) in the Scanner class.
• General structure:

import java.util.Scanner; Creating a


scanner
object
main (String [] args) (something
{ that can scan
Scanner <name of scanner> = new Scanner (System.in); user input)
<variable> = <name of scanner> .<method> ();
}
Using the capability of
the scanner object
(actually getting user
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
input) 107
Getting Text Input (2)
The name of the online example: MyInput.java
import java.util.Scanner;

public class MyInput


{
public static void main (String [] args)
{
String str1;
int num1;
Scanner in = new Scanner(System.in);
Scanner str = new Scanner(System.in);
System.out.print ("Type in an integer: ");
num1 = in.nextInt();
System.out.print ("Type in a line: ");
str1 = str.nextLine ();
System.out.println ("num1:" +num1 +"\t str1:" + str1);
}
}

Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 108


Useful Methods Of Class Scanner
• nextInt ()
• nextLong ()
• nextFloat ()
• nextDouble ()
• nextLine ();

Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 109


Reading A Single Character
• Text menu driven programs may require this capability.
• Example:
GAME OPTIONS
(a)dd a new player
(l)oad a saved game
(s)ave game
(q)uit game
• There’s different ways of handling this problem but one approach is to extract the
first character from the string.
• Partial example:
String s = "boo“;
System.out.println(s.charAt(0));

Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 110


Reading A Single Character
• Name of the (more complete example): MyInputChar.java
import java.util.Scanner;
public class MyInputChar
{
public static void main (String [] args)
{
final int FIRST = 0;
String selection;
Scanner in = new Scanner (System.in);
System.out.println("GAME OPTIONS");
System.out.println("(a)dd a new player");
System.out.println("(l)oad a saved game");
System.out.println("(s)ave game");
System.out.println("(q)uit game");
System.out.print("Enter your selection: ");

Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 111


Reading A Single Character (2)
selection = in.nextLine ();
System.out.println ("Selection: " + selection.charAt(FIRST));
}
}

Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT 112

You might also like