Simple Java Prog
Simple Java Prog
Simple Java Prog
Creatingan Object
As mentioned previously, a class provides the blueprints for
Class Factorial
{
{ int a, b=1;
Int n =Integer.parseInt(args[0]);
for(a=1; a<=n;a++)
{ b=b*a;
}
}
Factorial is 120
USING SCANNER CLASS
importjava.util.Scanner;
publicclassAddTwoNumbers2 {
publicstaticvoidmain(String[] args) {
int num1, num2, sum;
Scanner sc = newScanner(System.in);
System.out.println("Enter First Number: ");
num1 = sc.nextInt();
System.out.println("Enter Second Number: ");
num2 = sc.nextInt();
sc.close();
sum = num1 + num2;
System.out.println("Sum of these numbers: "+sum);
}
}
Java User Input
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:
SCANNER METHODS
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
public class Puppy {
int puppyAge;
public Puppy(String name) {
// This constructor has one parameter, name.
System.out.println("Name chosen is :" + name );
}
public void setAge( int age ) {
puppyAge = age;
}
public int getAge( ) {
System.out.println("Puppy's age is :" + puppyAge );
return puppyAge;
}
public static void main(String []args) {
/* Object creation */
Puppy myPuppy = new Puppy( "tommy" );
/* Call class method to set puppy's age */
myPuppy.setAge( 2 );
/* Call another class method to get puppy's age */
myPuppy.getAge( );
/* You can access instance variable as follows as well */
System.out.println("Variable Value :" + myPuppy.puppyAge );
}
}