-
Notifications
You must be signed in to change notification settings - Fork 0
'main'
.. looks like this:
public class MyFirstProgram
{
public static void main(String[] args)
{
System.out.println("Hello!");
int sum = 2 + 2;
System.out.println("The sum is " + sum);
System.out.println("OK, I'm done. Bye!");
}
}
Every Java program is built from classes. A class combines variables
to hold data and methods
which contain code. A class is defined like this:
public class NameOfTheClass
{
// The content of the class
}
Class names usually start Uppercase, and may use CamelCaseNotation.
Most classes are public
, meaning other code can see them.
In special cases, you create private
classes, we'll get to that later.
Inside a class, you can define methods like this:
public void doSomething()
{
System.out.println("I'm doing something");
}
This method returns nothing ,void
.
Method names usually start lowercase(), and may_use_underscores() or switchToCamelCase() for longer names.
Methods end in parenthesis for their arguments. Empty parenthesis '()' declare that a this method takes no arguments.
When you invoke it via doSomething()
, it will print some text.
This method takes one argument, you would invoke it with a String like hello("Fred")
public void hello(String name)
{
System.out.println("Nice to meet you, " + name);
}
This method takes two numeric arguments, and returns a number:
public int doMath(int a, int b)
{
int c = 2 * b;
return a - 5*c;
}
A _method _that takes arguments and returns a value is sometimes also called a function. You could use that as follows:
int result = doMath(47, 123);
System.out.println("The result is " + result);
A Java program starts by running the code in a special main
method which must have this exact signature:
public static void main(String[] args)
{
}