Loading...

Postulate is the best way to take and share notes for classes, research, and other learning.

More info

The AP CS A curriculum (Units 1-8) in 10 minutes for people who know Python | A Java syntax guide

Profile picture of Laura GaoLaura Gao
Apr 14, 2021Last updated Apr 30, 20229 min read

Part A: OOP, The underlying structure

Unlike Python, Java is a completely object oriented programming language - every single line of code is nested within a method of a class.

This is what the Hello World of Java looks like:

public class HelloWorld {
		public static void main (String args[]) {
				System.out.println("Hello Sunshine")
		}
}

Out:

Hello Sunshine

Analyzing the Hello World

In order to print a single line, we need to nested inside two sets of curly braces. The first set, public class HelloWorld is a class. In Java, the entirety of a file is within that one class. You cannot have multiple (public) classes in one file.

The second set, public static void main (String args[]), is a method, with name main. The main method gets executed when running the file.

Other methods can be added underneath the main method, and those have to be called within the main block.

public class HelloWorld {
		public static void main (String args[]) {
				String hello = "Hello Sunshine";
				System.out.println(addQuestionMark(hello));
		}

		public static String addQuestionMark (String s) {
				return s + '?';
		}
}

Out:

Hello Sunshine?

This is different from Python, in which you can call lines directly without nesting 'em inside a class nor a method.

Some things to note:

  • System.out.println("message") is the python equivalent of print("message")

  • Add a semicolon at the end of any block that doesn't end with a curly bracket

  • Blocks in Java are separated by curly brackets. This is equal to the python grouping of indents.

  • When methods are used within the class that they are declared in, they are called the same way that you call functions, i.e., straight-up calling them like addQuestionMark(); instead of putting it after a period of an object like you normally call methods. (In Python, you need to write self.method() to call a method within its class.)

Analyzing the Hello World x2

Part 1: The variables

Variables in Java are unique from both python and javascript. Each variable has a type when it's declared. E.g. to declare a variable to hold an integer,

int age = 15;

you have to declear that it's an integer with the int keyword.

Some types of variables are built into Java:

int age = 15;
double mark = 97.3;
String greeting = "Hello darling!";
boolean isHappy = true;

These are called primitive types. There are 4 main primitive types - the ones shown above.

In the Hello World x2 code, you can see that the variables that were declared follow this pattern:

String hello = "Hello Sunshine";

Part 2: Defining a function

Under the main function, we see that we had defined this function:

public static String addQuestionMark (String s) {
		return s + '?';
}

Each keyword has a meaning.

  • public means that this function can be assessible to objects outside of this class. (As opposed to private variables, whose values cannot be accessed by the outside.)

  • static I'm not sure what it means.

  • String means that the output of this function is a string

Parameters that are placed into a function must also have its type declared, as you can see from this line:

