Skip to content

Instantly share code, notes, and snippets.

@mviktora
Last active November 22, 2025 18:46
Show Gist options
  • Select an option

  • Save mviktora/62f639def8fa8642a9b709a5e2b6c39b to your computer and use it in GitHub Desktop.

Select an option

Save mviktora/62f639def8fa8642a9b709a5e2b6c39b to your computer and use it in GitHub Desktop.
Java coding

Simplest Java class
Adding a method
Using a class (from outside of a class definition)
Using a method (from inside of a class definition)
Method overloading
Writing a Java program
Public and private classes
Public and private methods
Class variables

Java elementary contructs:

while loop

Example:

// Will print numbers 0 to 9
int i = 0;

while (i < 10) { // will continue while the expression is true
	System.out.println(i);
	i++;
}

for loop

// Will print numbers 0 to 9
int i;

for (i = 0; i < 10; i++) {
	System.out.println(i);
}

Can also be written simpler like this:

// Will print numbers 0 to 9
for (int i = 0; i < 10; i++) {
	System.out.println(i);
}

The first part of the "for" statement (here int i = 0) is used to initialize the loop variable, that is to say what value it should have in the beginning The second part (here i < 10) is a condition evaluated each time before running the code in {}. The code will continue to be run as along as the condition is true The last part is what to do with the cycle variable at the end of the cycle (here i++). Typically it is increased or decremented by some value.

Simplest Java class

Example of a simplest Java class:

class MyCalculator {
}

We define a class by using the word "class", followed by a class name, (chosen by us), followed by a pair of curly brackets {}. The code of our class goes inside the curly brackets (in this case, there is no code).

The name of the class should be something that represents the task the class is going to do.

This example is not very useful because the class is empty. In order to make it more useful, we need add methods.

Adding a method

class MyCalculator {
	int addNumbers(int a, int b) {
		return a + b;
	}
}

Now the class has one method named "addNumbers".

When defining a method, we first write the method's return value (in this example int), followed by the method's name, and then followed by its parameters in parenthesis, separated by a comma. Each parameter must have a type in front of it (here int a and int b)

Method with no return value

If a method does not return a value, we use type "void". Example:

class MyCalculator {
	void printText(String text) {
		System.out.println(text);
	}
}

Method with no parameters

If a method does not have any parameters, the parenthesis are empty:

class MyCalculator {
	int getSomeNumber() {
		return 2;
	}
}

Using a class (from outside of a class definition)

Once we have created our class and added methods to it, we can use the class.

In order to use a class, we first have to create (instantiate) an object representing that class. That is done using the keyword "new", followed by the class name:

MyCalculator calc = new MyCalculator();

Now "calc" is an object variable containing the instance of MyCalculator class. From this point on, we can "call" its methods using the variable name, followed by dot ".", followed the method's name:

calc.sum(2, 5);

A complete example:

public  class MyApp {
	public static void main(String[] args) {
		// This will create our MyCalculator object and stores in "calc" variable
		MyCalculator calc = new MyCalculator();
		
		// Now we can call it's method:
		int x = calc.sum(2, 5);
		
		System.out.println(x);
	}
}

class MyCalculator {
	int sum(int  a, int  b) {
		return  a + b;
	}
}

If a method returns a value, that value can be assigned to a variable, like the example above. You can also pass the return value directly as another method's parameter:

		System.out.println(calc.sum(2, 50));

This will do exactly the same thing as:

		int x = calc.sum(2, 5);
		
		System.out.println(x);

Using a method (from inside of a class definition)

A class method can be called by another method from the same class. In order to do that, we use the word "this", followed by a dot ".", and the method's name.

Example:

class MyCalculator {
	int sum(int  a, int  b) {
		return  a + b;
	}
	void printSum(int a, int b) {
		// This will call our sum method
		int x = this.sum(a, b);
		System.out.println(x);
	}
}

Method overloading

A method of the same name can have different parameters. This is called method overloading.

Example:

public  class  MyCalculator {  
	public int add(int  a, int  b) {  
		return  a + b;  
	}  
	  
	public int add(int  a, int  b, int  c) {  
		return  a + b + c;  
	}    
}

Here the method "add" has two "versions". One that adds two numbers and another one that adds three numbers. It can be called like this:

x = calc.add(2, 5); // Will call the first method

x = calc.add(2, 5, 9); // Will call the second method

Java will correctly match the right method based on the number and type of parameters.

Writing a Java program

So how do we write a program in Java since everything in Java is an object?

In general, we put all of our code in classes and then use the classes by creating their instances. That's it.

Often, one class uses another class, and that class uses yet another class.

