Java quick guide for Python user

Tweet


File and Class Names

Python

print('Python program')

File name

myprogram.py

Output

Python program

The file name can be anything.

Java

public class myprogram{
    public static void main(String [] args){
        System.out.println("Java program");
    }
}

File name

myprogram.java

Output

Java program

File name and class name must be the same


main function

Python

def main():
    print('Python program')

if __name__ == '__main__':
    main()

Output

Python program

Executed in order from top to bottom
In this case, the if statement is executed and the main function is called

Java

public class myprogram{
    public static void main(String [] args){
        System.out.println("Java program");
    }
}

Output

Java program


Comment

Python

def main():
    ''' Comment 1st line
    Comment 2nd line '''
    print('Python program') # Comment

if __name__ == '__main__':
    main()

Output

Python program

Comments between ''''and'''''
# and onwards to the end of the line is the comment

Java

public class myprogram{
    public static void main(String [] args){
        /* Comment 1st line
        Comment 2nd line */
        System.out.println("Java program"); // Comment
    }
}

Output

Java program

Anything between /* and */ is a comment
// and onwards to the end of the line is the comment


Semicolon

Python

def main():
    print('Line 1')
    print('Line 2'); print('Line 3')
    print( \
        'Line 4' \
    )

if __name__ == '__main__':
    main()

Output

Line 1
Line 2
Line 3
Line 4

One instruction per line
Separate multiple instructions on a single line with a semicolon.
If a single instruction spans lines, add a backslash at the end of the line.

Java

public class myprogram{
    public static void main(String [] args){
        System.out.println("Line 1");
        System.out.println("Line 2"); System.out.println("Line 3");
        System.out.println(
            "Line 4"
        );
    }
}

Output

Line 1
Line 2
Line 3
Line 4

Instructions are separated by a semicolon.
A line may contain multiple instructions, or a single instruction may span multiple lines, up to and including a semicolon.


Text output and line breaks

Python

def main():
    print('Example',end='')
    print('Program')
    print()
    print('Line1\nLine2')

if __name__ == '__main__':
    main()

Output

ExampleProgram

Line1
Line2

The print function outputs a character and breaks line
If no line break, specify '' for end
\n denotes a line break

Java

public class myprogram{
    public static void main(String [] args){
        System.out.print("Example");
        System.out.println("Program");
        System.out.println();
        System.out.println("Line1\nLine2");
    }
}

Output

ExampleProgram

Line1
Line2

The println function outputs a character and breaks line
If no line break, use print function
\n denotes a line break


Data Type and Variable Definitions

Python

def main():
    a=10
    b=2.5
    c=2.5
    d="abc"
    e=True
    print(a)
    print(type(a))
    print(b)
    print(type(b))
    print(c)
    print(type(c))
    print(d)
    print(type(d))
    print(e)
    print(type(e))

if __name__ == '__main__':
    main()

Output

10
<class 'int'>
2.5
<class 'float'>
2.5
<class 'float'>
abc
<class 'str'>
True
<class 'bool'>

When defining variables, it is not necessary to write the data type
The data type for integers is int, and there are no restrictions on the number that can be represented.
The data type of floating-point numbers is float, and 64-bit floating-point numbers
String data type is str
Bool value data is of type bool
All Python data types are class types

Java

public class myprogram{
    public static void main(String [] args){
        int a=10;
        float b=2.5f;
        double c=2.5;
        String d="abc";
        boolean e=true;
        System.out.println(a);
        System.out.println(((Object)a).getClass().getSimpleName());
        System.out.println(b);
        System.out.println(((Object)b).getClass().getSimpleName());
        System.out.println(c);
        System.out.println(((Object)c).getClass().getSimpleName());
        System.out.println(d);
        System.out.println(((Object)d).getClass().getSimpleName());
        System.out.println(e);
        System.out.println(((Object)e).getClass().getSimpleName());
    }
}

Output

10
Integer
2.5
Float
2.5
Double
abc
String
true
Boolean

When defining variables, be sure to write the data type
type int is a 32-bit integer data type
The float type is a data type for 32-bit floating-point numbers
double type is a data type for 64-bit floating-point numbers
String type is a string data type
boolean is a boolean data type
Primitive types: int, float, double, and boolean have corresponding class types: Integer, Float, Double, and Boolean.
Primitive types are not classes, but data types that contain only their data
    For example, type int has only 32 bits of data representing an integer, and there are no methods or fields as a class.


