0% found this document useful (0 votes)
22 views

Chapter-7 Ix Computer

Uploaded by

parasharaarna2
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

Chapter-7 Ix Computer

Uploaded by

parasharaarna2
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 46

CHAPTER-7

INPUT IN JAVA
Variable
• A variable is a container which holds the value
while the Java program is executed.
• A variable is assigned with a data type.
• A variable is the name of a reserved area
allocated in memory.
• In other words, it is a name of the memory
location.
• It is a combination of "vary + able" which
means its value can be changed.
• int data=50;//Here data is variable
Local Variable
• A variable declared inside the body of the
method is called local variable.
• You can use this variable only within that
method and the other methods in the class
aren't even aware that the variable exists.
• A local variable cannot be defined with "static"
keyword.
Instance Variable
• A variable declared inside the class but
outside the body of the method, is called an
instance variable.
• It is not declared as static.
• It is called an instance variable because its
value is instance-specific and is not shared
among instances.
Static variable
• A variable that is declared as static is called a
static variable.
• It cannot be local.
• You can create a single copy of the static
variable and share it among all the instances of
the class.
• Memory allocation for static variables happens
only once when the class is loaded in the
memory.
Example to understand the types of
variables in java
public class A {
static int m=100;//static variable
void method()
{ int n=90;//local variable
}
public static void main(String args[]) {
int data=50;//instance variable
}
}//end of class
public class A {
static int m=100;//static variable
void method()
{ int n;//local variable(error)
}
public static void main(String args[]) {

int data=50;//instance variable


}
}//end of class
Introducing to packages
• A package in Java is used to group related
classes.
• Think of it as a folder in a file directory.
• We use packages to avoid name conflicts, and
to write a better maintainable code.
• Packages are divided into two categories:
– Built-in Packages (packages from the Java API)
– User-defined Packages (create your own packages)
Built-in Packages
• The Java API is a library of prewritten classes,
that are free to use, included in the Java
Development Environment.
• The library is divided into packages and
classes. Meaning you can either import a
single class (along with its methods and
attributes), or a whole package that contain all
the classes that belong to the specified
package.
• To use a class or a package from the
library, you need to use the import
keyword:
• Syntax
– import package.name.Class; // Import
a single class
– import package.name.*; // Import the
whole package
Import a Class
• If you find a class you want to use, for
example, the Scanner class, which is used to
get user input, write the following code:
– import java.util.Scanner;
• In the example above, java.util is a package,
while Scanner is a class of the java.util
package.
import java.util.Scanner;
class MyClass {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter username");
String userName = sc.nextLine();
System.out.println("Username is: " +
userName);
}
}
Import a Package
• There are many packages to choose from. In the
previous example, we used the Scanner class
from the java.util package.
• This package also contains date and time
facilities, random-number generator and other
utility classes.
• To import a whole package, end the sentence
with an asterisk sign (*).
• The following example will import ALL the classes
in the java.util package:
– import java.util.*;
• java.lang: It contains classes for primitive
types, strings, math functions, threads, and
exceptions.
• java.util: It contains classes such as vectors,
hash tables, dates, Calendars, etc.
• java.io: It has stream classes for Input/Output.
• java.awt: Classes for implementing Graphical
User Interface – windows, buttons, menus,
etc.
• java.net: Classes for networking
• java. Applet: Classes for creating and
implementing applets
User-defined Packages
• To create your own package, you need to
understand that Java uses a file system
directory to store them. Just like folders on
your computer:
package mypack;
class MyPackageClass {
public static void main(String[] args) {
System.out.println("This is my package!");
}
}
Advantages of java packages
• Make easy searching or locating of classes and interfaces.
• Avoid naming conflicts.
• Implement data encapsulation (or data-hiding).
• Provide controlled access: The access specifiers protected and
default have access control on package level. A member
declared as protected is accessible by classes within the same
package and its subclasses. A member without any access
specifier that is default specifier is accessible only by classes in
the same package.
• Reuse the classes contained in the packages of other programs.
• Uniquely compare the classes in other packages.
Java User Input (Scanner)
• The Scanner class is used to get user input,
and it is found in the java.util package.
• To use the Scanner class, create an object of
the class and use any of the available methods
found in the Scanner class documentation. In
our example, we will use the nextLine()
method, which is used to read Strings:
import java.util.Scanner; // Import the Scanner class
class Main {
static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
// Create a Scanner object
System.out.println("Enter username");
String userName = myObj.nextLine();
// Read user input
System.out.println("Username is: " + userName);
// Output user input
}
}
Method Description

