📕
Dan Fitz's Notes
  • README
  • Ai
    • Supervised Machine Learning
      • Introduction To Machine Learning
      • Regression With Multiple Input Variables
      • Classification
  • Csharp
    • C Sharp Advanced
      • Generics
      • Delegates
      • Lambda Expressions
      • Events
    • C Sharp Fundamentals
      • Intro To C
      • Primitive Types And Expressions
      • Non Primitive Types
      • Control Flow
      • Arrays And Lists
      • Working With Dates
      • Working With Text
      • Working With Files
      • Debugging Applications
    • C Sharp Intermediate
      • Classes
      • Association Between Classes
      • Inheritance
      • Polymorphism
      • Interfaces
  • Java
    • Inheritance Data Structures Java
      • Inheritance Polymorphism Using Overriding And Access Modifiers
      • Abstract Classes And Debugging
      • File I O And Exceptions
      • Collections Maps And Regular Expressions
    • Intro To Java
      • Introduction To Java Classes And Eclipse
      • Unit Testing Arrays And Array Lists
      • Static Variables Methods And Polymorphism Using Overloading
  • Javascript
    • Algorithms Data Structures
      • Big O Notation
      • Analyzing Performance Of Arrays And Objects
      • Problem Solving Approach
      • Problem Solving Patterns
      • Recursion
      • Searching Algorithms
      • Bubble Selection And Insertion Sort
      • Merge Sort
      • Quick Sort
      • Radix Sort
      • Data Structures Introduction
      • Singly Linked Lists
      • Doubly Linked Lists
      • Stacks And Queues
      • Binary Search Trees
      • Tree Traversal
      • Binary Heaps
    • Complete Nodejs
      • Understanding Node.js
      • REST AP Is And Mongoose
      • API Authentication And Security
      • Node.js Module System
      • File System And Command Line Args
      • Debugging Node.js
      • Asynchronous Node.js
      • Web Servers
      • Accessing API From Browser
      • Application Deployment
      • Mongo DB And Promises
    • Complete React Native
      • Working With Content
      • Building Lists
      • Navigating Users Between Screens
      • State Management
      • Handling Screen Layout
      • Setting Up An App
      • More On Navigation
      • Advanced Statement Management With Context
      • Building A Custom Express API
      • In App Authentication
    • Epic React
      • React Fundamentals
      • React Hooks
      • Advanced React Hooks
      • Advanced React Patterns
      • React Performance
    • Fireship Firestore
      • Firestore Queries And Data Modeling Course
      • Model Relational Data In Firestore No SQL
    • Functional Light Javascript
      • Intro
      • Function Purity
      • Argument Adapters
      • Point Free
      • Closure
      • Composition
      • Immutability
      • Recursion
      • List Operations
      • Transduction
      • Data Structure Operations
      • Async
    • Js Weird Parts
      • Execution Contexts And Lexical Environments
      • Types And Operators
      • Objects And Functions
      • Object Oriented Java Script And Prototypal Inheritance
      • Defining Objects
    • Mastering Chrome Dev Tools
      • Introduction
      • Editing
      • Debugging
      • Networking
      • Auditing
      • Node.js Profiling
      • Performance Monitoring
      • Image Performance
      • Memory
    • React Complete Guide
      • What Is React
      • React Basics
      • Rendering Lists And Conditionals
      • Styling React Components
      • Debugging React Apps
      • Component Deep Dive
      • Building A React App
      • Reaching Out To The Web
      • Routing
    • React Testing
      • Intro To Jest Enzyme And TDD
      • Basic Testing
      • Redux Testing
      • Redux Thunk Testing
    • Serverless Bootcamp
      • Introduction
      • Auction Service Setup
      • Auction Service CRUD Operations
      • Auction Service Processing Auctions
    • Testing Javascript
      • Fundamentals Of Testing
      • Static Analysis Testing
      • Mocking Fundamentals
      • Configuring Jest
      • Test React Components With Jest And React Testing Library
    • Typescript Developers Guide
      • Getting Started With Type Script
      • What Is A Type System
      • Type Annotations In Action
      • Annotations With Functions And Objects
      • Mastering Typed Arrays
      • Tuples In Type Script
      • The All Important Interface
      • Building Functionality With Classes
    • Web Performance With Webpack
      • Intro
      • Code Splitting
      • Module Methods Magic Comments
  • Other
    • Algo Expert
      • Defining Data Structures And Complexity Analysis
      • Memory
      • Big O Notation
      • Logarithm
      • Arrays
      • Linked Lists
      • Hash Tables
      • Stacks And Queues
      • Strings
      • Graphs
      • Trees
    • Aws Solutions Architect
      • AWS Fundamentals IAM EC 2
    • Fundamentals Math
      • Numbers And Negative Numbers
      • Factors And Multiples
      • Fractions
    • Mysql Bootcamp
      • Overview And Installation
      • Creating Databases And Tables
      • Inserting Data
      • CRUD Commands
      • The World Of String Functions
      • Refining Our Selections
      • The Magic Of Aggregate Functions
    • Random Notes
      • Understanding React Hooks
  • Python
    • Data Analysis Using Python
      • Loading Querying And Filtering Data Using The Csv Module
      • Loading Querying Joining And Filtering Data Using Pandas
      • Summarizing And Visualizing Data
    • Intro To Python
      • Course Introduction Intro To Programming And The Python Language Variables Conditionals Jupyter Notebook And IDLE
      • Intro To Lists Loops And Functions
      • More With Lists Strings Tuples Sets And Py Charm
      • Dictionaries And Files