Bit operation

Python

def main():
    print(1|2|4|8|16|32|64|128)

if __name__ == '__main__':
    main()

Output

255

The bit OR operation is performed by |
The AND operation of the bits is &

Java

public class myprogram{
    public static void main(String [] args){
        System.out.println(1|2|4|8|16|32|64|128);
    }
}

Output

255

The bit OR operation is performed by |
The AND operation of the bits is &


Four arithmetic operations and increment operators

Python

def main():
    print(20%7)
    print(3**2)
    a=10
    a+=1
    print(a)

if __name__ == '__main__':
    main()

Output

6
9
11

The four arithmetic operators are +-*/
The remainder of the division is %.
Power (power) is **.
There is no operator named ++.

Java

public class myprogram{
    public static void main(String [] args){
        System.out.println(20%7);
        System.out.println(Math.pow(3,2));
        int a=10;
        a++;
        System.out.println(a);
    }
}

Output

6
9.0
11

The four arithmetic operators are +-*/
The remainder of the division is %.
Use Math.pow function for powers
The ++ operator is an operator that increases by 1


Integer division

Python

def main():
    print(5//2)
    print(5/2)

if __name__ == '__main__':
    main()

Output

2
2.5

Integer division is //.
Floating point numbers can be divided by /.

Java

public class myprogram{
    public static void main(String [] args){
        System.out.println(5/2);
        System.out.println(5.0/2.0);
    }
}

Output

2
2.5

Both 5 and 2 are integers, so 5/2 is integer division
Both 5.0 and 2.0 are floating-point numbers, so 5.0/2.0 is the division of floating-point numbers


Array

Python

def main():
    a=[0,0]
    a[0]=1
    a[1]=2
    print(a[0])
    print(a[1])

if __name__ == '__main__':
    main()

Output

1
2

List

Java

public class myprogram{
    public static void main(String [] args){
        int[] a=new int[2];
        a[0]=1;
        a[1]=2;
        System.out.println(a[0]);
        System.out.println(a[1]);
    }
}

Output

1
2

Array
Allocate memory using new operation


Data type conversion

Python

def main():
    a=5
    b=2
    print(float(a)/float(b))

    c=[0,0]
    c[0]=1
    c[1]=2
    d=1.01
    print(c[int(d)])

if __name__ == '__main__':
    main()

Output

2.5
2

Convert data type using int or float

Java

public class myprogram{
    public static void main(String [] args){
        int a=5;
        int b=2;
        System.out.println((double)a/(double)b);

        int[] c=new int[2];
        c[0]=1;
        c[1]=2;
        double d=1.01;
        System.out.println(c[(int)d]);
    }
}

Output

2.5
2

Convert data type using int or double


Connecting strings

Python

def main():
    a='a'
    b='b'
    c=0
    print(a+b)
    print(a+str(c))

if __name__ == '__main__':
    main()

Output

ab
a0

Connect strings using +
Numeric values are converted to str type before concatenation.

Java

public class myprogram{
    public static void main(String [] args){
        String a="a";
        String b="b";
        int c=0;
        System.out.println(a+b);
        System.out.println(a+c);
    }
}

Output

ab
a0

Connect strings using +
Numerical values can be linked as they are.


Formatted strings

Python

def main():
    a=15
    print('a%03d'%a)
    b='a% 3d'%a
    print(b)

if __name__ == '__main__':
    main()

Output

a015
a 15

If you write %d in a string, followed by a %, followed by an integer, the number becomes a string

Java

public class myprogram{
    public static void main(String [] args){
        int a=15;
        System.out.printf("a%03d\n",a);
        String b=String.format("a% 3d",a);
        System.out.println(b);
    }
}

Output

a015
a 15

Using the printf function, write %d in the string and an integer as the second argument, and the number will be output as a string
To assign to a variable, use the String.format function


Array initial values

Python

def main():
    a=[1,2]
    print(a[0])
    print(a[1])

if __name__ == '__main__':
    main()

Output

1
2

Create a list and assign it to a variable

Java

public class myprogram{
    public static void main(String [] args){
        int[] a=new int[]{1,2};
        System.out.println(a[0]);
        System.out.println(a[1]);
    }
}

Output

1
2

Write the value to be assigned to the array after the new operator


multidimensional array

Python

def main():
    a=[[1,2],[3,4]]
    print(a[0][1])
    b=[['' for _ in range(2)] for _ in range(2)]
    b[0][0]='a'
    b[0][1]='b'
    b[1][0]='c'
    b[1][1]='d'
    print(b)

if __name__ == '__main__':
    main()

Output

2
[['a', 'b'], ['c', 'd']]

Example of a 2x2 list

Java

import java.util.*;
public class myprogram{
    public static void main(String [] args){
        int[][] a=new int[][]{{1,2},{3,4}};
        System.out.println(a[0][1]);
        String[][] b=new String[2][2];
        b[0][0]="a";
        b[0][1]="b";
        b[1][0]="c";
        b[1][1]="d";
        System.out.println(Arrays.deepToString(b));
    }
}

Output

2
[[a, b], [c, d]]

Example of a 2x2 array


Number of array elements

Python

def main():
    a=[1,2]
    print(len(a))

if __name__ == '__main__':
    main()

Output

2

The len function can be used to determine the length of a list.

Java

public class myprogram{
    public static void main(String [] args){
        int[] a=new int[]{1,2};
        System.out.println(a.length);
    }
}

Output

2

Arrays are also a class and have a length field, which can be used to determine the length of the array


Using created objects

Python

def main():
    a=[1,2][0]
    print(a)

if __name__ == '__main__':
    main()

Output

1

Created objects can be used even in the middle of code

Java

public class myprogram{
    public static void main(String [] args){
        int a=(new int[]{1,2})[0];
        System.out.println(a);
    }
}

Output

1

Created objects can be used even in the middle of code


Import library

Python

import numpy as np

def main():
    print(np.random.randint(10))

if __name__ == '__main__':
    main()

Output

1

import imports library

Java

import java.util.*;
public class myprogram{
    public static void main(String [] args){
        Random rnd=new Random();
        System.out.println(rnd.nextInt(10));
    }
}

Output

5

import imports library


Constructor

Python

import numpy as np

def main():
    a=np.ndarray((2,2))
    b=np.empty((2,2))
    c=np.zeros((2,2))
    d=np.array([[1,2],[3,4]])
    print(type(a))
    print(type(b))
    print(type(c))
    print(type(d))

if __name__ == '__main__':
    main()

Output

<class 'numpy.ndarray'>
<class 'numpy.ndarray'>
<class 'numpy.ndarray'>
<class 'numpy.ndarray'>

Constructor is called upon object creation
The () after the data type specifies the argument to be passed to the constructor.
Many Python libraries are not recommended to create objects by calling constructors
For example, when creating a numpy matrix, its class name is ndarray, but it is not recommended to use ndarray to create matrices
    It is recommended to use empty, zeros, arrays, etc. when creating numpy matrices

Java

import java.util.*;
public class myprogram{
    public static void main(String [] args){
        String a=new String();
        String b=new String("b");
        System.out.println(a);
        System.out.println(b);
    }
}

Output


b

Constructor is called upon object creation
The () after the data type specifies the argument to be passed to the constructor.


if statement

Python

def main():
    a=1
    b=2
    c=3
    if a==1 and b==2:
        print('a1b2')
    if a==2:
        print('a2')
    elif a==1 or b==1:
        print('a1')
    else:
        print('a?')
    if c>b>a: print('correct')
    else: print('wrong')
if __name__ == '__main__':
    main()

Output

a1b2
a1
correct

Range of if statements is indicated by indentation
elif stands for else if.
Logical operators are and, or, etc.
Multiple comparison operators may be strung together as in c>b>a

Java

public class myprogram{
    public static void main(String [] args){
        int a=1;
        int b=2;
        int c=3;
        if(a==1&&b==2)System.out.println("a1b2");
        if(a==2)System.out.println("a2");
        else if(a==1||b==1)System.out.println("a1");
        else System.out.println("a?");
        if(c>b&&b>a)System.out.println("correct");
        else System.out.println("wrong");
    }
}

Output

a1b2
a1
correct

The range of an if statement is a single command or the range enclosed by {}.
else if for elif
Logical operators are &&, ||, etc.
You cannot connect multiple comparison operators like c>b>a


conditional operator

Python

def main():
    a = 7
    b = 'even' if a % 2 == 0 else 'odd'
    print(b)

if __name__ == '__main__':
    main()

Output

odd

if statement in the middle of an imperative statement
(if true) if (condition) else (if false)

Java

public class myprogram{
    public static void main(String [] args){
        int a=7;
        String b = (a%2==0) ? "even" : "odd";
        System.out.println(b);
    }
}

Output

odd

conditional operator
(Condition) ? (if true) : (if false)


while statement

Python

def main():
    a=0
    while True:
        print(a)
        a+=1
        if a>=10:
            break
if __name__=='__main__':
    main()

Output

0
1
2
3
4
5
6
7
8
9

The range of the while statement is indicated by indentation.

Java

public class myprogram{
    public static void main(String [] args){
        int a=0;
        while(true){
            System.out.println(a);
            a++;
            if(a>=10)break;
        }
    }
}

Output

0
1
2
3
4
5
6
7
8
9

The range of the while statement is a single instruction or the range enclosed by {}.


for statement

Python

def main():
    for i in range(0,10):
        print(i)

if __name__ == '__main__':
    main()

Output

0
1
2
3
4
5
6
7
8
9

The range of the for statement is indicated by indentation.
All for statements in Python are range-based for statements (foreach statements)
range(0,10) is the range between 0 and 10, 1 by 1

Java

public class myprogram{
    public static void main(String [] args){
        for(int i=0;i<10;i++){
            System.out.println(i);
        }
    }
}

Output

0
1
2
3
4
5
6
7
8
9

The range of the for statement is a single instruction or the range enclosed by {}.
for(○;△;×)
○ is the statement that is called the first time before entering the loop
× is a statement called at the end of each loop
△ is a conditional expression examined at the beginning of the loop
If this condition is met, the loop continues
If not satisfied, exit the loop


Function

Python

def myfunc(a,b,c):
    a+=1
    b+=1
    c[0]+=1
    c[1]+=1
    return str(a)+"+"+str(b)+"="+str(a+b)
def main():
    x=1
    y=2
    z=[3,4]
    w=myfunc(x,y,z)
    print(x)
    print(y)
    print(z[0])
    print(z[1])
    print(w)
if __name__ == '__main__':
    main()

Output

1
2
4
5
2+3=5

Usage and properties of functions are almost the same as general programming languages
a and b do not affect the function to the outside
The contents of c affect everything outside the function.

Java

public class myprogram{
    private static String myfunc(int a,int b,int[] c){
        a++;
        b++;
        c[0]++;
        c[1]++;
        return new String(a+"+"+b+"="+(a+b));
    }
    public static void main(String [] args){
        int x=1;
        int y=2;
        int[] z=new int[]{3,4};
        String w=myfunc(x,y,z);
        System.out.println(x);
        System.out.println(y);
        System.out.println(z[0]);
        System.out.println(z[1]);
        System.out.println(w);
    }
}

Output

1
2
4
5
2+3=5

Usage and properties of functions are almost the same as general programming languages
a and b do not affect the function to the outside
The contents of c affect everything outside the function.


Local and global variables

Python

a=1
def myfunc1(a):
    a=2
def myfunc2():
    a=3
def myfunc3():
    global a
    a=4
def main():
    global a
    print(a)
    a=5
    print(a)
    myfunc1(a)
    print(a)
    myfunc2()
    print(a)
    myfunc3()
    print(a)
    while True:a=6;break
    print(a)
if __name__ == '__main__':
    main()

Output

1
5
5
5
4
6

a=1 a is used by myfunc3 and main as a global variable
a in myfunc1 is a kind of value passing, so it does not affect the caller of the function
a in myfunc2 is a local variable and its scope is only within myfunc2, so it does not affect outside myfunc2

Java

public class myprogram{
    private static int a=1;
    private static void myfunc1(int a){
        a=2;
    }
    private static void myfunc2(){
        int a=3;
    }
    private static void myfunc3(){
        a=4;
    }
    public static void main(String [] args){
        System.out.println(a);
        a=5;
        System.out.println(a);
        myfunc1(a);
        System.out.println(a);
        myfunc2();
        System.out.println(a);
        myfunc3();
        System.out.println(a);
        while(true){a=6;break;}
        System.out.println(a);
        while(true){int a=7;break;}
        System.out.println(a);
    }
}

Output

1
5
5
5
4
6
6

a=1 a is used by myfunc3 and main as a global variable (actually, field (member variable))
a in myfunc1 is a value passing, so it does not affect the caller of the function
a in myfunc2 is a local variable and its scope is only within myfunc2, so it does not affect outside myfunc2
Scope of variable enclosed by { and }
Variables defined inside { and } have precedence over variables defined outside { and }.


List and generics

Python

def main():
    a=[]
    a.append(1)
    a.append(2)
    b=[]
    b.append('x')
    b.append('y')
    print(a)
    print(b)
if __name__=='__main__':
    main()

Output

[1, 2]
['x', 'y']

Adding an element to a list with the append function
The type of the elements of the list is not specified.

Java

import java.util.*;
public class myprogram{
    public static void main(String [] args){
        ArrayList<Integer> a=new ArrayList<Integer>();
        a.add(1);
        a.add(2);
        ArrayList<String> b=new ArrayList<String>();
        b.add("x");
        b.add("y");
        System.out.println(a.toString());
        System.out.println(b.toString());
    }
}

Output

[1, 2]
[x, y]

Adding an element to a list with the add function
The type of the list element is specified by <>


List and sort

Python

def main():
    a=[]
    a.append(30)
    a.append(40)
    a.append(20)
    a.append(10)
    a.append(50)
    print(a)
    a.sort()
    print(a)

if __name__ == '__main__':
    main()

Output

[30, 40, 20, 10, 50]
[10, 20, 30, 40, 50]

sort funciton sorts

Java

import java.util.*;
public class myprogram{
    public static void main(String [] args){
        ArrayList<Integer> a=new ArrayList<Integer>();
        a.add(30);
        a.add(40);
        a.add(20);
        a.add(10);
        a.add(50);
        System.out.println(a.toString());
        a.sort(null);
        System.out.println(a.toString());
    }
}

Output

[30, 40, 20, 10, 50]
[10, 20, 30, 40, 50]

sort function sorts


Class inheritance

Python

class animal:
    def isanimal(self):
        return True
    def cry(self):
        print('undefined')
class cat(animal):
    def cry(self):
        print('meow')
class dog(animal):
    def cry(self):
        print('bowwow')
class pig(animal):
    def cry(self):
        print('oink')
def main():
    a=cat()
    b=dog()
    c=pig()
    a.name='calico cat'
    b.name='shiba inu'
    c.name='iberian pig'
    d=[a,b,c]
    for e in d:
        print(type(e))
        print(e.isanimal())
        print(e.name)
        e.cry()

if __name__=='__main__':
    main()

Output

<class '__main__.cat'>
True
calico cat
meow
<class '__main__.dog'>
True
shiba inu
bowwow
<class '__main__.pig'>
True
iberian pig
oink

Example of cat, dog, and pig classes inheriting from animal class

Java

public class myprogram{
    private static class animal{
        public String name;
        public boolean isanimal(){
            return true;
        }
        public void cry(){
            System.out.println("undefined");
        }
    }
    private static class cat extends animal{
        public void cry(){
            System.out.println("meow");
        }
    }
    private static class dog extends animal{
        public void cry(){
            System.out.println("bowwow");
        }
    }
    private static class pig extends animal{
        public void cry(){
            System.out.println("oink");
        }
    }
    public static void main(String [] args){
        cat a=new cat();
        dog b=new dog();
        pig c=new pig();
        a.name="calico cat";
        b.name="shiba inu";
        c.name="iberian pig";
        animal[] d=new animal[]{a,b,c};
        for(animal e:d){
            System.out.println(e.getClass().getSimpleName());
            System.out.println(e.isanimal());
            System.out.println(e.name);
            e.cry();
        }
    }
}

Output

cat
true
calico cat
meow
dog
true
shiba inu
bowwow
pig
true
iberian pig
oink

Example of cat, dog, and pig classes inheriting from animal class


Back