nextBoolean() Reads a boolean value from the user

nextByte() Reads a byte value from the user

nextDouble() Reads a double value from the user

nextFloat() Reads a float value from the user

nextInt() Reads a int value from the user

nextLine() Reads a String value from the user

nextLong() Reads a long value from the user

nextShort() Reads a short value from the user


import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
System.out.println("Enter name, age and salary:");
// String input
String name = myObj.nextLine();
// Numerical input
int age = myObj.nextInt(); double salary =
myObj.nextDouble(); // Output input by user
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Salary: " + salary);
}
}
Using Buffered Reader Class
• This is the Java classical method to take input,
Introduced in JDK1.0.
• This method is used by wrapping the System.in
(standard input stream) in an
InputStreamReader which is wrapped in a
BufferedReader, we can read input from the
user in the command line.
• The input is buffered for efficient reading.
• The wrapping code is hard to remember.
// Java program to demonstrate BufferedReader
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Test {
public static void main(String[] args)
throws IOException
{
// Enter data using BufferReader
BufferedReader reader = new BufferedReader(
new InputStreamReader(System.in));

// Reading data using readLine


String name = reader.readLine();

// Printing the read line


System.out.println(name);
}
}

To read other types, we use functions like Integer.parseInt(), Double.parseDouble(). To read


multiple values, we use split().
Using Scanner Class
• This is probably the most preferred method to take
input.
• The main purpose of the Scanner class is to parse
primitive types and strings using regular expressions,
however, it is also can be used to read input from the
user in the command line.
• Convenient methods for parsing primitives (nextInt(),
nextFloat(), …) from the tokenized input.
• Regular expressions can be used to find tokens.
• The reading methods are not synchronized
// Java program to demonstrate working of Scanner in Java
import java.util.Scanner;

class GetInputFromUser {
public static void main(String args[])
{
// Using Scanner for Getting Input from User
Scanner in = new Scanner(System.in);

String s = in.nextLine();
System.out.println("You entered string " + s);

int a = in.nextInt();
System.out.println("You entered integer " + a);

float b = in.nextFloat();
System.out.println("You entered float " + b);
}
}
Using Console Class
• It has been becoming a preferred way for
reading user’s input from the command line.
In addition, it can be used for reading
password-like input without echoing the
characters entered by the user; the format
string syntax can also be used (like
System.out.printf()).
• Reading password without echoing the
entered characters.
• Reading methods are synchronized.
• Format string syntax can be used.
• Does not work in non-interactive environment
(such as in an IDE).
// Java program to demonstrate working of
System.console()
// Note that this program does not work on IDEs as
// System.console() may require console
public class Sample {
public static void main(String[] args)
{
// Using Console to input data from user
String name = System.console().readLine();

System.out.println("You entered string " + name);


}
}
Using Command line argument
• Most used user input for competitive coding. The
command-line arguments are stored in the String
format.
• The parseInt method of the Integer class converts
string argument into Integer.
• Similarly, for float and others during execution. The
usage of args[] comes into existence in this input form.
• The passing of information takes place during the
program run. The command line is given to args[].
These programs have to be run on cmd.
// Program to check for command line arguments
class Hello {
public static void main(String[] args)
{
// check if length of args array is
// greater than 0
if (args.length > 0) {
System.out.println(
"The command line arguments are:");

// iterating the args array and printing


// the command line arguments
for (String val : args)
System.out.println(val);
}
else
System.out.println("No command line "
+ "arguments found.");
}
}
Compile time errors
Run Time errors
• Run Time errors occur or we can say, are detected during the
execution of the program.
• Sometimes these are discovered when the user enters an invalid data
or data which is not relevant.
• Runtime errors occur when a program does not contain any syntax
errors but asks the computer to do something that the computer is
unable to reliably do.
• During compilation, the compiler has no technique to detect these
kinds of errors.
• It is the JVM (Java Virtual Machine) that detects it while the program
is running.
• To handle the error during the run time we can put our error code
inside the try block and catch the error inside the catch block.
• For example: if the user inputs a data of string
format when the computer is expecting an
integer, there will be a runtime error. Example
1: Runtime Error caused by dividing by zero
// Java program to demonstrate Runtime Error

class DivByZero {
public static void main(String args[])
{
int var1 = 15;
int var2 = 5;
int var3 = 0;
int ans1 = var1 / var2;
// This statement causes a runtime error,
// as 15 is getting divided by 0 here
int ans2 = var1 / var3;
System.out.println("Division of va1"+ " by var2 is: "+ ans1);
System.out.println("Division of va1"+ " by var3 is: "+ ans2);
}
}
Compile Time Error
• Compile Time Errors are those errors which prevent the code from
running because of an incorrect syntax such as a missing semicolon
at the end of a statement or a missing bracket, class not found, etc.
• These errors are detected by the java compiler and an error
message is displayed on the screen while compiling.
• Compile Time Errors are sometimes also referred to as Syntax
errors.
• These kind of errors are easy to spot and rectify because the java
compiler finds them for you.
• The compiler will tell you which piece of code in the program got in
trouble and its best guess as to what you did wrong.
• Usually, the compiler indicates the exact line where the error is, or
sometimes the line just before it, however, if the problem is with
incorrectly nested braces, the actual error may be at the beginning
of the block. In effect, syntax errors represent grammatical errors in
the use of the programming language.
Misspelled variable name or method names
class MisspelledVar {
public static void main(String args[])
{
int a = 40, b = 60;

// Declared variable Sum with Capital S


int Sum = a + b;

// Trying to call variable Sum


// with a small s ie. sum
System.out.println("Sum of variables is "+ sum);
}
}
Missing semicolons
class PrintingSentence {
public static void main(String args[])
{
String s = "Geek";

// Missing ';' at the end


System.out.println("Welcome to " + s)
}
}
Logical error
• A logic error is when your program compiles and executes, but
does the wrong thing or returns an incorrect result or no output
when it should be returning an output.
• These errors are detected neither by the compiler nor by JVM.
The Java system has no idea what your program is supposed to
do, so it provides no additional information to help you find the
error.
• Logical errors are also called Semantic Errors. These errors are
caused due to an incorrect idea or concept used by a
programmer while coding.
• Syntax errors are grammatical errors whereas, logical errors are
errors arising out of an incorrect meaning.
• For example, if a programmer accidentally adds two variables
when he or she meant to divide them, the program will give no
error and will execute successfully but with an incorrect result.
Example: Accidentally using an incorrect operator on the
variables to perform an operation (Using ‘/’ operator to get the
modulus instead using ‘%’)
public class LErrorDemo {
public static void main(String[] args)
{
int num = 789;
int reversednum = 0;
int remainder;

while (num != 0) {

// to obtain modulus % sign should


// have been used instead of /
remainder = num / 10;
reversednum= reversednum * 10+ remainder;
num /= 10;
}
System.out.println("Reversed number is "+ reversednum);
}
}
Syntax Error:
• Syntax and Logical errors are faced by
Programmers.
• Spelling or grammatical mistakes are syntax
errors, for example, using an uninitialized
variable, using an undefined variable, etc.,
missing a semicolon, etc.
• int x, y; x = 10 // missing semicolon (;) z = x + y;
// z is undefined, y in uninitialized. Syntax
errors can be removed with the help of the
compiler.

You might also like