Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- These are general Java programming tutorials provided for free on YouTube:
- http://thenewboston.org/list.php?cat=31
- Java Syntax
- I would personally watch as many as I could until I feel comfortable with Java. Once you get comfortable with Java, you can start Android programming:
- http://thenewboston.org/list.php?cat=6
- I am visual so I like learning by watching videos. If you would like to read instead, there are many other websites. For example: http://docs.oracle.com/javase/tutorial/
- filenames must end with .java
- javac classname.java
- java classname
- error: Class names, 'variables.txt', are only accepted if annotation processing is explici
- tly requested
- 1 error
- C:\JAVA>
- When they compile, the output file is .class and the filename corresponds with the class name in the file.
- **Make sure your class is named properaly (class java ...)
- + concatenation operator
- public class
- public method
- dot seperator
- class.method(aurgument );
- public class tuna {
- public void simpleMessage() {
- System.out.println("This is another class");
- }
- }
- public class apples {
- public static void main(String[] args) {
- tuna tunaObject = new tuna();
- tunaObject.simpleMessage();
- }
- }
- System.out.printf("Your first gf was %s", getName());
- System.out.println //prints endline breaks
- System.out.print(tuna); //continues from the previous
- public class tuna {
- public void simpleMessage(String name) {
- System.out.println("Hello " + name);
- }
- }
- if/else statments
- if (argument)
- dothis...;
- else if (argument)
- dothat...;
- ...
- else
- doother...;
- Nesting
- if () {
- if () {
- ...
- }
- }
- Average
- import java.util.Scanner;
- class apples {
- public static void main(String[] args) {
- Scanner input = new Scanner(System.in);
- int total = 0;
- int grade;
- int average;
- int counter = 0;
- while (counter < 10) {
- grade = input.nextInt();
- total = total + grade;
- counter++;
- }
- average = total/10;
- System.out.println("Your average is " + average);
- }
- }
- Arrays
- int bucky[] = new int[10];
- int bucky[] = {2,4,5,7,9}; array initializer (subscript/indexer)
- bucky[0]=87;
- bucky[1]=543;
- bucky[9]=65;
- System.out.println(bucky[1]);
- Index
- System.out.println("Index\tValue");
- int bucky[] = {32, 48, 18, 54, 2};
- for(int counter=0; counter < bucky.length; counter++) {
- System.out.println(counter + "\t" + bucky[counter]);
- }
- Total Sum
- int bucky[] = {21, 16, 86, 21, 3};
- int sum=0;
- for (int counter=0; counter<bucky.length; counter++) {
- sum+=bucky[counter];
- }
- System.out.println("The sum of these numbers is " + sum);
- Conditional Operators
- System.out.println(age > 50 ? "You are old" : "You are Young");
- import java.util.Scanner;
- public class apples {
- public static void main(String[] args) {
- Scanner input = new Scanner(System.in);
- tuna tunaObject = new tuna();
- System.out.println("Enter your name here: ");
- String name = input.nextLine();
- tunaObject.simpleMessage(name);
- }
- }
- toString
- class apples {
- public static void main(String[] args) {
- potpie potObject = new potpie(4,5,6);
- }
- }
- public class potpie {
- private int month;
- private int day;
- private int year;
- public potpie(int m, int d, int y) {
- month = m;
- day = d;
- year = y;
- System.out.printf("The constructor for this is %s\n", this);
- }
- public String toString() {
- return String.format("%d/%d/%d", month, day, year);
- }
- }
- Composition
- class apples {
- public static void main(String[] args) {
- potpie potObject = new potpie(4,5,6);
- tuna tunaObject = new tuna("Greg", potObject);
- System.out.println(tunaObject);
- }
- }
- public class tuna {
- private String name;
- private potpie birthday;
- public tuna(String theName, potpie theDate) {
- name = theName;
- birthday = theDate;
- }
- public String toString() {
- return String.format("My name is %s, my birthday is %s", name, birthday);
- }
- }
- public class potpie {
- private int month;
- private int day;
- private int year;
- public potpie(int m, int d, int y) {
- month = m;
- day = d;
- year = y;
- System.out.printf("The constructor for this is %s\n", this);
- }
- public String toString() {
- return String.format("%d/%d/%d", month, day, year);
- }
- }
- Type-safe enumerations (enum types)
- JDK 1.5 is not available, type-safe enumerations can still be implemented as a regular Java class
- Enumeration
- class apples {
- public static void main(String[] args) {
- for (tuna people: tuna.values())
- System.out.printf("%s\t%s\t%s\n", people, people.getDesc(), people.getYear());
- }
- }
- public enum tuna {
- bucky("nice", "22"),
- kelsey("cutie", "10"),
- julia("bigmistake", "12");
- private final String desc;
- private final String year;
- tuna(String description, String birthday) {
- desc = description;
- year = birthday;
- }
- public String getDesc() {
- return desc;
- }
- public String getYear() {
- return year;
- }
- }
- EnumSet Range
- import java.util.EnumSet;
- class apples {
- public static void main(String[] args) {
- for (tuna people: tuna.values())
- System.out.printf("%s\t%s\t%s\n", people, people.getDesc(), people.getYear());
- System.out.println("\nAnd for the range of constants!!!\n");
- for (tuna people: EnumSet.range(tuna.kelsey, tuna.candy))
- System.out.printf("%s\t%s\t%s\n", people, people.getDesc(), people.getYear());
- }
- }
- public enum tuna {
- bucky("nice", "22"),
- kelsey("cutie", "10"),
- julia("bigmistake", "12"),
- nicole("italian", "13"),
- candy("different", "14"),
- erin("I wish", "16");
- private final String desc;
- private final String year;
- tuna(String description, String birthday) {
- desc = description;
- year = birthday;
- }
- public String getDesc() {
- return desc;
- }
- public String getYear() {
- return year;
- }
- }
- Static
- Are defined the same the whole time the program is run, and can be accessed globally, using the class name reference.
- class apples {
- public static void main(String[] args) {
- tuna member1 = new tuna("Meagan", "Fox");
- tuna member2 = new tuna("Natalie", "Portman");
- tuna member3 = new tuna("Taylor", "Swift");
- System.out.println();
- System.out.println(member2.getFirst());
- System.out.println(member2.getLast());
- System.out.println(member2.getMembers());
- System.out.println();
- System.out.println(tuna.getMembers());
- }
- }
- public class tuna {
- private String first;
- private String last;
- private static int members = 0;
- public tuna(String fn, String ln) {
- first = fn;
- last = ln;
- members++;
- System.out.printf("Constructor for %s %s, members in the club: %d\n", first, last, members);
- }
- public String getFirst () {
- return first;
- }
- public String getLast () {
- return last;
- }
- public static int getMembers() {
- return members;
- }
- }
- Final
- class apples {
- public static void main(String[] args) {
- tuna tunaObject = new tuna(10);
- for(int i = 0; i < 5; i++) {
- tunaObject.add();
- System.out.printf("%s", tunaObject);
- }
- }
- }
- public class tuna {
- private int sum;
- private final int NUMBER; //(final) initializer ( = 2; )
- public tuna(int x) {
- NUMBER = x;
- }
- public void add() {
- sum+=NUMBER;
- }
- public String toString() {
- return String.format("sum = %d\n", sum);
- }
- }
- Building Objects for Constructors
- Variable length arguments
- class apples {
- public static void main(String[] args) {
- //tuna tunaObject = new tuna();
- //System.out.println(tunaObject.toMilitary());
- //System.out.println(tunaObject.toString());
- //tunaObject.setTime(13, 27, 6);
- //System.out.println(tunaObject.toMilitary());
- //System.out.println(tunaObject.toString());
- tuna tunaObject = new tuna();
- tuna tunaObject2 = new tuna(5);
- tuna tunaObject3 = new tuna(5,13);
- tuna tunaObject4 = new tuna(5,13,43);
- System.out.printf("%s\n", tunaObject.toMilitary());
- System.out.printf("%s\n", tunaObject2.toMilitary());
- System.out.printf("%s\n", tunaObject3.toMilitary());
- System.out.printf("%s\n", tunaObject4.toMilitary());
- }
- }
- public class tuna {
- private int hour;
- private int minute;
- private int second;
- public tuna() {
- this(0,0,0);
- }
- public tuna(int h) {
- this(h,0,0);
- }
- public tuna(int h, int m) {
- this(h,m,0);
- }
- public tuna(int h, int m, int s) {
- setTime(h,m,s);
- }
- public void setTime(int h, int m, int s) {
- setHour(h);
- setMinute(m);
- setSecond(s);
- }
- public void setHour (int h) {
- hour = ((h >=0 && h < 24) ? h : 0);
- }
- public void setMinute (int m) {
- minute = ((m >=0 && m < 60) ? m : 0);
- }
- public void setSecond (int s) {
- second = ((s >=0 && s < 60) ? s : 0);
- }
- public int getHour () {
- return hour;
- }
- public int getMinute () {
- return minute;
- }
- public int getSecond () {
- return second;
- }
- public String toMilitary() {
- return String.format("%02d:%02d:%02d", getHour(), getMinute(), getSecond());
- }
- }
- Inheritance (Extends)
- Can be used on multiple levels (hierarchical) with inheritance
- only public methods can be inherited.
- tuna extends potpie
- potpie extends food
- class apples {
- public static void main(String[] args) {
- tuna tunaObject = new tuna();
- potpie potObject = new potpie();
- tunaObject.eat();
- potObject.eat();
- }
- }
- public class tuna extends food {
- public void eat() {
- System.out.println("I am the new method of tuna");
- }
- }
- public class potpie extends food {
- }
- public class food {
- public void eat() {
- System.out.println("I am the eat methods");
- }
- }
- Constructor
- method must match the same name (method name) as the class name, inorder for it to be considered a constructor
- Math Operators
- ++pre-increment variable (-- subtraction)
- increments the variable before it returns
- post-increment++ variable (-- subtraction)
- increments the variable after it returns
- increment assign operator
- variable += 5
- Logical Operator (Multiple Test)
- && AND
- || OR
- var1 && var2 (both have to be true)
- var1 || var2 (either must be true, the other maybe false)
- int whole numbers
- int + int = sum
- int * int = product
- int / int = divide
- int % int = modulus (remainder)
- int var = 1;
- int var_name(, var_name2, var_name3...);
- var_name = 1;
- double
- fraction/decimal numbers
- String variable = "value";
- "...it can only do one or the other."
- if (condition) {
- //condition is true
- testing
- != does not equal
- === absolute equal
- >= greater than or equal to
- <= less than or equal to
- > greater than
- < less than
- block
- } else {
- //condition is false
- }
- While Loop
- while (counter < 10) {
- System.out.println(counter);
- counter++;
- }
- Do-while loop
- int counter = 0;
- do {
- System.out.println(counter);
- counter++;
- } while (counter <= 10);
- Java Methods (declare after being used?)
- public static void main(String[] args) {
- int bucky[]={3,4,5,6,7};
- change(bucky);
- for(int y:bucky)
- System.out.println(y);
- }
- public static void change(int x[]) {
- for (int counter = 0; counter < x.length; counter++ ) {
- x[counter] += 5;
- }
- }
- Java Local Variables
- public void setTime(int hour, int minute, int second) {
- this.hour = 4;
- this.minute = 5;
- this.second = 6;
- }
- Java Global Variables
- public int hour = 1;
- public int minute = 2;
- public int second = 3'
- Java Multi-Array
- int firstarray[][]={{8,9,10,11}, {12, 13, 14, 15}};
- int secondarray[][]={{30,31,32,33},{43},{4,5,6}};
- firstarray[0][1]; //[col][row]
- Java Multi-Array Display
- public static void main(String[] args) {
- int firstarray[][]={{8,9,10,11}, {12, 13, 14, 15}};
- int secondarray[][]={{30,31,32,33},{43},{4,5,6}};
- //firstarray[0][1]; //[col][row]
- System.out.println("This is the first array");
- display(firstarray);
- System.out.println("This is the second array");
- display(secondarray);
- }
- public static void display(int x[][]) {
- for (int row=0; row < x.length; row++) {
- for (int column=0; column < x[row].length; column++ ) {
- System.out.print(x[row][column]+"\t");
- }
- System.out.println();
- }
- }
- Variable Length Arguments
- public static void main(String[] args) {
- System.out.println(average(43,6,26,23));
- }
- public static int average(int...numbers) {
- int total = 0;
- for (int x:numbers)
- total+=x;
- return total/numbers.length;
- }
- For loop
- for(int counter = 1; counter <= 10; counter++) //counter+=3 step by 3, 6, 9...
- Enhanced For Loop
- int bucky[] = {3,4,5,6,7};
- int total = 0;
- for (int x: bucky) { total +=x; }
- System.out.println(total);
- Random Dice
- import java.util.Random;
- Random dice = new Random();
- int number;
- for(int counter=1; counter <= 10; counter++) {
- number = 1+dice.nextInt(6);
- System.out.println(number + " ");
- }
- Random Face/Dice Generator
- Random rand = new Random();
- int freq[] = new int[7];
- for (int roll = 1; roll < 1000; roll++ ) {
- ++freq[1+rand.nextInt(6)];
- }
- System.out.println("Face\tFrequency");
- for (int face=1; face<freq.length; face++) {
- System.out.println(face+"\t"+freq[face]);
- }
- Time
- private int hour;
- private int minute;
- private int second;
- public void setTime(int h, int m, int s) {
- hour = ((h >= 0 && h < 24) ? h : 0);
- minute = ((m >= 0 && m < 60) ? m : 0);
- second = ((s >= 0 && s < 60) ? s : 0);
- }
- public String toMilitary() {
- return String.format("%02d:%02d:%02d", hour, minute, second );
- }
- public String toString() {
- return String.format("%d:%02d:%02d %s", ((hour==0 || hour==12) ? 12 : hour%12), minute, second, (hour < 12 ? "AM" : "PM"));
- }
- public static void main(String[] args) {
- tuna tunaObject = new tuna();
- System.out.println(tunaObject.toMilitary());
- tunaObject.setTime(13, 27, 6);
- System.out.println(tunaObject.toMilitary());
- }
- Compound Interest
- A=P(1+R)^n
- A = Amount
- P = Principle
- * (1+R = Rate) ^ (power) n = Years
- double amount;
- double principal = 10000;
- double rate = .01;
- for (int day = 1; day <= 20; day++) {
- amount = principal*Math.pow(1 + rate, day);
- System.out.println(day + " " + amount);
- }
- System.out.println(Math.abs());
- abs = absolute value (-26.7 == 26.7)
- ceil = ceiling (7.4 == 8.0)
- floor = floor (7.8 == 7.0)
- max = maximum (8.6, 5.2 == 8.6)
- min = minimum (8.6, 5.2 == 5.2)
- pow = power (5, 3 == 125)
- sqrt = square root (9 == 3)
- GUI
- import javax.swing.JOptionPane;
- class apples {
- public static void main(String[] args) {
- String fn = JOptionPane.showInputDialog("Enter first number");
- String sn = JOptionPane.showInputDialog("Enter second number");
- int num1 = Integer.parseInt(fn);
- int num2 = Integer.parseInt(sn);
- int sum = num1 + num2;
- JOptionPane.showMessageDialog(null, "The answer is " +sum, "the title", JOptionPane.PLAIN_MESSAGE);
- }
- }
- GUI with JFrame
- import javax.swing.JFrame;
- class apples {
- public static void main(String[] args) {
- tuna bucky = new tuna();
- bucky.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- bucky.setSize(275,180);
- bucky.setVisible(true);
- }
- }
- import java.awt.FlowLayout;
- import javax.swing.JFrame;
- import javax.swing.JLabel;
- public class tuna extends JFrame {
- private JLabel item1;
- public tuna() {
- super("The Title Bar");
- setLayout(new FlowLayout());
- item1 = new JLabel("This is a sentence");
- item1.setToolTipText("This is going to show up on hover.");
- add(item1);
- }
- }
- Event Handling
- import javax.swing.JFrame;
- class apples {
- public static void main(String[] args) {
- tuna bucky = new tuna();
- bucky.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- bucky.setSize(350,100);
- bucky.setVisible(true);
- }
- }
- import java.awt.FlowLayout;
- import java.awt.event.ActionListener;
- import java.awt.event.ActionEvent;
- import javax.swing.JFrame;
- import javax.swing.JTextField;
- import javax.swing.JPasswordField;
- import javax.swing.JOptionPane;
- public class tuna extends JFrame {
- private JTextField item1;
- private JTextField item2;
- private JTextField item3;
- private JPasswordField passwordField;
- public tuna() {
- super("The Title Bar");
- setLayout(new FlowLayout());
- item1 = new JTextField(10);
- add(item1);
- item2 = new JTextField("Enter text here");
- add(item1);
- item3 = new JTextField("uneditable", 20);
- item3.setEditable(false);
- add(item3);
- passwordField = new JPasswordField("mypass");
- add(passwordField);
- thehandler handler = new thehandler();
- item1.addActionListener(handler);
- item2.addActionListener(handler);
- item3.addActionListener(handler);
- passwordField.addActionListener(handler);
- }
- private class thehandler implements ActionListener {
- public void actionPerformed(ActionEvent event) {
- String string = "";
- if (event.getSource() == item1)
- string = String.format("field 1: %s", event.getActionCommand());
- else if(event.getSource() == item2)
- string = String.format("field 2: %s", event.getActionCommand());
- else if(event.getSource() == item3)
- string = String.format("field 3: %s", event.getActionCommand());
- else if(event.getSource() == passwordField)
- string = String.format("password field is : %s", event.getActionCommand());
- JOptionPane.showMessageDialog(null, string);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement