Posts

Showing posts with the label Part E : JAVA Methods

Methods : Accessing from outer Classes (Part 3)

Image
  In the last tutorials , we learned about accessing methods within the class using static keyword. Now we will learn how to access methods from outside the class i.e other classes. Accessing methods outside the Class Till now we used to declare methods and call them in the same class , that is why we used static keyword . static means method of main class. eg:- public class MyClass { static void start () { System.out.println(" Machine Starting ! "); } public static void main(String args[]) { start (); } } //Outputs Machine Starting ! Here we declared and called a method in the class MyClass . For accessing methods from outer class , we should first create objects of it and then access them.If you are not through with creating objects , visit  Objects page. Here ( . ) keyword is used to access methods or variables of a class i.e" object . method/variable" class OtherClass { void sta...

Methods : Parameters & Arguments (Part 2)

Image
In the last tutorial we learned about Methods Declaration and Calling them . In this tutorial , we will learn about passing an argument and parameter into methods and the difference between them. Method Parameters Information can be passed to methods as parameter. Parameters act as variables inside the method. Parameters are specified after the Method name , inside the parentheses. You can add as many parameters as you want, just separate them with a comma. The following example has a method  getName()  that takes a  String  called  name  as parameter. When the method is called, we pass along a String, which is used inside the method to print the name: public class MyClass { static void getName (String name ) { System.out.println(" Heyy I am " + name + " . "); } public static void main(String args[]) { getName (" Bob "); getName (" Harry "); getName (" John ...

Methods : Basics (Part 1)

Image
Java Methods ⏺ A  method  is a block of code which only runs when it is called. ⏺ Methods are used to perform certain actions, which are also known as  functions . ➤Why use methods ?  To reuse code: define the code once, and use it many times. ➤ Declaring a method ⏺ A method must be declared within a class.  ⏺ It is defined with the name of the method, followed by parentheses  ()  . ⏺ Method is created by first specifying its dataType such as void , int , string , etc. and then its name. ⏺ When method is called :          void  will not return any value          int  will return an integer          String  will return a string ➤Syntax:- dataType MethodName () { //block of code to be executed } For example I created a method named start ( ) which will print out starting machine when called. static void start () { ...