public static String addQuestionMark (String s) {



Declaring classes

The heart of OOP is your own classes to which you can apply methods to. Within the same folder, we make another file, named Wolf.java.

class Wolf {

}

The whole wolf.java file will contain the instructions for this class. The name of the java file is equal to the name of this class that fills the whole page.

Back in the main file, we can create an instance of the wolf class.

Wolf bobby = new Wolf();

This variable, bobby, is different from a variable such as hello. Hello is a primitive variable, bobby is a reference variable. The significance? If we print a reference variable,

System.out.println(bobby);

Out:

Wolf@28a418fc

We don't get no value. We get a reference object, where the variable "points" or the location at which it is stored.

Inside the wolf class, we can declare methods just like we did previously in Hello World x2.

class Wolf {
		public static void doStuff() {
				for(int i = 10; i < 20; i++){
						System.out.println("I love all numbers, including " + i);
				}
		}
}

Note: void means that the function returns a null value.

We can call this method in our main file

bobby.doStuff();

Out:

I love all numbers, including 10
I love all numbers, including 11
I love all numbers, including 12
I love all numbers, including 13
I love all numbers, including 14
I love all numbers, including 15
I love all numbers, including 16
I love all numbers, including 17
I love all numbers, including 18
I love all numbers, including 19

Here is all of our code together, if you want to see the overall structure:

In file HelloWorld.java:

public class HelloWorld {
		public static void main (String args[]) {
				String hello = "Hello Sunshine";
				System.out.println(addQuestionMark(hello));
				Wolf bobby = new Wolf();
				System.out.println(bobby);
				bobby.doStuff();
		}

		public static String addQuestionMark (String s) {
				return s + '?';
		}
}

In Wolf.java:

class Wolf {
		public static void doStuff() {
				for(int i = 10; i < 20; i++){
						System.out.println("I love all numbers, including " + i);
				}
		}
}

Note: when two java files are in the same folder, you don't need any import statements to use classes and methods from another file.

End of OOP, the underlying structure.



Part B: Syntax

If you know python, you know the logic behind how for loops, if statements, arrays, etc work. Syntax is different, but you can understand syntax just by looking at code. Below is code:

Array Syntax

String[] senpais = {"sigil", "michael", "samson", "taira"} // declaration
senpais[0] // access an element
senpais[senpais.length-1] // find the length

String[] hotties = new String[4]; // another method of declaration

Double arrays:

// Create
char [] [] gameBoard = {{' ', '|', ' ', '|', ' ' },  
		{'-', '+', '-', '+', '-' }, 
		{' ', '|', ' ', '|', ' ' },
		{'-', '+', '-', '+', '-' }, 
		{' ', '|', ' ', '|', ' ' }};
		
// Access elements
		gameBoard[0][4] // Returns the element on the 1st column and 5th row

Arrays are reference variables.

Arrays have the downfall that you cannot change their length after declaration, and being reference variables, you have to loop through each element to print out a list. To get around this, we use ArrayLists.

ArrayLists

Import at beginning of Java file, before the class declaration: import java.util.ArrayList;

public class Main {
	public static void main(String[] args) {
		ArrayList<String> cars = new ArrayList<String>(); // note the declaration syntax
		cars.add("Volvo"); // add method to append elements
		cars.add("BMW");
		cars.add("Ford");
		cars.add("Mazda");
		System.out.println(cars);
		cars.get(0); // get method to retrieve elements based on index number
		cars.set(0, "Opel"); // set method to change an element
		cars.remove(0); // remove method to remove an element based on index number
		cars.clear(); // clear method to remove all elements
		cars.size(); // returns the number of eleemnts
	}
}

If else

if (round % 2 == 1)
	player1 = true;
else
	player1 = false;

Can have curly brackets or not curly brackets. Use curly brackets usually if your indented code has more than one line because Java doesnt recognize indents - Java won't recognize the rest of the indented block as within the if statement.

if (pos % 2 == 1) {
	if (pos == 1 || pos == 5 || pos == 9) {
		checks[2][0] = 1;
		checks[2][1] = 5;
		checks[2][2] = 9;
	}
	else {
		checks[2][0] = 3;
		checks[2][1] = 5;
		checks[2][2] = 7;
	}
	if (pos == 5) {
		checks[3][0] = 1;
		checks[3][1] = 5;
		checks[3][2] = 9;
	}

Loops

For loop - also can either have curly braces or not.

for (int i = 0; i < gameBoard.length; i++) {
	System.out.println(gameBoard[i]);
}

Just like if statements, all forms of intended blocks do not recongize multi-lined indents as part of the block.



For each loop - works with arrays and arraylists:

for (String name : senpais) { 
	print(name)
}

Note: you can't modify each array element using for each loops. Only access.

While loop:

while(isInteger == false) {
	try {
		Scanner scan = new Scanner(System.in);
		pos = scan.nextInt();
		isInteger = true;
	} catch(java.util.InputMismatchException exception) {
		System.out.println("Please enter an integer 1-9!");
		isInteger = false;
	}
}

While loops are best used when the number of iterations is not certain; for loops when it is.

Try catch

try {
	Scanner scan = new Scanner(System.in);
	pos = scan.nextInt();
} catch(java.util.InputMismatchException exception) {
	System.out.println("Please enter an integer 1-9!");
}

Some quirks with strings

String literals vs string objects:



So always use .equals() when comparing strings.

To create substrings: String.substring(start-index, last-index + 1);



Other syntax quirks:

  • A variable created in a block is recognize only in that block.



To combat this: declare n outside the inner block. You can use int n; to decare the variable without assigning it.

  • In division, if dividents and divisors are both integer-types, then the output will be an integer even if it's not perfectly divisible.
  • % for the modulus pperator (returns the remainder of division, e.g. 8 % 3 returns 2.)

Unlike Python, like JS:

  • ; at end of each line

  • || is or

  • && is and

  • else if instead of elif

  • like JavaScript's var keyword to declare variable but the keyword is type of the variable

  • // is single line comment
  • Boolean values (true and false) are lowercase (uppercase in Python)
  • ++ serves as += 1

Unllike JS, like Python:

  • == is equal

Unlike Python:

  • Everything added to a string becomes a string, e.g. "Hello" + 1 returns Hello1. (in Python, you can't add an integer to a string without converting it into a string first.)

  • Single quotes and double quotes are not interchangeable, like they are in both js and python. Single quotes for character literals, double quotes for string literals.

Comments (loading...)

Sign in to comment

Dev/CS

Builders gonna build baby