πŸ“˜ CodingMarble Learn

Java Programming Basics

Java is a strongly typed, object-oriented language. Code is compiled to bytecode that runs on the Java Virtual Machine (JVM), so the same program runs on any computer. Every value has a type (int, double, char, boolean, String). Operators compute, if/switch choose, and for/while loops repeat. Arrays hold many values of one type, counted from 0. A class is a blueprint and new makes objects. Exceptions handle errors, wrapper classes turn primitives into objects, and threads let a program do several jobs at once.

🎬 Step-by-step story

  1. A variable is a box in memory. Every box has a type: int whole number, double decimal, char one letter, boolean true/false.
  2. Operators combine values from boxes: sum = a + b. The answer goes into a new box.
  3. A for loop: if the condition i < 4 is true, do the work, add 1 to i, then check again. When it is false, the loop stops.
  4. An array is a row of boxes of one type. Counting starts at 0: the first box is arr[0].
  5. A class is a blueprint. Writing new makes a fresh object from it, each with its own values.
  6. Try it: change n. The loop fills arr[i] = i*i. Press "new Student" to make more objects.

Tip: drag the 3D scene to turn it. Use two fingers to zoom.

πŸ€” Common doubts, cleared

Why must I tell Java the type of every variable?

The type decides how big the box is and what you can do with it. Java checks types before running, catching many mistakes early.

Why is 7 / 2 equal to 3?

Both numbers are int, so the answer is an int box and the decimal part is dropped. Make one a double (7.0 / 2) to get 3.5.

When does a for loop stop?

It checks the condition before every lap. The first time it is false (i = 4 here), the loop ends. Watch the counter in step 3.

Why does an array start at 0?

The index means "how many boxes from the start". The first box is 0 steps away, so it is arr[0].

If two objects come from one class, do they share values?

No. Each new object gets its own copy of the fields (unless the field is static). See each green box with its own name and marks.

What happens if I change n so the array is shorter?

arr.length changes, so the loop runs fewer times and never goes past the last index.

What Java is and how a program runs

Java is a general-purpose language created in 1995. Its big idea: write once, run anywhere.

  1. You write source code in a file Hello.java.
  2. The compiler javac turns it into bytecode (Hello.class).
  3. The JVM (Java Virtual Machine) runs the bytecode on any computer.
public class Hello {
  public static void main(String[] args) {
    System.out.println("Hello, world");
  }
}

Every program starts at main. Statements end with a semicolon; blocks sit inside { }. Java is case-sensitive: Age and age are different names. Comments: // one line and /* many lines */.

Data types, variables and constants

A variable is a named box in memory. You must give its type before use: int marks = 85;

TypeHoldsSize
byte, short, int, longwhole numbers1, 2, 4, 8 bytes
float, doubledecimals4, 8 bytes
charone Unicode character, e.g. 'A'2 bytes
booleantrue or false-

These 8 are primitive types. String, arrays and objects are reference types. A final variable is a constant: final double PI = 3.14159;. Rules for names: start with a letter, _ or $, no spaces, not a keyword like class.

Type casting: small to big is automatic (double d = 5;); big to small needs a cast (int n = (int) 7.9; gives 7).

Operators

Precedence: * / % before + βˆ’; use brackets to be clear.

Control flow: if, switch and loops

if (marks >= 90) grade = 'A';
else if (marks >= 75) grade = 'B';
else grade = 'C';

switch picks one of many fixed values (use break to stop falling into the next case).

Example: sum of 1 to 10: int s = 0; for (int i = 1; i <= 10; i++) s += i; gives 55.

Arrays and strings

An array stores many values of one type: int[] m = {70, 85, 92}; or int[] m = new int[3];. Index starts at 0, so the last index is m.length βˆ’ 1. Going past it throws ArrayIndexOutOfBoundsException. A 2-D array is a table: int[][] t = new int[3][4];.

A String is an object holding text. Strings are immutable: methods return a new string.

For a lot of joining inside loops, use StringBuilder.

OOP and class design

A class is a blueprint with fields (data) and methods (actions). An object is one thing made from it with new.

