Go language features explained for Java Developer

Go language features explained for Java Developer

Some facts about Go Language compared with Java

  1. Go started at Google, and Java at Sun Microsystem
  2. 17 vs 29 years of maturity in 2024
  3. Go is based on C program syntax achieves max effects with min means but Java JRE is written in C
  4. Go started as system programming language but widely accepted now as general-purpose language, Java renamed from Oak
  5. Both are Typed language
  6. Go proven to have better performance than Java
  7. Go is a small, simple, easy to learn, easy to use and really fabulous language
  8. Go provides standard libraries comes with “Batteries included”?:) and decentered libraries but Java usages centralized approach like Maven
  9. Go is kind of reduced set or stripped features of Java
  10. No VM in Go but Java is based JVM
  11. Go usage struct for complex data type and great support for JSON data handling and it is easy to implement with struct
  12. Go implements some of the object-oriented features in very unusual approach
  13. Go supports Pointers and Address unlike Java
  14. No inheritance in Go, complex object behaviors are created by composition
  15. No Method Overloading in Go
  16. Two functions/methods cannot have same name in a package in Go
  17. The panic and recover feature in Go are similar to the Exception handling in Java
  18. Go concurrency model is based on Go routine something different than thread
  19. Go also support automatic memory management
  20. Go playground on web for playing with code and sharing

Side by side comparison

1. Java and Go both are strongly Typed

  • Java: Strongly typed, with explicit type declarations enforced at compile time.
  • Go: Also strongly typed, but offers type inference, allowing for more concise variable declarations and makes little easy by short variable ( := ) declaration

2. Package Management:??

  • Java: Relies on tools like Maven etc. for dependency management, with centralized repo for libraries and packages.????
  • Go: Utilizes a decentralized approach to package management with the go get command and the go.mod file, allowing us to specify and manage dependencies within their projects.

Code Organization?in Go

  1. Workspace
  2. Module - Something like Maven for Java
  3. Package

  • Go package has no dependency on folder(s) name of go source, but one folder must have only one package.
  • Go package always short name, without dot (.) unlike java and has no relation with folder name.
  • Go package while importing the package, need module name and folder(s) where package exist.
  • Go program Execution always starts with main package and function main.

Code structure and naming convention in Go

3. Access Control

  • Java - Access control by declaring variables, methods and class as public, private, protected and default.
  • Go - Access control by Private and Public is by the first letter of the name for variable or function both. If the letter is lowercase, it is private. If it is uppercase, it is public. The scope of a private function/method/type is the package in which it is defined.

4. Unused variable and Blank identifier variable

  • Java - No complain and alright to define unused variable or not receiving return values of method.
  • Go - Unused variable, unused import gives compile time error but that can be replaced with underscore ( _ ) known as blank identifier.

5. Initializing variable or perform initialization during code load time

  • Java- When class is loaded in memory, static variables or code block is initialized.?
  • Go- Supports init() method that is called when program is imported. These?init()?functions can be used within a?package?block and regardless of how many times that package is imported, the?init()?function will only be called once.? if just want to call init() method then import package with Blank Identifier

6. Global variable

  • Java: Java got access modifier like public, private, protected and default attached to and even volatile to update the value from different threads update
  • Go: Global variables in Go are editable. Any code in any of the functions can edit the global variable.

7. Pointer and Address

  • Java references:?Automatically managed memory; pointing to an object abstracts away the memory address.
  • Go pointers:?Explicitly point to memory addresses; changes made through a pointer affect the original variable.

Play with Pointers: https://go.dev/play/p/sLvPX4ngymO

8. Object-Oriented Programming (OOP)

  • Java: Purely object-oriented, where everything is an object and classes are fundamental.???
  • Go: Supports some OOP principles like structs and methods, but also encourages composition over inheritance., Go implements it for structs only in unique way

Go supports,

  1. Function
  2. Method: Example: https://go.dev/play/p/wU3XAWg_Fhu, Method is associated with. A function that accepts a special receiver argument is a method and receiver is instance of struct. The receiver is declared between the method name and the func keyword in its own parameter list.
  3. Interface: https://go.dev/tour/methods/10. This helps implementing something polymorphism by using method.

9. Method overloading and overriding

  1. Java: Purely object-oriented so overloading and overriding are key features of language
  2. Go: No method Overloading and two functions/methods cannot have same name in a package in Go, except init()

