Header Ads

Java SE Programming 3 - Method parameters, Scanner class





In last post we talked about variables and methods. Let's continue.

Do you know in Java, there can have multiple classes in one source file. But when naming the source file 'the name of the source file' should be same as the class file where the main method exist.




As you can see here there are 4 classes in the source file.
The main method is in Test class,
then the source file's name should be Test.java













outcome of these statements are commented in front of the each status.








Method Parameters 

In previous posts you should have seen that when we write a method we used 

Return type + Method name + () +{

}

 this format.

For example ,

       void m(){
            System.out.println("m method");
       }

There are parenthesis but inside those we didn't put anything. Let's put some parameters and see what the outcomes are.





Inside those parenthesis we put parameters, they are variables with data types. And those variables are only visible to that method, It means those variables are Method Local Variables which we learned in last post.  







When we call the method we put the variables which are wanted to use in that method.
For the first method calling 2.4 become x and 4.5 become y.





How to take user inputs from the keyboard 

We use Scanner class in Java to get user inputs. Scanner is a predefined class which has several methods that can be used to take keyboard inputs. 
Those methods are below,

next()    -----------> use to read String inputs
nextInt() ----------> use to read integer inputs
nextDouble() -----> use to read double inputs 

Before we use those methods we have to import the Scanner class. 
















output of above code


                                                                                                                                                                                                                                                                               










Remember that when using import statements it should be put just before the class and outside the class declaration.




No comments

Powered by Blogger.