Powered by GitBook
On this page
  • Java basics
  • Syntax
  • Data types
  • String vs. char
  • Variables
  • Printing
  • Iteration
  • Boolean operators and conditionals
  • Getting input
  • Comments and Javadocs
  • Math operations
  • Character operations
  • Casting
  • Widening vs. narrowing
  • Classes
  • Class definition basics
  • Class instantiation
  1. Java
  2. Intro To Java

Introduction To Java Classes And Eclipse

Java is compiled to binary machine code known as bytecode, leading to the following benefits:

  • Portable because different machines and operating systems can run Java

  • Runs faster and more efficiently due to optimizations during compilation

  • Catches errors early on during compilation

Java basics

Syntax

Things to consider related to Java syntax:

  • Camelcase is the preferred variable naming convention

  • Lines of code are determined via the semicolon ;, and code blocks are determined using curly braces {}

  • As a result, indentation/new lines/whitespace don't matter at all and are purely for readability

Data types

Some primitive data types:

  • int

  • float

  • double (larger, more precise float)

  • byte, short, long (integer sizes with 8, 16, or 64 bits)

  • boolean

  • char

Some common non-primitive data types:

  • String (an Object)

  • Integer, Boolean, Double (wrapper classes for the primitive data types)

Pro tip: To know the data type of a value, you have access to the getClass method.

String someString = "hello";
someString.getClass(); // returns class java.lang.String

// Some data types require casting TO an Object first
int someInt = 1;
((Object)someInt).getClass(); // returns class java.lang.Integer

String vs. char

In Java, single quotes are for char, and double quotes are for String:

String firstName = "Dan";
char grade = 'A';

Note that with Strings, you can concatenate them with +:

String sentence = "I am " + 8 + " years old";

Note: As you can see, Java automatically casts data types to Strings during concatenation.

Variables

You can declare a variable with and without values:

// With values
int count = 0;
String firstName = "Dan";

// Without values
float cost;
String lastName;

cost = 5.1; // set later!

Note: You always include a pre-defined data type with a variable declaration. You cannot change the data type of a variable. This means Java is statically typed.

Printing

To print data, you have the following options:

  • System.out.println(x) prints something and ends the line

  • System.out.print(x) prints something and doesn't end the line

Important: If you create your own custom Objects, you will need to create a custom toString method in your class, so the System.out methods know how to print your Objects.

public class Customer {
  String name;
  public Customer(String name) {
    this.name = name;
  }
  
  // must return string
  public String toString() {
    return this.name;
  }
}

Iteration

while loops and for loops are just like JavaScript:

int i = 0;
while (i < 10) {
  i++;
  // Loop 10 times
}

for (int j = 0; j < 10; i++) {
  // Loop 10 times
}

Boolean operators and conditionals

Boolean operators and conditionals are pretty much the same as JavaScript too:

  • && and

  • || or

  • ! not

  • == equal

  • != not equal

boolean isEven = x % 2 == 0;
if (isEven) {
  // ...
} else {
  // ...
}

Note: When comparing Objects like Strings, you need to use the equals method instead.

"abc".equals("abc");

Pro tip: When using the equals method, it's best to use the known String first. If you do it to an unknown String (i.e. a String that might be null), you'll get an error because the equals method won't exist.

Pro tip 2: When you're building custom Objects, it's for this reason that you usually want to build out your own custom equals methods for them.

Getting input

Getting input from a user is as simple as:

import java.util.Scanner;

Scanner scan = new Scanner(System.in); // System.in means input comes from keyboard

int num = scan.nextInt(); // reads next input as an int
String str = scan.next(); // reads next input as a string
String line = scan.nextLine(); // reads next line


scan.close(); // always close your scanner!

Comments and Javadocs

Comments use the same syntax as JavaScript:

// Comment type 1

/* Comment type 2
   (also multi-line!)
*/

Just like Python's docstrings, you also can add Javadocs right before a variable, function, or class:

/**
 * Returns sum of two given numbers
 * @param firstNum First value to add
 * @param secondNum Second value to add
 * @return Sum of values
 */
public int getSum(int firstNum, int secondNum) {
  return firstNum + secondNum;
}

Math operations

Math operations are all pretty standard:

  • + for addition

  • - for subtraction

  • * for multiplication

  • / for division

  • % for modulus

Character operations

Here's some common character/string operations you are likely to perform:

// Get a char in a String
String str = "Dan";
char secondChar = str.charAt(1);

// Convert String to array of chars
Char[] chars = "Dan".toCharArray();

// Check that char is a letter
Character.isLetter('d');

// Check that char is uppercase or lowercase
Character.isUpperCase('d');
Character.isLowerCase('d');

// Convert char to uppercase or lowercase
Character.toUpperCase('d');
Character.toLowerCase('d');

// Compare chars
's' < 't';
's' == 't';

Casting

Here's some basic casting operations you are likely to perform:

  • int to String

    • Integer.toString(int)

    • String.valueOf(int)

  • String to int

    • Integer.parseInt(str)

Alternatively, you can cast using the following syntax: (typeToCast) value.

Widening vs. narrowing

Some data types are subsets of other data types. For example, integers are a subset of doubles. That means all integers are doubles, but not all doubles are integers.

Widening is the act of casting a sub-data type to a wider data type: an integer to a double. Narrowing is casting a data type to one of its subsets: a double to an integer.

Widening and narrowing typically happens when passing arguments to methods:

public class Customer {
  public static void buy(int i) {
    // ...
  }
  
  public static void main(String args[]) {
    Customer.buy(5.0); // example of narrowing!
  }
}

In Java, widening is legal, while narrowing is illegal.

Classes

Everything in Java is class-based. As a result (like C#), you always have to write at least one class to run a Java program.

Think of classes as objects that represent a new data type. You need to create an instance of the class to use the class though.

Classes consist of:

  • Fields that hold data, the state of the object

  • Constructors that run when creating a new class instance

  • Methods that encapsulate computations the object can perform

Class definition basics

// public is an access modifier that makes the class
// visible/available to any other part of the program
public class Person {
  // Fields
  String name; // field declaration
  int age = 0; // field declaration, initially set to 0
 
  // Constructor
  public Person(parameters) {
    // things to do when class instance is created
    // parameters are passed in during instantiation
  }
  
  // Methods
  boolean isAdult() {
    return age >= 18;
  }
  void voteAsync() {
    // Do some stuff that doesn't require returning anything
  }
}

Class instantiation

Creating a new class instance is pretty much as expected:

Person person = new Person("Dan", 29);
PreviousIntro To JavaNextUnit Testing Arrays And Array Lists

Last updated 3 years ago