Java Basics
Pages 616
- Home
- Home
- 10 Steps To Plan Better So You Can Write Less Code
- 5 Steps to organizing a successful Campsite event
- Academic Honesty Policy
- accessibility 101
- Accessing the database from your frontend
- Adding Environment Variables
- Adding Snippets In Sublime Text
- Adding Snippets To Sublime Text
- Advantages and Disadvantages of Javascript
- Algorithm Arguments Optional
- Algorithm Binary Agents
- Algorithm Boo who
- Algorithm Caesars Cipher
- Algorithm Check for Palindromes
- Algorithm Chunky Monkey
- Algorithm Confirm the Ending
- Algorithm Convert HTML Entities
- Algorithm Diff Two Arrays
- Algorithm DNA Pairing
- Algorithm Drop It
- Algorithm Everything be True
- Algorithm Exact Change
- Algorithm Factorialize a Number
- Algorithm Falsy Bouncer
- Algorithm Find The Longest Word in a String
- Algorithm Finders Keepers
- Algorithm Friendly Date Ranges
- Algorithm Inventory Update
- Algorithm Make a Person
- Algorithm Map the Debris
- Algorithm Missing letters
- Algorithm Mutations
- Algorithm No Repeats Please
- Algorithm Pairwise
- Algorithm Pig Latin
- Algorithm Repeat a String Repeat a String
- Algorithm Return Largest Numbers in Arrays
- Algorithm Reverse a String
- Algorithm Roman Numeral Converter
- Algorithm Search and Replace
- Algorithm Seek and Destroy
- Algorithm Slasher Flick
- Algorithm Smallest Common Multiple
- Algorithm Sorted Union
- Algorithm Spinal Tap Case
- Algorithm Steamroller
- Algorithm Style Guide
- Algorithm Sum All Numbers in a Range
- Algorithm Sum All Odd Fibonacci Numbers
- Algorithm Sum All Primes
- Algorithm Symmetric Difference
- Algorithm Title Case a Sentence
- Algorithm Truncate a String
- Algorithm Validate US Telephone Numbers
- Algorithm Where art thou
- Algorithm Where do I belong
- Algorithms Merge Sort
- Angular Resources
- Arithmetic Operators
- Array.isArray
- August 2015 Improvements
- August Live Stream
- Back End Project Resources
- Backend file structure
- beta
- Bobby Tables
- Bonus SocketIO
- Bootstrap
- bot announce
- botdemo
- botintro
- Brownie Points
- Browser Storage
- Camper News
- camperbot
- Campsites
- Capitalize First Letter Of String
- chai
- chai assert
- chai cheat
- Challenge Access Array Data with Indexes
- Challenge Access Multi Dimensional Arrays With Indexes
- Challenge Accessing Nested Arrays In Json
- Challenge Accessing Nested Objects In Json
- Challenge Accessing Objects Properties With Bracket Notation
- Challenge Accessing Objects Properties With The Dot Operator
- Challenge Accessing Objects Properties With Variables
- Challenge Add a Negative Margin to an Element
- Challenge Add a Submit Button to a Form
- Challenge Add Alt Text to an Image for Accessibility
- Challenge Add Borders Around your Elements
- Challenge Add Different Margins to Each Side of an Element
- Challenge Add Different Padding to Each Side of an Element
- Challenge Add Elements within your Bootstrap Wells
- Challenge Add Font Awesome Icons to all of our Buttons
- Challenge Add Font Awesome Icons to our Buttons
- Challenge Add ID Attributes to Bootstrap Elements
- Challenge Add Images to your Website
- Challenge Add New Properties to a JavaScript Object
- Challenge Add Placeholder Text to a Text Field
- Challenge Add Rounded Corners with a Border Radius
- Challenge Add Two Numbers with JavaScript
- Challenge Add your JavaScript Slot Machine Slots
- Challenge Adding A Default Option In Switch Statements
- Challenge Adjust the Margin of an Element
- Challenge Adjusting the Padding of an Element
- Challenge Appending Variables to Strings
- Challenge Apply the Default Bootstrap Button Style
- Challenge Assignment With A Returned Value
- Challenge Assignment with Divided by Equals
- Challenge Assignment with Minus Equals
- Challenge Assignment with Plus Equals
- Challenge Assignment with Times Equals
- Challenge Bring your JavaScript Slot Machine to Life
- Challenge Build JavaScript Objects
- Challenge Call out Optional Actions with Button Info
- Challenge Center Text with Bootstrap
- Challenge Chaining If Else Statements
- Challenge Change Text Inside an Element Using jQuery
- Challenge Change Text with Click Events
- Challenge Change the Color of Text
- Challenge Change the CSS of an Element Using jQuery
- Challenge Change the Font Size of an Element
- Challenge Check Radio Buttons and Checkboxes by Default
- Challenge Check the Length Property of a String Variable
- Challenge Clone an Element Using jQuery
- Challenge Comment out HTML
- Challenge Comment your JavaScript Code
- Challenge Comparison With The Equality Operator
- Challenge Comparison With The Greater Than Equal To Operator
- Challenge Comparison With The Greater Than Operator
- Challenge Comparison With The Inequality Operator
- Challenge Comparison With The Less Than Equal To Operator
- Challenge Comparison With The Less Than Operator
- Challenge Comparison With The Strict Equality Operator
- Challenge Comparison With The Strict Inequality Operator
- Challenge Comparisons With The Logical And Operator
- Challenge Comparisons With The Logical Or Operator
- Challenge Concatenate Strings with .concat
- Challenge Concatenating Strings with Plus Operator
- Challenge Concatenating Strings with the Plus Equals Operator
- Challenge Condense arrays with reduce
- Challenge Construct JavaScript Objects with Functions
- Challenge Constructing Strings with Variables
- Challenge Convert JSON Data to HTML
- Challenge Count Backwards With a For Loop
- Challenge Create a Block Element Bootstrap Button
- Challenge Create a Bootstrap Button
- Challenge Create a Bootstrap Headline
- Challenge Create a Bootstrap Row
- Challenge Create a Bulleted Unordered List
- Challenge Create a Class to Target with jQuery Selectors
- Challenge Create a Custom Heading
- Challenge Create a Form Element
- Challenge Create a JavaScript Slot Machine
- Challenge Create a Set of Checkboxes
- Challenge Create a Set of Radio Buttons
- Challenge Create a Text Field
- Challenge Create an Ordered List
- Challenge Create Bootstrap Wells
- Challenge Create Decimal Numbers with JavaScript
- Challenge Declare JavaScript Objects as Variables
- Challenge Declare JavaScript Variables
- Challenge Declare String Variables
- Challenge Decrement a Number with Javascript
- Challenge Delete HTML Elements
- Challenge Delete Properties from a JavaScript Object
- Challenge Delete your jQuery Functions
- Challenge Disable an Element Using jQuery
- Challenge Ditch Custom CSS for Bootstrap
- Challenge Divide One Number by Another with JavaScript
- Challenge Escape Sequences in Strings
- Challenge Escaping Literal Quotes in Strings
- Challenge Fill in the Blank with Placeholder Text
- Challenge Filter Arrays with filter
- Challenge Find Numbers with Regular Expressions
- Challenge Find the Length of a String
- Challenge Find White Space with Regular Expressions
- Challenge Finding a Remainder in Javascript
- Challenge Generate Random Fractions with JavaScript
- Challenge Generate Random Whole Numbers with JavaScript
- Challenge Generate Random Whole Numbers within a Range
- Challenge Get Geo location Data
- Challenge Get JSON with the jQuery getJSON Method
- Challenge Give a Background Color to a Div Element
- Challenge Give Each Element a Unique ID
- Challenge Give your JavaScript Slot Machine some stylish images
- Challenge Global Scope And Functions
- Challenge Global Vs Local Scope In Functions
- Challenge Headline with the h2 Element
- Challenge House our page within a Bootstrap Container Fluid Div
- Challenge Import a Google Font
- Challenge Increment a Number with Javascript
- Challenge Inform with the Paragraph Element
- Challenge Inherit Styles from the Body Element
- Challenge Initializing Variables with the Equal Operator
- Challenge Introducing Else If Statements
- Challenge Introducing Else Statements
- Challenge Introducing Javascript Object Notation Json
- Challenge Invert Regular Expression Matches with JavaScript
- Challenge Iterate Odd Numbers With a For Loop
- Challenge Iterate over Arrays with map
- Challenge Iterate Through An Array With A For Loop
- Challenge Iterate with JavaScript For Loops
- Challenge Iterate with JavaScript While Loops
- Challenge Join Strings with .join
- Challenge Label Bootstrap Buttons
- Challenge Label Bootstrap Wells
- Challenge Learn how Script Tags and Document Ready Work
- Challenge Line up Form Elements Responsively with Bootstrap
- Challenge Link to External Pages with Anchor Elements
- Challenge Local Scope And Functions
- Challenge Make Circular Images with a Border Radius
- Challenge Make Dead Links using the Hash Symbol
- Challenge Make Images Mobile Responsive
- Challenge Make Instances of Objects with a Constructor Function
- Challenge Make Object Properties Private
- Challenge Make Unique Objects by Passing Parameters to our Constructor
- Challenge Manipulate Arrays With pop()
- Challenge Manipulate Arrays With push()
- Challenge Manipulate Arrays With shift()
- Challenge Manipulate Arrays With unshift()
- Challenge Manipulate JavaScript Objects
- Challenge Modify Array Data With Indexes
- Challenge Multiple Identical Options In Switch Statements
- Challenge Multiply Two Numbers with JavaScript
- Challenge Nest an Anchor Element within a Paragraph
- Challenge Nest Many Elements within a Single Div Element
- Challenge Nest one Array within Another Array
- Challenge Nesting For Loops
- Challenge Override All Other Styles by using Important
- Challenge Override Class Declarations by Styling ID Attributes
- Challenge Override Class Declarations with Inline Styles
- Challenge Override Styles in Subsequent CSS
- Challenge Passing Values To Functions With Arguments
- Challenge Perform Arithmetic Operations on Decimals with JavaScript
- Challenge Prefilter JSON
- Challenge Prioritize One Style Over Another
- Challenge Quoting Strings with Single Quotes
- Challenge Remove an Element Using jQuery
- Challenge Remove Classes from an element with jQuery
- Challenge Render Images from Data Sources
- Challenge Replacing If Else Chains With Switch
- Challenge Responsively Style Checkboxes
- Challenge Responsively Style Radio Buttons
- Challenge Return A Value From A Function With Return
- Challenge Return Early Pattern For Functions
- Challenge Returning Boolean Values From Functions
- Challenge Reverse Arrays with reverse
- Challenge Save your Code Revisions Forever with Git
- Challenge Say Hello to HTML Elements
- Challenge Selecting From Many Options With Switch Statements
- Challenge Set the Font Family of an Element
- Challenge Set the ID of an Element
- Challenge Sift through Text with Regular Expressions
- Challenge Size your Images
- Challenge Solution Template
- Challenge Sort Arrays with sort
- Challenge Specify How Fonts Should Degrade
- Challenge Split Strings with split
- Challenge Split your Bootstrap Row
- Challenge Store Multiple Values in one Variable using JavaScript Arrays
- Challenge Storing Values with the Equal Operator
- Challenge Style Multiple Elements with a CSS Class
- Challenge Style Text Inputs as Form Controls
- Challenge Style the HTML Body Element
- Challenge Subtract One Number from Another with JavaScript
- Challenge Target a Specific Child of an Element Using jQuery
- Challenge Target Elements by Class Using jQuery
- Challenge Target Elements by ID Using jQuery
- Challenge Target Even Numbered Elements Using jQuery
- Challenge Target HTML Elements with Selectors Using jQuery
- Challenge Target the Children of an Element Using jQuery
- Challenge Target the Parent of an Element Using jQuery
- Challenge Target the same element with multiple jQuery Selectors
- Challenge Taste the Bootstrap Button Color Rainbow
- Challenge Testing Objects For Properties
- Challenge Trigger Click Events with jQuery
- Challenge Turn an Image into a Link
- Challenge Uncomment HTML
- Challenge Understand Boolean Values
- Challenge Understand String Immutability
- Challenge Understanding Case Sensitivity in Variables
- Challenge Understanding Uninitialized Variables
- Challenge Updating Object Properties
- Challenge Use a CSS Class to Style an Element
- Challenge Use Abbreviated Hex Code
- Challenge Use an ID Attribute to Style an Element
- Challenge Use appendTo to Move Elements with jQuery
- Challenge Use Bracket Notation to Find the First Character in a String
- Challenge Use Bracket Notation to Find the Last Character in a String
- Challenge Use Bracket Notation to Find the Nth Character in a String
- Challenge Use Bracket Notation to Find the Nth to Last Character in a String
- Challenge Use Clockwise Notation to Specify the Margin of an Element
- Challenge Use Clockwise Notation to Specify the Padding of an Element
- Challenge Use Comments to Clarify Code
- Challenge Use Conditional Logic with If Else Statements
- Challenge Use CSS Selectors to Style Elements
- Challenge Use Hex Code for Specific Colors
- Challenge Use Hex Code for Specific Shades of Gray
- Challenge Use Hex Code to Color Elements Blue
- Challenge Use Hex Code to Color Elements Gray
- Challenge Use Hex Code to Color Elements Green
- Challenge Use Hex Code to Color Elements Red
- Challenge Use Hex Code to Color Elements White
- Challenge Use Hex Code to Mix Colors
- Challenge Use HTML5 to Require a Field
- Challenge Use jQuery to Modify the Entire Page
- Challenge Use Responsive Design with Bootstrap Fluid Containers
- Challenge Use RGB to Color Elements Blue
- Challenge Use RGB to Color Elements Gray
- Challenge Use RGB to Color Elements Green
- Challenge Use RGB to Color Elements Red
- Challenge Use RGB to Color Elements White
- Challenge Use RGB to Mix Colors
- Challenge Use RGB values to Color Elements
- Challenge Use Spans for Inline Elements
- Challenge Use the Bootstrap Grid to Put Elements Side By Side
- Challenge Use the Javascript Console
- Challenge Using Objects For Lookups
- Challenge Using typeof
- Challenge Warn your Users of a Dangerous Action
- Challenge Write Reusable JavaScript with Functions
- Check if an element is hidden using jQuery
- Check if element is hidden js or jquery
- Checkpoint Convert Celsius to Fahrenheit
- Checkpoint Counting Cards
- Checkpoint Golf Code
- Checkpoint Profile Lookup
- Checkpoint Record Collection
- Checkpoint Shopping List
- Checkpoint Stand In Line
- Checkpoint Word Blanks
- Clear Your Browser's Local Storage
- Clone A Specific Branch
- code case
- code formatting
- Code of Conduct
- Coding Help
- CONTRIBUTING
- Contributions Guide with Typo Demo
- Create, Upload and Link Animated GIF Image
- Creating a new API endpoint
- Creating a new directive
- Creating a New Github Issue
- Creating a new route
- css
- css selectors
- Currying
- dau
- debugging
- Debugging JavaScript with Browser DevTools
- Deleting A Branch
- demo trim
- Develop Back End Project locally and run on c9.io
- Disable Code Auto Run
- Django Start Project
- Dotnet
- Dynamic URLs using $routeParams
- Edit or Delete message
- Elixir
- emoji
- Epilogue
- equality vs identity
- example
- Fixing exports.update
- For loops Explained
- Free Code Camp Back End Development Certification
- Free Code Camp completion language requirements
- Free Code Camp Data Visualization Certification
- Free Code Camp Deployment Workflow
- Free Code Camp Front End Development Certification
- Free Code Camp Full Stack Development Certification
- Free Code Camp is an open source community distributed across many platforms
- Free Code Camp JavaScript Style Guide
- Free Code Camp logo
- Free Code Camp's Privacy Policy
- Front End Project Use the Twitchtv JSON API
- Frontend file structure
- Functional Programming Higher Order Functions
- Get info about the current user
- Get Screen Size In Pixels
- Get started with Node_js
- Getting a coding job
- Git Amend Last
- Git Blame
- Git Change the URL of a remote repository
- Git Checkout A Remote Branch
- Git Delete a Branch both locally and remotely
- Git Force Git to overwrite local files on pull
- git merge
- Git Pull Vs Git Fetch
- Git Push Local To Remote Repository
- git rebase
- Git Resources
- Git Shortcut
- Git Undo Redo A Commit
- Gitter
- Gitter Moderation Policy
- global variables
- Go
- Grunt
- Guide Online Contribution
- Guide to Back End Projects Table of Contents
- Guide to Submitting Posts to Free Code Camp Medium Publication
- Gulp Basics
- Help I've Found a Bug
- Help Rooms
- Heroku Deployment Guide
- Higher Order functions
- How Free Code Camp works
- How FreeCodeCamp Nonprofit Projects work
- How GitHub Issue Moderators AKA Issue Mods Work
- How JSONP is different from JSON
- How Long Free Code Camp Takes
- How to add Free Code Camp to my LinkedIn profile
- How to best use the Global Control Shortcuts for Mac
- How to clear specific values from your browser's local storage
- How to clone the FreeCodeCamp website on a Windows pc
- How To Contribute To The Wiki
- How to create a Campsite for your city
- How To Create A Pull Request for Free Code Camp
- How to deploy a website without writing any code at all
- How To Fork And Maintain a Local Instance of Free Code Camp
- How to Get Help on Gitter
- How to get help when you get stuck
- How to get the MEAN stack running locally on OSX
- How To Install Clementine
- How to install Screenhero
- How to know who is in charge of your Campsite on Facebook
- How To Log In To Your Local FCC Site
- how to post code
- How to Rename a Local Branch
- How to share your workspace selfie with FreeCodeCamp on instagram
- How to start when you are stuck (I)
- How to start when you are stuck (II)
- How to start when you are stuck (III)
- How to use the Free Code Camp Wiki
- How you can get to Inbox Zero with Gmail shortcuts
- How you can help to stimulate your city's Campsite on Facebook
- How you can reach the Free Code Camp team to interview them for your publication
- Html and CSS Cheat Sheet
- html elements
- If Free Code Camp is free, how does it make money
- Ignore Files Committed To Git Repo
- IIFE
- Install Django Flask
- Installing WordPress Locally on Mac
- Intro to Yeoman Angular Fullstack Back End Projects
- isLoggedInAsync
- Java
- Java Basics
- Java Introduction
- Java Loops
- Java Resources
- Javascript Callback Functions
- JavaScript Truth Table
- jQuery
- js arguments
- js Array prototype concat
- js Array prototype every
- js Array prototype filter
- js Array prototype forEach
- js Array prototype indexOf
- js Array prototype join
- js Array prototype lastIndexOf
- js Array prototype map
- js Array prototype pop
- js Array prototype push
- js Array prototype reduce
- js Array prototype reverse
- js Array prototype shift
- js Array prototype slice
- js Array prototype some
- js Array prototype sort
- js Array prototype splice
- js Array prototype toString
- js Boolean
- js closures
- JS Comparison Operators
- JS Current URL
- js falsy
- js for in loop
- js for loop
- js for of loop
- js functions
- JS Get Timestamp
- js Global Object
- js immutable
- js loops
- JS Regex Resources
- JS Resources
- js Scopes
- JS Strict Mode
- js String prototype charAt
- js String prototype charCodeAt
- js String prototype concat
- js String prototype indexOf
- js String prototype lastindexOf
- js String prototype match
- js String prototype replace
- js String prototype slice
- js String prototype split
- js String prototype substr
- js String prototype substring
- js String prototype toLowerCase
- js String prototype toUpperCase
- js ternary
- js truthy
- js undefined
- jsonp
- Know it all
- Known Issues With Codepen
- latex
- Learn the basics of the VIM editor
- Linking Your Account with GitHub
- Linux
- List of Free Code Camp city based Campsites
- Loop Protect
- Map
- materializecss framework as a bootstrap alternative
- Math.max
- Math.min
- Math.pow
- medium example wiki article
- More useful APIs
- Mostaganem
- Object.getOwnPropertyNames
- Object.keys
- October 2015 Improvements
- October 2015 Summit Agenda
- Official Free Code Camp Chat Rooms
- ooda
- Other resources that Free Code Camp recommends to nonprofits
- Page redirects using javascript
- Pair programming and why it is special
- parseInt
- Permutations
- Php
- Politica De Honestidad Academica
- Programming Fundamental
- Programming Methodology
- Promises
- Pseudoclassical class definition OOp
- Pull Request Contribute
- PULL_REQUEST_TEMPLATE
- Python
- Python Basics
- Python Functions
- Python Introduction
- Python More Builtin Types
- Python Operators
- Python Resources
- Quick tip keep data in sync
- README
- Reduce made easy
- Refresh Your Browser Cache
- Registering your Nonprofit to Raise Donations through Free Code Camp Commit
- Restrict a page to authenticated users
- RTFM
- Ruby
- Ruby Introduction
- Run Apache Server On A Mac
- Saturday Summit August 2015
- Saturday Summit December 2015
- Saturday Summit November 2015
- Saturday Summit October 2015
- Searching for Your Issue on Github
- Seed data
- Select Issues for Contributing Using Labels
- Setting Up A React ES6 Webpack Project
- Site Improvements August 2015
- Site Improvements October 2015
- Slack
- Spanish Translation Terminology
- staging
- Start Here
- Streaks
- Stream Your Coding Sessions on Twitch.tv
- String.fromCharCode
- String.length
- Swashbuckle Swagger Operation Alphabetical Order
- The main advantages of Free Code Camp
- The Return Early Pattern
- Tips on How To Become A Good Pair Programmer
- topic
- Translating Free Code Camp into Your Native Language
- Translations Guide
- Twitch
- up_and_running_with_sass
- update
- Updates February 11 2016
- using anonymous self executing functions for private namespacing in your js apps
- Using browsec for securing your connection to fcc
- Using Github Pages for your front end development projects
- video demo
- wat
- Web Development in Python
- Web Resources
- What exactly Free Code Camp does
- What pair programming is and why it is special
- What the main advantages of Free Code Camp are
- What the style guide for Algorithms is
- What to do if you speak a language that Free Code Camp does not yet support
- What you will learn, and in what sequence you will learn it
- Why does Free Code Camp use JavaScript instead of Ruby or Python
- Why you need Free Code Camp
- Why You Should Try Pair Programming
- wiki js template
- Wiki Style Guide
- World Language Chat Rooms
- Write and Run ES6 Code in Browser
- writing a markdown file using atom
- Writing great git commit message
- Show 601 more pages…
New to Free Code Camp?
JS Concepts
JS Language Reference
- arguments
- Array.prototype.filter
- Array.prototype.indexOf
- Array.prototype.map
- Array.prototype.pop
- Array.prototype.push
- Array.prototype.shift
- Array.prototype.slice
- Array.prototype.some
- Array.prototype.toString
- Boolean
- for loop
- for..in loop
- for..of loop
- String.prototype.split
- String.prototype.toLowerCase
- String.prototype.toUpperCase
- undefined
Other Links
Clone this wiki locally
Java Basics
Core Concepts
The Java Virtual Machine (JVM)
Java belongs to a family of languages called Compiled Languages (https://en.wikipedia.org/wiki/Compiled_language). Any code written in such a language needs to be converted (compiled) to an intermediate form that can then be understood by the host platform (the OS/platform in which the code runs).
For Java, this intermediate form is called Bytecode which is then interpreted by a runtime called a Java Virtual Machine (JVM). Think of JVM (https://docs.oracle.com/javase/specs/jvms/se7/html/) as a piece of software that does the hard work of running your Java code. It takes care of memory allocation, thread management, garbage collection and so much more. Apart from Java, it also supports (read: able to run) code written in languages such as Groovy, Scala etc.
In Java, code is written and saved as .java
files. The compiler (javac) operates on the java files and generates the equivalent Bytecode (.class
) files. The java
command would now be able to execute the Bytecode stored in the .class
files. More on this later.
The following sections describe some of the basic building blocks of coding in Java.
Variables
Variables store values.
In Java, variables are strongly typed, which means you have to define the type for each variable whenever you declare it. Otherwise, the compiler will throw error at compile time. Therefore, each variable has an associate data type of either :
- Primitive Type :
int
,short
,char
,long
,boolean
,byte
,float
,double
- Wrapper Type :
Integer
,Short
,Char
,Long
,Boolean
,Byte
,Float
,Double
- Object Type:
String
,StringBuilder
,Calendar
,ArrayList
etc.
We made a distinction between Wrapper Type and general Object Type for a reason - wrapper types are closely linked with their primitive counterparts via autoboxing and unboxing; but more on that later.
Typically you can declare variables using the following syntax :
//Primitive Data Type
int i = 10;
// Object Data Type
//initiates an Float object with value 1.0
// variable myFloat now points to the object
Float myFloat = new Float(1.0);
But there are more to these variables, read about them here.
Classes & Objects
Classes are groups of variables and operations on them. A class can have variables, methods (or functions) and constructors (or methods which are used to initiate, more on that later!).
Think of a Class
as a blueprint for creating something concrete. A Class
tells you the 'what' and 'how' an object
of that Class will look like once instantiated
. In essence, it defines properties
(say color, engine capacity) and behavior
(stop, speed up, change gears, honk etc.) for a Car in this case.
Objects are instances of a class. All objects are instances of a certain class. Imagine a class being a "template", which every Object copies to. When you create an Object, basically it creates a new object on the blueprint of a class. Now lets look at this from a little piece of code :
// Car class
public class Car {
// car name
private String name;
// car mannufacturer name
private String manufacturerName;
// constructor
public Car(String name, String man) {
this.name = name;
this.manufacturerName = man;
}
// getter method
public String getName() {
return name;
}
// getter method
public String getManufacturerName() {
return manufacturerName;
}
//setter method
public void setName(String name){
this.name = name;
}
}
Car modelS = new Car("Model S","Tesla");
System.out.println("Full Car Name = " + modelS.getManufacturerName() + " " + modelS.getName());
// prints Tesla Model S
So, Car
is a class, which has the fields or properties name and manufacturerName. modelS
is an object of Car
class. So modelS
also has the same properties and methods.
Access Modifiers
Ok, so if modelS
has all the same properties, I should be able to access name
or manufacturerName
right?
System.out.println(modelS.name);
Results in :
Main.java:13: error: name has private access in Car
System.out.println(modelS.name);
^
1 error
Why? Notice we had mentioned private
before the variable name
in class Car
. This marks the variable as private
to the class which means that the variable cannot be modified or accessed from another class, even if an object of the class is instantiated. So, unless you provide a public setter
method or any other public
method to access the variable, there is no way it's visible to the outside world.
There are other kinds of access modifiers such as public, protected, default etc. Read more about them here.
Constructors
What's the point then? I should be able to store data in it right?
That's when we use either getter (e.g., getName()) / setter (e.g., setName()) methods or in this case constructors to initialize a class. Basically every Java Class has a constructor, which is the method which is called first when any object of the class is initialized. Think of it as a bit of starter code.
When you write a class without any constructor, then Java assumes it has a default constructor :
public class Car {
private String name;
}
Car modelS = new Car();
This initializing with no parameters is a way of calling the default constructor. You can also have a default constructor written yourself this way :
public class Car {
private String name;
public Car() {
name = "Tesla";
}
}
Then, when calling new Car()
, the variable name
will get auto-initialized to "Tesla"
.
Like what Constructor
s can do? Dive into it more here.
Methods
getName()
and getManufacturerName()
are two "Getter" methods we have used here. Notice, unlike JavaScript, we have to define the return type of any method we write, otherwise it will fail at compile time. If you do not want a method to return anything, use void
return type.
public class Car {
private String name;
public void changeName() {
name = "Tesla";
}
}
As with any other language, methods (or functions, if you are here from JS world) are used often for their modularity and reusability. Read more about them here.
Inheritance
So great you have successfully created a Car class. But, wait, aren't Tesla cars supposed to be electric variants? I want an Electric car class, but it also should have the properties of the original Car
class.
Solution : Inheritance. Java provides a neat way to "inherit" parent properties :
public class Car {
private String name;
private String manufacturerName;
public Car(String name, String man) {
this.name = name;
this.manufacturerName = man;
}
// Getter method
public String getName() {
return name;
}
// Getter method
public String getManufacturerName() {
return manufacturerName;
}
}
public class ElectricCar extends Car {
public ElectricCar(String name, String man) {
super(name, man);
}
public void charge() {
System.out.println("Charging ...");
}
}
ElectricCar modelS = new ElectricCar("Model S","Tesla");
// prints Tesla
System.out.println(modelS.getName());
// prints Charging ...
modelS.charge();
See here that the class ElecticCar
inherits or extends
the public methods from Car
class, as well as has its own methods and properties. Cool way to pass on information!
Also notice the usage of super keyword here. Since our Car
class had a constructor, so we have to initialize that constructor from the child class as well. We do that using the super
keyword. Read more about Inheritance here.
Interfaces
But wait, my manager has given me a set of strict specifications every class to create, but has told me you can implement it in whichever way you want. Incidentally, Java has a nifty feature of Interfaces which does exactly that!
interface Car {
public String getName();
public String getManufacturerName();
}
class ElectricCar implements Car {
private String name;
private String manufacturerName;
public ElectricCar(String name, String man) {
this.name = name;
this.manufacturerName = man;
}
public void charge() {
System.out.println("Charging ...");
}
// Getter method
public String getName() {
return name;
}
// Getter method
public String getManufacturerName() {
return manufacturerName;
}
}
So interface basically binds you to a contract to follow, where you must implement all the methods. If you don't, the compiler will complain! Know more about the awesome power of Inheritance here.
Basic Operations
Java supports the following operations on variables:
- Arithmetic :
Addition(+)
,Subtraction(-)
,Multiplication(*)
,Division(/)
,Modulus(%)
,Increment(++)
,Decrement(--)
. - String concatenation:
+
can be used for String concatenation but subtraction-
on a String is not a valid operation. - Relational:
Equal to(==)
,Not Equal to (!=)
,Greater than(>)
,Less than(<)
,Greater than or equal to(>=)
,Less than or equal to(<=)
, - Bitwise:
Bitwise And(&)
,Bitwise Or(|)
,Bitwise XOR(^)
,Bitwise Compliment(~)
,Left shift(<<)
,Right Shift (>>)
,Zero fill right shift (>>>)
- Logical:
Logical And (&&)
,Logical Or(||)
,Logical Not (!)
- Assignment:
=
,+=
,-=
,*=
,/=
,%=
,<<=
,>>=
,&=
,^=
,|=
- Others:
Conditional/Ternary(?:)
,instanceof
While most of the operations are self explanatory, the Conditional (Ternary) Operator works as follows:
expression that results in boolean output ? return this value if true : return this value if false
For e.g:
int x = 10;
int y = (x == 10) ? 5 : 9; <-- y will equal 5 since the expression x == 10 evaluates to true
The instanceof
operator
The instanceof
operator allows you to check the validity of a IS A
relationship. If at any point of time, we are not sure about this and we want to validate this at runtime, we can do the following:
//assuming vehicle is an instance of Class `Car` the expression inside the 'if' will return true
if( vehicle instanceof Car ) {
//do something if vehicle is a Car
}
Control Flow
Control flow statements are exactly what the term means. They are statements that alter execution flow based on decisions, loops and branching so that the program can conditionally execute blocks of code.
Primarily, Java has the following constructs for flow control:
if
if( <expression that results in a boolean>) {
//code enters this block if the above expression is 'true'
}
if...else
if( <expression that results in a boolean> ){
//execute this block if the expression is 'true'
} else{
//execute this block if the expression is 'false'
}
switch
Switch is an alternative for the if...else
construct when there are multiple values and cases to check against.
switch( <integer / String / Enum > ){
case <int/String/Enum> : <statements>
break;
case <int/String/Enum> : <statements>
default: <statements>
}
Note: The program flow falls through
the next case
if the break
statement is missing. For e.g. Let's say you say the standard 'Hello' to everyone at office, but you are extra nice to the girl who sits next to you and sound grumpy to your boss. The way to represent would be something like:
switch(person){
case 'boss' : soundGrumpy();
break;
case 'neighbour' : soundExtraNice();
case 'colleague': soundNormal();
break;
default :
soundNormal();
}
Note: The `default` case runs when none of the `case` matches. Remember that when a case has no `break` statement, it `falls through` to the next case and will continue to the subsequent `cases` till a `break` is encountered.
nested statements
Any of the previous control flows can be nested. Which means you can have nested if
,if..else
and switch..case
statements. i.e., you can have any combination of these statements within the other and there is no limitation to the depth of nesting
.
For example, let's consider the following scenario:
If you have less than 25 bucks, you get yourself a cup of coffee. If you have more than 25 bucks but less than 60 bucks, you get yourself a decent meal. If you have more than 60 bucks but less than a 100, you get yourself a decent meal along with a glass of wine. However, when you have more than a 100 bucks, depending on who you are with, you either go for a candle lit dinner (with your wife) or you go to a sports bar (with your friends).
One of the ways to represent this will be:
if(cash<25){
getCoffee();
}else if(cash<60){
getDecentMeal();
}else if(cash<100){
getDecentMeal();
getGlassOfWine();
}else{
switch(company){
case "wife" : candleLitDinner();
break;
case "friends" : meetFriendsAtSportsBar();
break;
}
}
Loop constructs
Remember that one friend who goes on and on about something? Well, that's a loop
right there for you. In Java
, a developer can represent the action of doing something repeatedly
using the following constructs:
while
Loop
The while
loop executes a group of statements / single statement till a condition evaluates to true
. For instance:
while(some_condition_is_true){
//do something
}
Note
: For the while
loop to start executing, you'd require the condition to be true. However, to exit the loop you must do something as given below (otherwise the loop will execute forever. Practically, it will run till the JVM runs out of memory).
while(i<10){
System.out.println("i :"+ i);
i++; //<- This ensures that value of i in the while condition will become more than 10 at some point thereby breaking the condition and exiting the loop.
}
Can you now guess the output of the following snippet?
int i = 0;
while( i < 10 ){
System.out.println("Value of i is : " + i);
i++;
}
for
Loop
There are 2 of these:
- Normal
for
loop
for( initialize variable; condition; modify variable ){
//perform action
}
For e.g.
for(int i=0; i<10; i++){
System.out.println("The value of is : " + i);
}
- Enhanced
for
loop
Well, this came into existence in Java 5. It helps when you are required to iterate over a list of items and perform some action like so:
//assuming nameList is a List of names that are actually Strings
for( String name : nameList ){
SYstem.out.println(name);
}
do..while
Loop
The do..while
loop is a special case of the while
loop wherein the group of statements is guranteed to run atleast once before checking for a given condition. Confused? Ok, the follwing example should clear things up.
Can you guess the output of the following code snippet?
int i=10;
do{
System.out.println("The value of i is " + i);
i--;
}while( i >= 10 );
Remember
: The condition of a do-while
loop is checked After the code body is executed once.
Now that you have some idea of basic syntax, let's delve into some of the most relevant and commonly used data types which will help you to develop programs in Java.
Strings
Strings, as you might be already aware, are a sequence of characters. In Java, a String
is an Object
.
String course = "FCC";
System.out.println( course instanceof Object); //<- This prints 'true'
You can create a String in the following ways:
-
String str = "I am a String";
//This is a String literal -
String str = new String("I am a String")
; //This is a String Object
You might be thinking: What's the difference between the two?
Well, using the new
keyword gurantees that a new String
object will be created and a new memory location will be allocated in the Heap
memory (Click here to learn more)[https://docs.oracle.com/cd/E13150_01/jrockit_jvm/jrockit/geninfo/diagnos/garbage_collect.html]. You see, Java takes care of memory allocation and collecting unused memory in the background - among other things. However, in this case, it's good to be aware about the difference so that you can write code that can help the JVM make appropriate optimizations.
The following snippet will make things more clearer. The objective is to understand: How many String objects are created?
String str = "This is a string";
String str2 = "This is a string";
String str3 = new String("This is a string");
System.out.println( str == str2 ); //This prints true
System.out.println( str == str3 ); //This prints false
The answer is: 2 String objects are created.
You see, the creators of the JVM are pretty smart. They figured that Strings differ mostly in terms of its content
. When you create a String literal, the JVM internally checks, what is known as the String pool
, to see if it can find a similar (content wise) String object. If it finds it, it returns the same reference. Otherwise, it just goes ahead and creates a new String object in the pool so that the same check can be performed in the future.
However, whenever you use the new
keyword, it no longer performs this check. So, there could be a 1000s of String objects with the same content and yet, it'll go ahead and create a new String - using up additional memory. This is precisely why it's a good practice to use String literals
instead of using the new
keyword as much as possible.
Learn to code and help nonprofits. Join our open source community in 15 seconds at http://freecodecamp.com
Follow our Medium blog
Follow Quincy on Quora
Follow us on Twitter
Like us on Facebook
And be sure to click the "Star" button in the upper right of this page.