Example:

public  class MyApp {
	public static void main(String[] args) {
		MyClassA objA = new MyClassA();

		objA.methodA();		
	}
}

class MyClassA {
	void methodA() {
		MyClassB objB = new MyClassB();

		objB.methodB();
	}
}

class MyClassB {
	void methodB() {
		// Code that does something
	}
}

Objects can be (and ofter are) passed as method parameters.

Example:

public  class MyApp {
	public static void main(String[] args) {
		MyClassA objA = new MyClassA();
		MyClassB objB = new MyClassB();

		classA.methodA(objB);
	}
}

class MyClassA {
	void methodA(MyClassB objB) {
		objB.methodB();
	}
}

class MyClassB {
	void methodB() {
		// Code that does something
	}
}

Public and private classes

By default classes are private. Private classes can be used only within the file in which they are defined.

If we want to use a class in another Java file, we have to make it public by using the word "public" in front of the word "class":

public class MyCalculator {
	// your code
}

Now you can use MyCalculator in another Java file.

A Java file can have only one public class. If you need another class to be public, you must place in a separate file.

Public and private methods

Methods inside of a class are by default "public". That means the methods can be used (called) from outside of the class.

That is in many cases undesirable. For example, when more programmers are working together, it may be useful to say which methods are "allowed" to used from outside, and which are internal to the logic of the class and cannot be used from outside. Its a way of saying to "others", use only these (public) methods.

In order to make a method private, we use the "private" word:

class MyCalculator {
	private int sum(int  a, int  b) {
		return  a + b;
	}
	void printSum(int a, int b) {
		// This will call our sum method
		int x = this.sum(a, b);
		System.out.println(x);
	}
}

Now, trying to use the "sum" method from outside will trigger an error. The only method that can be used from outside is "printSum".

Note that you can also use the word "public" in method header:

	public void printSum(int a, int b) {

It is exactly the same as leaving the word public out:

	void printSum(int a, int b) {

In both cases the method is public.

Strings and characters

In Java, another elementary type is "char". Char represents a single letter (character).

Example:

char x = 'A'; // defines a variable x of char type and assignes a letter A to it

Note: Unlike String where we use double quotes, we use single quotes when referring to a single character.

We can compare char variables like numbers:

char x = 'A';

if (x == 'A') {
	System.println("x contains A");
}

We can access individual characters in a String using charAt(index) method.

Example:

String text = "Hello";

char x = text.charAt(0); // x will contain H (first character)

To get the total number of characters in a string we can use length() method:

String text = "Hello";
System.println(text.length()); // will print 5

Class variables

So far we have added only methods to our class. Now what if we want the instance of our class to remember some information, like a number or string?

In order to do that, we can define variables inside of the class definition:

class MyClass {
	int a;
	String text;
}

Let's use it on an example. Let's say we are implementing a class called Counter, which keeps a numerical value. We can add or subtract value to / from it.

class Counter {
	int value = 0;
	
	void add(int x) {
		this.value = this.value + x;
	}
	void subtract(int x) {
		this.value = this.value - x;
	}
}


public class MyApp {
	public static void main(String args[]) {
		Counter counter = new Counter();

		System.out.println("The value of counter is: " + counter.value);
				
		counter.add(3);
		System.out.println("The value of counter is: " + counter.value);
		
		counter.subtract(1);
		System.out.println("The value of counter is: " + counter.value);

	}
}

When referring the to member variable from within the class definition, we use the word "this", such as "this.value". When referring to the member variable from outside, we use the object instance variable, such as "counter.value".

Task:

Create a class called FruitStore that will keep a count of the following fruits: bananas, apples, oranges and pears.

The class will have the following methods:

// Constructur that will initialize the number of fruits:
FruitStand(int bananas, int apples, int oranges, int pears);

// Will increase the stored number for a given fruit by count
void add(String fruitName, count);

// Will return a string with the fruit, for example: "Here are your 3 pears". and decrease the number of pears by 3.
void get(String fruitName, count);

// Will return the current count of a given fruit
int getCount(String fruitName);

void printInventory(); // will print the name and count of fruit

The String parameter fruitName will be name of one of the fruits.

The following is an example use of the class:

FruitStand *stand = new FruitStand(4, 7, 11, 9);

stand.add("apple", 3);
stand.add("pear", 5);

stand.printInventory();
/* Will output:

Bananas: 4
Apples: 10
Oranges: 11
Pears: 14

*/

String text = stand.get("Apples", 2);
System.out.println(text);

/* Will output: "Here are you 2 apples."

It will also descerase the number of apples by 2.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment