Beruflich Dokumente
Kultur Dokumente
1
Contents
User input
Scope and Lifetime of variable
Conversion
Automatic Conversion
Casting
Arrays
One Dimensional
Multidimensional
Java Programming
User Input
User Input
java.util Library
Scanner class is part of Java.util library
Scanner class:
Built-in Class use to handle input from user.
import keyword
import is a keyword used to reference any class in code.
E.g.
import java.util.Scanner; //It should be placed before class
Java Programming 4
User Input
Class object
Objects are instance of class
Class is just container, objects are actual player of class.
Functionality of Scanner class is utilized by creating its
object:
E.g. Scanner obj_userinput = new Scanner(System.in);
Scanner is name of class
new Keyword is used to create new object of class.
System.in (System input)
Java Programming 5
User Input
Scanner class method next
This gets the next string types by user
E.g.
String first_name;
System.out.print(“Enter your first name”);
first_name = obj_userinput.next();
Java Programming 6
Program: Write a program which takes input from user, and display it.
import java.util.Scanner;
Output
public class user_input
Enter your name:
{ Ahsan
Your name is: Ahsan
public static void main(String[] arg)
{
String var_name;
Scanner obj_input = new Scanner(System.in);
Java Programming
Scope and Lifetime of variable
Types of Scope
Global: Visible to other scopes.
Local: Invisible to other scopes.
Nested Scope
When child scope is defined in parent scope, is called as nested scope.
Each element of parent scope is visible to child scope.
But elements of child scope are invisible to parent scope.
E.g.
Parent scope
{
Child Scope
{}
}
Java Programming
Program: Write a program which demonstrate local and global scope.
Java Programming
Program: Write a program which demonstrate re-initialization of local variable.
Output:
public class var_scope Global y is: 10
{ Local y is: -1
public static void main(String[] args) Local y2 is 100
{ Local y is: -1
Local y2 is 100
int y=10; Local y is: -1
System.out.println("Global y is: "+y); Local y2 is 100
for(int x = 0; x < 3; x++) Global y is: 100
{
y = -1;
System.out.println("Local y is: " + y);
y = 100;
System.out.println("Local y2 is " + y);
}
System.out.println("Global y is: "+y);
}
}
Java Programming
Conversion and Casting
Conversion
Conversion of value of one type to another type.
Java Programming
Numeric Data Types
byte 1 byte Integers in the range
-128 to +127
2-16
Conversion
Syntax:
(target-type)value
E.g.
int a;
byte b;
// ...
b = (byte) a;
Java Programming
Casting
Automatic or Widening Conversion
E.g. int type is able to handle all byte values, so byte can be
converted to int automatically.
Java Programming
Casting
Truncation
When floating point type value is assigned to integer type,
the fractional component is lost.
Java Programming
Program: Write a program
Java Programming