DEV Community

Janardhan Pulivarthi
Janardhan Pulivarthi

Posted on • Edited on

Day 5 of 100 - Java: Functions and Objects

Working with functions

Function definition of println:

public void println(String x) { if(x == null) { x = "null"; } try { ensureOpen(); textOut.write(x); } catch (IOException e) { trouble = true; } newLine(); } 
Enter fullscreen mode Exit fullscreen mode

Function call:

System.out.println(); 
Enter fullscreen mode Exit fullscreen mode

public - access modifier
void - return type
function() - how we call our function
inside the function - block of code

Parameters and Arguments:

public void greeting(String location) { System.out.println("Hello, " + location); } greeting("New York"); 
Enter fullscreen mode Exit fullscreen mode

Randomly rolled dice:

/** * This dice function simulates a 6 sided dice roll * * @return random value from 1 to 6 */ public int rollDice() { double randomNumber = Math.random(); // 0 to 0.999... // A dice have 1 to 6 // i.e, so max value 6.9999 and min value of 1.00 randomNumber = randomNumber * 6 // shift range up one randomNumber = randomNumber + 1; int randomInt = (int) randomNumber; // casting return randomInt; } int roll1 = rollDice(); //example, 2 int roll2 = rollDice(); //example, 4 
Enter fullscreen mode Exit fullscreen mode

Points on functions:

  1. Easy to reuse code
  2. Organize and group code
  3. More maintainable code
  4. Function definition is like a dictionary detail for a word in a sentence
  5. Argument order is important in a function call
  6. Math.Random() gives a random number between 0 and 1

Objects

Points on objects:

  1. Objects combine variables together to make your code meaningful
  2. Organized and maintainable code

--
https://docs.oracle.com/javase/8/docs/api/java/lang/package-summary.html

Top comments (0)