10. Error/Exception Handling

  • Java: Utilizes checked exceptions, requiring methods to declare the exceptions they might throw.???
  • Go: Emphasizes error handling via return values rather than exceptions, with no support for checked exceptions.

  1. In Go, errors are returned “normally” from a function and you as the caller are responsible for handling them.
  2. Example: https://go.dev/play/p/qitccG6T7ge

11. Logging

  • Java: there are many loggings' libraries support including jdk logger and log4j???
  • Go: provide basic logging, and recent version supports slog (structured logging). Rolling file and some of features need to use third party library support.

12. Unit Test

  • Java: ?JUnit is an open-source Unit testing framework for java
  • Go: Unit testing is an inbuilt tool/command for conducting automated tests

Playground https://go.dev/play/p/e08fPhaWgDF

13. Generic

  • Java: Has generics, allowing classes and methods to work with objects of various types in a type-safe manner.???
  • Go: Lacks generics, but developers can achieve similar functionality using interfaces and type assertions.

Generic: https://go.dev/play/p/e08fPhaWgDF

14. Reflection

  • Java: Supports reflection, allowing programs to inspect and modify their own structure at runtime.???
  • Go: Has limited support for reflection compared to Java, primarily used for inspecting types and accessing struct fields

Example: https://go.dev/play/p/gs_YddjW6v9

15. Annotation

  • Java: Supports annotations for adding metadata to classes, methods, and other program elements, used for various purposes like configuration and code generation etc.
  • Go: Annotation is a go package that allows parsing and read?Java Style?annotation strings e.x?@SomeAnnotation(param="value"), this package is used by?go-service?to read and parse annotations in comments.

16. Concurrency Model

  • Java: Uses threads for concurrency, with libraries like java.util.concurrent for synchronization and coordination.??
  • Go: Offers built-in support for concurrency with go-routines and channels, making it easier to write concurrent programs compared to Java's thread-based model.

Go routine is something like Virtual Threads (part of JDK 21)

17. Stacktrace and dump

  • Java: thread dump and stack dump.??
  • Go: supports Runtime API for Stacktrace dump

  1. Similar to Java, SIGQUIT (kill -3 <GO_PROCESS_PID_ID>? or if process running prompt is available then? press?^\?keys (?CTRL+\?)) can be used to print a stack trace of a Go program and its goroutines. A key difference, however, is that by default sending SIGQUIT to Java programs do not terminate them, while Go programs do exit. This approach requires no code change to print a stack trace of all goroutines of existing programs. e.g.

$ kill  -3 24456        

https://pkg.go.dev/runtime


18. Memory management and GC

  • Java: Garbage collection is handled by the JVM's garbage collector, which is optimized for Java's memory management.? ?
  • Go: Has its own garbage collector optimized for concurrent execution, with control over memory allocation and deallocation. Go implements concurrent, Tri-Color block (White-Balck-Gray), Mark and Sweep policy and uniquely implemented stack and heap memory management.
  • Garbage collection in Go
  • Manages memory allocation and deallocation automatically.
  • Picks up anything out of scope or nil
  • GC is triggered based on trigger ratio
  • GC runs concurrently using mark and sweep, Tri-Color block (White-Balck-Gray)
  • The GOGC is environment variable sets the initial garbage collection target percentage. A garbage collection is triggered when the ratio of freshly allocated data to live data remaining after the previous collection reaches this percentage. The default is GOGC=1OO.
  • Setting GOGC= off disables the garbage collector entirely.

runtime package - runtime - Go Packages

Google search

19. Profiling

  • Java: heap dump and profiling code using profiling API
  • Go: comes with inbuild Profiler and very efficient but not seen heap dump.?https://go.dev/doc/diagnostics

20. Execution Model

  • Java: Code is typically executed on the Java Virtual Machine (JVM), providing platform independence but using? GraalVM, Java code can be converted into native binary? ?
  • Go: Code is compiled directly to machine code, resulting in faster execution and simpler deployment, but sacrificing some platform independence so it's Fast native code

Rishi Sahni

Engineering Leader | Strategic Accounts | Growth & Innovation focused

10 个月

Great read

回复

要查看或添加评论,请登录

Shambhu Kumar Sinha的更多文章

社区洞察

其他会员也浏览了