class Student {
  private String name; private int marks;
  Student(String n, int m) { name = n; marks = m; }  // constructor
  boolean passed() { return marks >= 33; }
}
Student s = new Student("Asha", 60);

Exceptions and assertions

An exception is an error event at run time, such as dividing an integer by zero or opening a missing file. Handle it so the program does not crash:

try { int r = a / b; }
catch (ArithmeticException e) { System.out.println("Cannot divide by zero"); }
finally { System.out.println("Done"); }

Checked exceptions (e.g. IOException) must be caught or declared with throws; unchecked ones (e.g. NullPointerException) come from programming mistakes. You can raise one with throw.

An assertion checks something you believe must be true while testing: assert marks >= 0 : "marks negative";. Assertions are off by default and turned on with java -ea; never use them to check user input.

Wrapper classes and threads

Wrapper classes wrap a primitive in an object: int β†’ Integer, double β†’ Double, char β†’ Character, boolean β†’ Boolean. Collections like ArrayList<Integer> need objects. Java converts automatically (autoboxing and unboxing). Useful methods: Integer.parseInt("42"), Double.parseDouble("2.5"), Character.isDigit(c).

A thread is a separate path of work inside one program, so it can, for example, download a file while the screen stays responsive. Create one by extending Thread or implementing Runnable, then call start() (not run()). States: new β†’ runnable β†’ running β†’ waiting/blocked β†’ terminated. When threads share data, synchronized stops them changing it at the same moment.

Try it

In the 3D, set n = 6 and predict arr[5] before you look (it is 25). Then on any computer with Java, type a program that prints the 7 times table with a for loop, and change it to stop at 7 Γ— 5 using break.

Key formulas and definitions

Worked examples

1. What does this print? int a = 17, b = 5; System.out.println(a / b + " " + a % b);

a / b with integers is 3 (decimal dropped) and a % b is 2. Output: 3 2.

2. Write a loop that adds all even numbers from 2 to 20.

int s = 0; for (int i = 2; i <= 20; i += 2) s += i; The total is 2 + 4 + … + 20 = 110.

3. Find the largest value in int[] m = {45, 88, 67, 91, 30}.

int max = m[0]; for (int i = 1; i < m.length; i++) if (m[i] > max) max = m[i]; Trace: 45 β†’ 88 β†’ 88 β†’ 91 β†’ 91. Answer 91.

4. What happens with: String s = "Java"; System.out.println(s.charAt(4));

Valid indexes are 0 to 3, so charAt(4) throws StringIndexOutOfBoundsException at run time.

5. Design a class BankAccount with a private balance, a deposit method and a withdraw method that refuses to go below zero.

class BankAccount { private double balance; void deposit(double x) { if (x > 0) balance += x; } boolean withdraw(double x) { if (x <= balance) { balance -= x; return true; } return false; } double getBalance() { return balance; } } Private balance plus checks is encapsulation.

6. Convert the text "250" to a number, add 50 and print it, handling bad input.

try { int n = Integer.parseInt("250"); System.out.println(n + 50); } catch (NumberFormatException e) { System.out.println("Not a number"); } prints 300.

Common mistakes

Practice quiz

1. Java source code is compiled into:
2. Which type stores true or false?
3. For int[] a = new int[5], the last index is:
4. Which keyword creates an object?
5. Integer is the wrapper class of:

Practice: answer these yourself

Type or choose your answer, then press Check. Use a hint if you are stuck; the full solution appears after you answer.

Frequently asked questions

Is Java hard for beginners?

It needs a little more typing than Python, but its strict types and clear structure help you learn good habits. Start with variables, if and loops, then classes.

What is the difference between JDK, JRE and JVM?

The JVM runs bytecode; the JRE is the JVM plus standard libraries; the JDK is the JRE plus tools like the javac compiler for writing programs.

Is Java the same as JavaScript?

No. They are different languages with similar names. Java is compiled to bytecode and strongly typed; JavaScript mainly runs in web browsers.

Where this is taught

CBSE (India)Class 11Fundamentals of Java
CBSE (India)Class 12Fundamentals of Java Programming

Learn first

Learn next

Related lessons

All Computer Science lessons